Add WebGL gradient shimmer background
Port of helium-prism's GradientShimmer to React on top of ogl, with intro and emphasize handles and reduced-motion support. Adds the ogl dependency and the shimmer styles. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b471e00699
commit
5db51ca156
5 changed files with 1318 additions and 0 deletions
3
bun.lock
3
bun.lock
|
|
@ -22,6 +22,7 @@
|
||||||
"motion": "^12.43.0",
|
"motion": "^12.43.0",
|
||||||
"next": "16.0.10",
|
"next": "16.0.10",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
|
"ogl": "^1.0.11",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
"radix-ui": "^1.6.7",
|
"radix-ui": "^1.6.7",
|
||||||
"react": "19.2.1",
|
"react": "19.2.1",
|
||||||
|
|
@ -1229,6 +1230,8 @@
|
||||||
|
|
||||||
"object.values": ["object.values@1.2.1", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0" } }, "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA=="],
|
"object.values": ["object.values@1.2.1", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0" } }, "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA=="],
|
||||||
|
|
||||||
|
"ogl": ["ogl@1.0.11", "", {}, "sha512-kUpC154AFfxi16pmZUK4jk3J+8zxwTWGPo03EoYA8QPbzikHoaC82n6pNTbd+oEaJonaE8aPWBlX7ad9zrqLsA=="],
|
||||||
|
|
||||||
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
|
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
|
||||||
|
|
||||||
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
|
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,7 @@
|
||||||
"motion": "^12.43.0",
|
"motion": "^12.43.0",
|
||||||
"next": "16.0.10",
|
"next": "16.0.10",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
|
"ogl": "^1.0.11",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
"radix-ui": "^1.6.7",
|
"radix-ui": "^1.6.7",
|
||||||
"react": "19.2.1",
|
"react": "19.2.1",
|
||||||
|
|
|
||||||
|
|
@ -149,3 +149,48 @@
|
||||||
@apply bg-background text-foreground;
|
@apply bg-background text-foreground;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* GradientShimmer (src/components/gradient-shimmer.tsx). Colors must be hex:
|
||||||
|
the renderer parses them through a 2D canvas context. */
|
||||||
|
.gradient-shimmer {
|
||||||
|
--shimmer-alpha: 0.35;
|
||||||
|
--shimmer-grain-alpha: 0.4;
|
||||||
|
--shimmer-grain-luminance: 144;
|
||||||
|
--shimmer-grain-contrast: 96;
|
||||||
|
--shimmer-grain-saturation: 32;
|
||||||
|
--shimmer-intro-alpha: 0.6;
|
||||||
|
--shimmer-speed-up-shine-boost: 0.15;
|
||||||
|
--shimmer-start: #131316;
|
||||||
|
--shimmer-highlight: #5d8a2e;
|
||||||
|
|
||||||
|
display: block;
|
||||||
|
z-index: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
opacity: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
image-rendering: pixelated;
|
||||||
|
transition: opacity 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gradient-shimmer.visible {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gradient-shimmer.fallback {
|
||||||
|
background: var(--shimmer-start);
|
||||||
|
}
|
||||||
|
|
||||||
|
.gradient-shimmer.background {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
width: 100vw;
|
||||||
|
height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.gradient-shimmer {
|
||||||
|
transition-duration: 1ms;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
276
src/components/gradient-shimmer.tsx
Normal file
276
src/components/gradient-shimmer.tsx
Normal file
|
|
@ -0,0 +1,276 @@
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
// React port of GradientShimmer.svelte from helium-prism (https://github.com/imputnet/helium-prism),
|
||||||
|
// licensed under GPL-3.0. This file is part of the FRG web app and is licensed under GPL-3.0 (see LICENSE).
|
||||||
|
|
||||||
|
import { useEffect, useImperativeHandle, useRef, useState, type Ref } from "react";
|
||||||
|
import * as Shimmer from "@/lib/gradient-shimmer";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
export type GradientShimmerHandle = {
|
||||||
|
intro: () => void;
|
||||||
|
emphasize: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
type GradientShimmerProps = {
|
||||||
|
intro?: boolean;
|
||||||
|
background?: boolean;
|
||||||
|
className?: string;
|
||||||
|
ref?: Ref<GradientShimmerHandle>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function GradientShimmer({
|
||||||
|
intro: shouldIntro,
|
||||||
|
background,
|
||||||
|
className,
|
||||||
|
ref,
|
||||||
|
}: GradientShimmerProps) {
|
||||||
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
|
const controllerRef = useRef<Shimmer.GradientShimmerControls | null>(null);
|
||||||
|
const [hasStaticFallback, setHasStaticFallback] = useState(false);
|
||||||
|
const [visible, setVisible] = useState(false);
|
||||||
|
|
||||||
|
useImperativeHandle(ref, () => ({
|
||||||
|
intro: () => controllerRef.current?.intro(),
|
||||||
|
emphasize: () => controllerRef.current?.emphasize(),
|
||||||
|
}), []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const canvas = canvasRef.current;
|
||||||
|
|
||||||
|
if (!canvas) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderer = Shimmer.createGradientShimmerRenderer(canvas);
|
||||||
|
|
||||||
|
if (!renderer) {
|
||||||
|
// One-off sync from a failed WebGL probe; there is no later render to wait for.
|
||||||
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
|
setHasStaticFallback(true);
|
||||||
|
setVisible(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const colorSchemeQuery = window.matchMedia(
|
||||||
|
"(prefers-color-scheme: dark)",
|
||||||
|
);
|
||||||
|
const reducedMotionQuery = window.matchMedia(
|
||||||
|
"(prefers-reduced-motion: reduce)",
|
||||||
|
);
|
||||||
|
|
||||||
|
let animationFrame: number | null = null;
|
||||||
|
let resizeFrame: number | null = null;
|
||||||
|
let introAnimation: Shimmer.IntroAnimation | null = null;
|
||||||
|
let speedUpAnimation: Shimmer.WaveSpeedUpAnimation | null = null;
|
||||||
|
let wavePhase = Shimmer.getRandomWavePhase();
|
||||||
|
let secondaryWavePhase = -wavePhase * 0.7;
|
||||||
|
let lastFrameTime: number | null = null;
|
||||||
|
let onScreen = true;
|
||||||
|
|
||||||
|
const cancelResizeFrame = () => {
|
||||||
|
if (resizeFrame === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
cancelAnimationFrame(resizeFrame);
|
||||||
|
resizeFrame = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancelAnimation = () => {
|
||||||
|
if (animationFrame === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
cancelAnimationFrame(animationFrame);
|
||||||
|
animationFrame = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const drawFrame = (time: number) => {
|
||||||
|
const reducedMotion = reducedMotionQuery.matches;
|
||||||
|
const deltaSeconds = reducedMotion || lastFrameTime === null
|
||||||
|
? 0
|
||||||
|
: Math.min((time - lastFrameTime) / 1000, 0.064);
|
||||||
|
const speedUpState = Shimmer.updateSpeedUpAnimation(
|
||||||
|
time,
|
||||||
|
speedUpAnimation,
|
||||||
|
);
|
||||||
|
const activeIntroAnimation = reducedMotion ? null : introAnimation;
|
||||||
|
|
||||||
|
lastFrameTime = reducedMotion ? null : time;
|
||||||
|
speedUpAnimation = reducedMotion ? null : speedUpState.animation;
|
||||||
|
|
||||||
|
if (!reducedMotion) {
|
||||||
|
wavePhase += Shimmer.IDLE_WAVE.speed
|
||||||
|
* speedUpState.multiplier
|
||||||
|
* deltaSeconds;
|
||||||
|
secondaryWavePhase += Shimmer.IDLE_WAVE.secondarySpeed
|
||||||
|
* speedUpState.multiplier
|
||||||
|
* deltaSeconds;
|
||||||
|
}
|
||||||
|
|
||||||
|
renderer.render({
|
||||||
|
time,
|
||||||
|
wavePhase,
|
||||||
|
secondaryWavePhase,
|
||||||
|
introStartedAt: activeIntroAnimation?.startedAt ?? null,
|
||||||
|
shineProgress: reducedMotion ? 0 : speedUpState.shineProgress,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (
|
||||||
|
Shimmer.isIntroComplete(
|
||||||
|
time,
|
||||||
|
introAnimation,
|
||||||
|
renderer.getStripeCount(),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
introAnimation = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const startIntro = () => {
|
||||||
|
if (reducedMotionQuery.matches) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
introAnimation = { startedAt: performance.now() };
|
||||||
|
};
|
||||||
|
|
||||||
|
const startWaveSpeedUp = () => {
|
||||||
|
if (reducedMotionQuery.matches) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const time = performance.now();
|
||||||
|
|
||||||
|
speedUpAnimation = Shimmer.triggerSpeedUpAnimation(
|
||||||
|
time,
|
||||||
|
speedUpAnimation,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const controller: Shimmer.GradientShimmerControls = {
|
||||||
|
intro: startIntro,
|
||||||
|
emphasize: startWaveSpeedUp,
|
||||||
|
};
|
||||||
|
|
||||||
|
const applyResize = () => {
|
||||||
|
renderer.resize();
|
||||||
|
renderer.readColors();
|
||||||
|
};
|
||||||
|
|
||||||
|
const scheduleResize = () => {
|
||||||
|
cancelResizeFrame();
|
||||||
|
resizeFrame = requestAnimationFrame((time) => {
|
||||||
|
applyResize();
|
||||||
|
drawFrame(time);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const draw = (time: number) => {
|
||||||
|
animationFrame = null;
|
||||||
|
drawFrame(time);
|
||||||
|
requestAnimation();
|
||||||
|
};
|
||||||
|
|
||||||
|
const requestAnimation = () => {
|
||||||
|
if (animationFrame !== null || reducedMotionQuery.matches ||
|
||||||
|
!onScreen) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
animationFrame = requestAnimationFrame(draw);
|
||||||
|
};
|
||||||
|
|
||||||
|
const resumeAnimation = () => {
|
||||||
|
lastFrameTime = null;
|
||||||
|
requestAnimation();
|
||||||
|
};
|
||||||
|
|
||||||
|
applyResize();
|
||||||
|
|
||||||
|
if (shouldIntro !== false) {
|
||||||
|
startIntro();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delay the reveal until after the first WebGL frame has been painted.
|
||||||
|
drawFrame(performance.now());
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
setVisible(true);
|
||||||
|
});
|
||||||
|
controllerRef.current = controller;
|
||||||
|
|
||||||
|
const resizeObserver = new ResizeObserver(scheduleResize);
|
||||||
|
resizeObserver.observe(canvas);
|
||||||
|
|
||||||
|
const scheduleColorRead = () => {
|
||||||
|
cancelResizeFrame();
|
||||||
|
resizeFrame = requestAnimationFrame((time) => {
|
||||||
|
renderer.readColors();
|
||||||
|
drawFrame(time);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const intersectionObserver = new IntersectionObserver(([entry]) => {
|
||||||
|
onScreen = entry?.isIntersecting ?? true;
|
||||||
|
|
||||||
|
if (!onScreen) {
|
||||||
|
cancelAnimation();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
resumeAnimation();
|
||||||
|
});
|
||||||
|
intersectionObserver.observe(canvas);
|
||||||
|
|
||||||
|
const themeObserver = new MutationObserver(scheduleColorRead);
|
||||||
|
themeObserver.observe(document.documentElement, { attributes: true });
|
||||||
|
|
||||||
|
const updateMotionPreference = () => {
|
||||||
|
if (reducedMotionQuery.matches) {
|
||||||
|
introAnimation = null;
|
||||||
|
speedUpAnimation = null;
|
||||||
|
cancelAnimation();
|
||||||
|
drawFrame(performance.now());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
resumeAnimation();
|
||||||
|
};
|
||||||
|
|
||||||
|
colorSchemeQuery.addEventListener("change", scheduleColorRead);
|
||||||
|
reducedMotionQuery.addEventListener("change", updateMotionPreference);
|
||||||
|
|
||||||
|
updateMotionPreference();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (controllerRef.current === controller) {
|
||||||
|
controllerRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
setVisible(false);
|
||||||
|
cancelAnimation();
|
||||||
|
cancelResizeFrame();
|
||||||
|
resizeObserver.disconnect();
|
||||||
|
intersectionObserver.disconnect();
|
||||||
|
themeObserver.disconnect();
|
||||||
|
colorSchemeQuery.removeEventListener("change", scheduleColorRead);
|
||||||
|
reducedMotionQuery.removeEventListener("change", updateMotionPreference);
|
||||||
|
renderer.dispose();
|
||||||
|
};
|
||||||
|
}, [shouldIntro]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<canvas
|
||||||
|
ref={canvasRef}
|
||||||
|
aria-hidden="true"
|
||||||
|
className={cn(
|
||||||
|
"gradient-shimmer",
|
||||||
|
background && "background",
|
||||||
|
hasStaticFallback && "fallback",
|
||||||
|
visible && "visible",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
993
src/lib/gradient-shimmer.ts
Normal file
993
src/lib/gradient-shimmer.ts
Normal file
|
|
@ -0,0 +1,993 @@
|
||||||
|
// Adapted from helium-prism (https://github.com/imputnet/helium-prism),
|
||||||
|
// src/lib/gradient-shimmer.ts, licensed under GPL-3.0. Shader sources are inlined.
|
||||||
|
// Modification: GLSL is inlined as strings instead of loaded with Vite-style ?raw imports.
|
||||||
|
// This file is part of the FRG web app and is licensed under GPL-3.0 (see LICENSE).
|
||||||
|
|
||||||
|
import { Geometry, Mesh, Program, Renderer, Texture } from "ogl";
|
||||||
|
|
||||||
|
const FRAGMENT_SHADER_SOURCE = `#version 300 es
|
||||||
|
|
||||||
|
precision highp float;
|
||||||
|
|
||||||
|
uniform vec2 u_size;
|
||||||
|
uniform float u_inverse_dpr;
|
||||||
|
uniform float u_stripe_width;
|
||||||
|
uniform float u_gradient_top;
|
||||||
|
uniform float u_gradient_vertical_span;
|
||||||
|
uniform float u_inverse_gradient_denominator;
|
||||||
|
|
||||||
|
uniform vec3 u_start_color;
|
||||||
|
uniform vec3 u_highlight_delta;
|
||||||
|
uniform float u_grain_alpha;
|
||||||
|
uniform float u_grain_luminance;
|
||||||
|
uniform float u_grain_contrast;
|
||||||
|
uniform float u_grain_saturation;
|
||||||
|
uniform sampler2D u_grain_noise;
|
||||||
|
|
||||||
|
flat in float v_stripe_start;
|
||||||
|
flat in vec3 v_band;
|
||||||
|
flat in vec3 v_band_inverse;
|
||||||
|
flat in float v_out_alpha;
|
||||||
|
flat in float v_highlight_strength;
|
||||||
|
|
||||||
|
const float GRAIN_SIZE = 180.0;
|
||||||
|
|
||||||
|
out vec4 fragment_color;
|
||||||
|
|
||||||
|
float clamp01(float value) {
|
||||||
|
return clamp(value, 0.0, 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
vec3 overlayBlend(vec3 base, vec3 blend) {
|
||||||
|
vec3 low = 2.0 * base * blend;
|
||||||
|
vec3 high = 1.0 - 2.0 * (1.0 - base) * (1.0 - blend);
|
||||||
|
|
||||||
|
return mix(low, high, step(vec3(0.5), base));
|
||||||
|
}
|
||||||
|
|
||||||
|
float gradientHighlightAmount(float position) {
|
||||||
|
if (position < v_band.x) {
|
||||||
|
return 1.0 - clamp01(position * v_band_inverse.x);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (position < v_band.y) {
|
||||||
|
return clamp01((position - v_band.x) * v_band_inverse.y);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (position < v_band.z) {
|
||||||
|
return 1.0 - clamp01((position - v_band.y) * v_band_inverse.z);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
vec2 css_position = vec2(
|
||||||
|
gl_FragCoord.x * u_inverse_dpr,
|
||||||
|
u_size.y - gl_FragCoord.y * u_inverse_dpr
|
||||||
|
);
|
||||||
|
vec2 gradient_offset = vec2(
|
||||||
|
css_position.x - v_stripe_start,
|
||||||
|
css_position.y - u_gradient_top
|
||||||
|
);
|
||||||
|
vec2 gradient_axis = vec2(
|
||||||
|
u_stripe_width,
|
||||||
|
u_gradient_vertical_span
|
||||||
|
);
|
||||||
|
float gradient_position = clamp01(
|
||||||
|
dot(gradient_offset, gradient_axis) * u_inverse_gradient_denominator
|
||||||
|
);
|
||||||
|
vec3 color = u_start_color + u_highlight_delta * (
|
||||||
|
gradientHighlightAmount(gradient_position) * v_highlight_strength
|
||||||
|
);
|
||||||
|
|
||||||
|
ivec2 grain_position = min(
|
||||||
|
ivec2(mod(css_position, GRAIN_SIZE)),
|
||||||
|
ivec2(GRAIN_SIZE - 1.0)
|
||||||
|
);
|
||||||
|
vec4 noise = texelFetch(u_grain_noise, grain_position, 0) - 0.5;
|
||||||
|
float luminance = u_grain_luminance + noise.r * u_grain_contrast;
|
||||||
|
vec3 color_shift = noise.gba * u_grain_saturation;
|
||||||
|
vec3 grain = clamp((vec3(luminance) + color_shift) / 255.0, 0.0, 1.0);
|
||||||
|
|
||||||
|
color = mix(color, overlayBlend(color, grain), u_grain_alpha);
|
||||||
|
|
||||||
|
fragment_color = vec4(color * v_out_alpha, v_out_alpha);
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const VERTEX_SHADER_SOURCE = `#version 300 es
|
||||||
|
|
||||||
|
precision highp float;
|
||||||
|
|
||||||
|
// X is 0 at the stripe's left edge and 1 at its right edge, Y is in clip space.
|
||||||
|
in vec2 position;
|
||||||
|
|
||||||
|
uniform vec2 u_size;
|
||||||
|
uniform float u_stripe_max_index;
|
||||||
|
uniform float u_stripe_width;
|
||||||
|
uniform float u_wave_phase;
|
||||||
|
uniform float u_secondary_wave_phase;
|
||||||
|
uniform float u_intro_active;
|
||||||
|
uniform float u_intro_elapsed;
|
||||||
|
uniform float u_shine_progress;
|
||||||
|
|
||||||
|
uniform float u_alpha;
|
||||||
|
uniform float u_intro_alpha;
|
||||||
|
uniform float u_speed_up_shine_boost;
|
||||||
|
|
||||||
|
uniform float u_gradient_band_width;
|
||||||
|
uniform float u_gradient_min_stop;
|
||||||
|
uniform float u_gradient_max_stop;
|
||||||
|
uniform float u_intro_reveal_duration;
|
||||||
|
uniform float u_intro_reveal_duration_inverse;
|
||||||
|
uniform float u_intro_idle_blend_duration_inverse;
|
||||||
|
uniform float u_intro_stagger;
|
||||||
|
uniform float u_intro_center_index;
|
||||||
|
uniform float u_intro_center_distance;
|
||||||
|
uniform float u_intro_start_center;
|
||||||
|
uniform float u_intro_idle_center;
|
||||||
|
uniform float u_idle_stripe_phase;
|
||||||
|
uniform float u_idle_secondary_stripe_phase;
|
||||||
|
uniform float u_idle_primary_amplitude;
|
||||||
|
uniform float u_idle_secondary_amplitude;
|
||||||
|
|
||||||
|
// Everything below is constant across a stripe, so it's computed per stripe
|
||||||
|
// instead of per pixel.
|
||||||
|
flat out float v_stripe_start;
|
||||||
|
// Band start, center and band end.
|
||||||
|
flat out vec3 v_band;
|
||||||
|
// Inverse lengths of the three gradient segments.
|
||||||
|
flat out vec3 v_band_inverse;
|
||||||
|
flat out float v_out_alpha;
|
||||||
|
flat out float v_highlight_strength;
|
||||||
|
|
||||||
|
const float EPSILON = 0.0001;
|
||||||
|
|
||||||
|
float clamp01(float value) {
|
||||||
|
return clamp(value, 0.0, 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
float easeOutCubic(float value) {
|
||||||
|
float inverse = 1.0 - value;
|
||||||
|
return 1.0 - inverse * inverse * inverse;
|
||||||
|
}
|
||||||
|
|
||||||
|
float introRevealProgress(float delayed_elapsed) {
|
||||||
|
if (u_intro_active < 0.5) {
|
||||||
|
return 1.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return easeOutCubic(
|
||||||
|
clamp01(delayed_elapsed * u_intro_reveal_duration_inverse)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
float introIdleProgress(float delayed_elapsed) {
|
||||||
|
if (u_intro_active < 0.5) {
|
||||||
|
return 1.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return easeOutCubic(
|
||||||
|
clamp01(
|
||||||
|
(delayed_elapsed - u_intro_reveal_duration) *
|
||||||
|
u_intro_idle_blend_duration_inverse
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
float stripe_index = float(gl_InstanceID);
|
||||||
|
float stripe_start = stripe_index * u_stripe_width;
|
||||||
|
float edge_x = (stripe_index + position.x) * u_stripe_width;
|
||||||
|
|
||||||
|
// Avoid a gap at the right edge from float error.
|
||||||
|
if (stripe_index == u_stripe_max_index && position.x > 0.5) {
|
||||||
|
edge_x = u_size.x;
|
||||||
|
}
|
||||||
|
|
||||||
|
gl_Position = vec4(edge_x / u_size.x * 2.0 - 1.0, position.y, 0.0, 1.0);
|
||||||
|
|
||||||
|
float reveal_delay = max(
|
||||||
|
0.0,
|
||||||
|
abs(stripe_index - u_intro_center_index) - u_intro_center_distance
|
||||||
|
) * u_intro_stagger;
|
||||||
|
float delayed_intro_elapsed = u_intro_elapsed - reveal_delay;
|
||||||
|
float reveal_progress = introRevealProgress(delayed_intro_elapsed);
|
||||||
|
float idle_progress = introIdleProgress(delayed_intro_elapsed);
|
||||||
|
float alpha = u_intro_alpha + (u_alpha - u_intro_alpha) * idle_progress;
|
||||||
|
float stripe_phase = stripe_index * u_idle_stripe_phase;
|
||||||
|
float secondary_stripe_phase = stripe_index * u_idle_secondary_stripe_phase;
|
||||||
|
float primary_wave = sin(u_wave_phase - stripe_phase);
|
||||||
|
float secondary_wave = sin(
|
||||||
|
u_secondary_wave_phase + secondary_stripe_phase
|
||||||
|
);
|
||||||
|
float idle_center = 0.5 +
|
||||||
|
primary_wave * u_idle_primary_amplitude +
|
||||||
|
secondary_wave * u_idle_secondary_amplitude;
|
||||||
|
float intro_center = mix(
|
||||||
|
u_intro_start_center,
|
||||||
|
u_intro_idle_center,
|
||||||
|
reveal_progress
|
||||||
|
);
|
||||||
|
float center = mix(intro_center, idle_center, idle_progress);
|
||||||
|
float band_start = clamp(
|
||||||
|
center - u_gradient_band_width,
|
||||||
|
u_gradient_min_stop,
|
||||||
|
u_gradient_max_stop
|
||||||
|
);
|
||||||
|
float band_end = clamp(
|
||||||
|
center + u_gradient_band_width,
|
||||||
|
u_gradient_min_stop,
|
||||||
|
u_gradient_max_stop
|
||||||
|
);
|
||||||
|
float gradient_alpha = clamp01(
|
||||||
|
alpha * (1.0 + u_shine_progress * u_speed_up_shine_boost)
|
||||||
|
) * reveal_progress;
|
||||||
|
float out_alpha = gradient_alpha + alpha * (1.0 - gradient_alpha);
|
||||||
|
|
||||||
|
v_stripe_start = stripe_start;
|
||||||
|
v_band = vec3(band_start, center, band_end);
|
||||||
|
v_band_inverse = 1.0 / max(
|
||||||
|
vec3(band_start, center - band_start, band_end - center),
|
||||||
|
EPSILON
|
||||||
|
);
|
||||||
|
v_out_alpha = out_alpha;
|
||||||
|
// Compositing the gradient over the start color reduces to
|
||||||
|
// start + delta * amount * gradient_alpha / out_alpha.
|
||||||
|
v_highlight_strength = gradient_alpha / max(out_alpha, EPSILON);
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const STRIPE_WIDTH = {
|
||||||
|
min: 64,
|
||||||
|
target: 110,
|
||||||
|
max: 120,
|
||||||
|
};
|
||||||
|
|
||||||
|
const GRADIENT = {
|
||||||
|
bandWidth: 0.48,
|
||||||
|
minStop: 0.14,
|
||||||
|
maxStop: 0.96,
|
||||||
|
};
|
||||||
|
|
||||||
|
const INTRO = {
|
||||||
|
delay: 700,
|
||||||
|
revealDuration: 840,
|
||||||
|
idleBlendDuration: 500,
|
||||||
|
stagger: 45,
|
||||||
|
startCenter: 0.96,
|
||||||
|
idleCenter: 0.5,
|
||||||
|
};
|
||||||
|
|
||||||
|
const WAVE_SPEED_UP = {
|
||||||
|
multiplier: 2.15,
|
||||||
|
rampUpDuration: 140,
|
||||||
|
waveDuration: 320,
|
||||||
|
rampDownDuration: 480,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const IDLE_WAVE = {
|
||||||
|
speed: 0.42,
|
||||||
|
stripePhase: 0.74,
|
||||||
|
secondarySpeed: 0.26,
|
||||||
|
secondaryStripePhase: 1.28,
|
||||||
|
primaryAmplitude: 0.19,
|
||||||
|
secondaryAmplitude: 0.055,
|
||||||
|
};
|
||||||
|
|
||||||
|
const FULL_CIRCLE = Math.PI * 2;
|
||||||
|
|
||||||
|
const GRAIN = {
|
||||||
|
size: 180,
|
||||||
|
hashScale: [127.1, 311.7],
|
||||||
|
hashOffset: 43758.5,
|
||||||
|
// Luminance, then the red, green and blue color shifts.
|
||||||
|
channelOffsets: [[0, 0], [17, 3], [7, 29], [31, 11]],
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type IntroAnimation = {
|
||||||
|
startedAt: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type WaveSpeedUpValues = {
|
||||||
|
multiplier: number;
|
||||||
|
shineProgress: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WaveSpeedUpAnimation = {
|
||||||
|
phase: "ramp-up";
|
||||||
|
startedAt: number;
|
||||||
|
duration: number;
|
||||||
|
from: WaveSpeedUpValues;
|
||||||
|
} | {
|
||||||
|
phase: "hold";
|
||||||
|
startedAt: number;
|
||||||
|
} | {
|
||||||
|
phase: "ramp-down";
|
||||||
|
startedAt: number;
|
||||||
|
from: WaveSpeedUpValues;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Size = {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
dpr: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type GradientShimmerControls = {
|
||||||
|
intro: () => void;
|
||||||
|
emphasize: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
type WaveSpeedUpAnimationState = WaveSpeedUpValues & {
|
||||||
|
animation: WaveSpeedUpAnimation | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Color = [number, number, number];
|
||||||
|
|
||||||
|
type ShaderColors = {
|
||||||
|
alpha: number;
|
||||||
|
grainAlpha: number;
|
||||||
|
grainLuminance: number;
|
||||||
|
grainContrast: number;
|
||||||
|
grainSaturation: number;
|
||||||
|
introAlpha: number;
|
||||||
|
start: Color;
|
||||||
|
highlightDelta: Color;
|
||||||
|
speedUpShineBoost: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type StripeMetrics = {
|
||||||
|
count: number;
|
||||||
|
width: number;
|
||||||
|
maxIndex: number;
|
||||||
|
introCenterIndex: number;
|
||||||
|
introCenterDistance: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type RenderMetrics = {
|
||||||
|
inverseDpr: number;
|
||||||
|
gradientTop: number;
|
||||||
|
gradientVerticalSpan: number;
|
||||||
|
inverseGradientDenominator: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Grain is static, so it's hashed once here instead of per pixel every frame.
|
||||||
|
const createGrainNoise = () => {
|
||||||
|
const { size, hashScale, hashOffset, channelOffsets } = GRAIN;
|
||||||
|
const data = new Uint8Array(size * size * channelOffsets.length);
|
||||||
|
let index = 0;
|
||||||
|
|
||||||
|
for (let y = 0; y < size; y++) {
|
||||||
|
for (let x = 0; x < size; x++) {
|
||||||
|
for (const [offsetX, offsetY] of channelOffsets) {
|
||||||
|
const hash = Math.sin(
|
||||||
|
(x + offsetX) * hashScale[0] + (y + offsetY) * hashScale[1],
|
||||||
|
) * hashOffset;
|
||||||
|
|
||||||
|
data[index++] = Math.round((hash - Math.floor(hash)) * 255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
};
|
||||||
|
|
||||||
|
// One instanced quad per stripe. The vertex shader takes the stripe index
|
||||||
|
// from gl_InstanceID, so no per-instance attribute is needed.
|
||||||
|
const createStripeGeometry = (gl: Renderer["gl"]) => {
|
||||||
|
const geometry = new Geometry(gl, {
|
||||||
|
position: {
|
||||||
|
size: 2,
|
||||||
|
data: new Float32Array([
|
||||||
|
0, -1,
|
||||||
|
1, -1,
|
||||||
|
0, 1,
|
||||||
|
0, 1,
|
||||||
|
1, -1,
|
||||||
|
1, 1,
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
geometry.isInstanced = true;
|
||||||
|
|
||||||
|
return geometry;
|
||||||
|
};
|
||||||
|
|
||||||
|
type GradientShimmerRenderer = {
|
||||||
|
resize: () => void;
|
||||||
|
readColors: () => void;
|
||||||
|
render: (frame: {
|
||||||
|
time: number;
|
||||||
|
wavePhase: number;
|
||||||
|
secondaryWavePhase: number;
|
||||||
|
introStartedAt: number | null;
|
||||||
|
shineProgress: number;
|
||||||
|
}) => void;
|
||||||
|
dispose: () => void;
|
||||||
|
getStripeCount: () => number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const clamp = (value: number, min = 0, max = 1) => Math.max(min, Math.min(max, value));
|
||||||
|
const lerp = (start: number, end: number, progress: number) => start + (end - start) * progress;
|
||||||
|
const easeOutCubic = (value: number) => 1 - Math.pow(1 - value, 3);
|
||||||
|
const easeInOutCubic = (value: number) => (
|
||||||
|
value < 0.5 ? 4 * value * value * value : 1 - Math.pow(-2 * value + 2, 3) / 2
|
||||||
|
);
|
||||||
|
|
||||||
|
export const getRandomWavePhase = () => Math.random() * FULL_CIRCLE;
|
||||||
|
|
||||||
|
const readCssNumber = (
|
||||||
|
styles: CSSStyleDeclaration,
|
||||||
|
name: string,
|
||||||
|
) => {
|
||||||
|
const rawValue = styles.getPropertyValue(name).trim();
|
||||||
|
const value = Number(rawValue);
|
||||||
|
|
||||||
|
if (!rawValue || !Number.isFinite(value)) {
|
||||||
|
throw new Error(`Missing or invalid CSS number: ${name}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
|
||||||
|
const readCssString = (
|
||||||
|
styles: CSSStyleDeclaration,
|
||||||
|
name: string,
|
||||||
|
) => {
|
||||||
|
const value = styles.getPropertyValue(name).trim();
|
||||||
|
|
||||||
|
if (!value) {
|
||||||
|
throw new Error(`Missing CSS value: ${name}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStripeCount = (canvasWidth: number) => {
|
||||||
|
const minCount = Math.max(1, Math.ceil(canvasWidth / STRIPE_WIDTH.max));
|
||||||
|
const maxCount = Math.max(1, Math.floor(canvasWidth / STRIPE_WIDTH.min));
|
||||||
|
const targetCount = Math.max(
|
||||||
|
1,
|
||||||
|
Math.round(canvasWidth / STRIPE_WIDTH.target),
|
||||||
|
);
|
||||||
|
|
||||||
|
return Math.max(minCount, Math.min(maxCount, targetCount));
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStripeMetrics = (width: number): StripeMetrics => {
|
||||||
|
const count = getStripeCount(width);
|
||||||
|
const stripeWidth = width / count;
|
||||||
|
const maxIndex = count - 1;
|
||||||
|
|
||||||
|
return {
|
||||||
|
count,
|
||||||
|
width: stripeWidth,
|
||||||
|
maxIndex,
|
||||||
|
introCenterIndex: maxIndex / 2,
|
||||||
|
introCenterDistance: count % 2 === 0 ? 0.5 : 0,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const getRenderMetrics = (
|
||||||
|
size: Size,
|
||||||
|
stripes: StripeMetrics,
|
||||||
|
): RenderMetrics => {
|
||||||
|
const gradientVerticalSpan = size.height * 1.7;
|
||||||
|
|
||||||
|
return {
|
||||||
|
inverseDpr: 1 / size.dpr,
|
||||||
|
gradientTop: size.height * -0.35,
|
||||||
|
gradientVerticalSpan,
|
||||||
|
inverseGradientDenominator: 1 / (
|
||||||
|
stripes.width * stripes.width
|
||||||
|
+ gradientVerticalSpan * gradientVerticalSpan
|
||||||
|
),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const getRevealDelay = (
|
||||||
|
index: number,
|
||||||
|
stripeCount: number,
|
||||||
|
stagger = INTRO.stagger,
|
||||||
|
) => {
|
||||||
|
const centerIndex = (stripeCount - 1) / 2;
|
||||||
|
const centerDistance = stripeCount % 2 === 0 ? 0.5 : 0;
|
||||||
|
const distanceFromCenter = Math.abs(index - centerIndex) - centerDistance;
|
||||||
|
|
||||||
|
return Math.max(0, distanceFromCenter) * stagger;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getMaxRevealDelay = (stripeCount: number, stagger = INTRO.stagger) => {
|
||||||
|
if (stripeCount <= 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.max(
|
||||||
|
getRevealDelay(0, stripeCount, stagger),
|
||||||
|
getRevealDelay(stripeCount - 1, stripeCount, stagger),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const isIntroComplete = (
|
||||||
|
time: number,
|
||||||
|
introAnimation: IntroAnimation | null,
|
||||||
|
stripeCount: number,
|
||||||
|
) => {
|
||||||
|
if (!introAnimation) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const completeAt = introAnimation.startedAt
|
||||||
|
+ INTRO.delay
|
||||||
|
+ getMaxRevealDelay(stripeCount)
|
||||||
|
+ INTRO.revealDuration
|
||||||
|
+ INTRO.idleBlendDuration;
|
||||||
|
|
||||||
|
return time >= completeAt;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createShaderUniforms = (grainNoise: Texture) => ({
|
||||||
|
u_size: { value: [1, 1] },
|
||||||
|
u_inverse_dpr: { value: 1 },
|
||||||
|
u_stripe_max_index: { value: 0 },
|
||||||
|
u_stripe_width: { value: 1 },
|
||||||
|
u_gradient_top: { value: 0 },
|
||||||
|
u_gradient_vertical_span: { value: 1 },
|
||||||
|
u_inverse_gradient_denominator: { value: 1 },
|
||||||
|
u_wave_phase: { value: 0 },
|
||||||
|
u_secondary_wave_phase: { value: 0 },
|
||||||
|
u_intro_active: { value: 0 },
|
||||||
|
u_intro_elapsed: { value: 0 },
|
||||||
|
u_shine_progress: { value: 0 },
|
||||||
|
u_start_color: { value: [0, 0, 0] },
|
||||||
|
u_highlight_delta: { value: [0, 0, 0] },
|
||||||
|
u_alpha: { value: 1 },
|
||||||
|
u_intro_alpha: { value: 1 },
|
||||||
|
u_speed_up_shine_boost: { value: 0 },
|
||||||
|
u_grain_alpha: { value: 0 },
|
||||||
|
u_grain_luminance: { value: 0 },
|
||||||
|
u_grain_contrast: { value: 0 },
|
||||||
|
u_grain_saturation: { value: 0 },
|
||||||
|
u_grain_noise: { value: grainNoise },
|
||||||
|
u_intro_center_index: { value: 0 },
|
||||||
|
u_intro_center_distance: { value: 0 },
|
||||||
|
u_gradient_band_width: { value: GRADIENT.bandWidth },
|
||||||
|
u_gradient_min_stop: { value: GRADIENT.minStop },
|
||||||
|
u_gradient_max_stop: { value: GRADIENT.maxStop },
|
||||||
|
u_intro_reveal_duration: { value: INTRO.revealDuration },
|
||||||
|
u_intro_reveal_duration_inverse: { value: 1 / INTRO.revealDuration },
|
||||||
|
u_intro_idle_blend_duration_inverse: { value: 1 / INTRO.idleBlendDuration },
|
||||||
|
u_intro_stagger: { value: INTRO.stagger },
|
||||||
|
u_intro_start_center: { value: INTRO.startCenter },
|
||||||
|
u_intro_idle_center: { value: INTRO.idleCenter },
|
||||||
|
u_idle_stripe_phase: { value: IDLE_WAVE.stripePhase },
|
||||||
|
u_idle_secondary_stripe_phase: { value: IDLE_WAVE.secondaryStripePhase },
|
||||||
|
u_idle_primary_amplitude: { value: IDLE_WAVE.primaryAmplitude },
|
||||||
|
u_idle_secondary_amplitude: { value: IDLE_WAVE.secondaryAmplitude },
|
||||||
|
});
|
||||||
|
|
||||||
|
const parseColorChannel = (channel: string) => {
|
||||||
|
if (channel.endsWith("%")) {
|
||||||
|
return clamp(Number.parseFloat(channel) / 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
return clamp(Number.parseFloat(channel) / 255);
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseCssColorValue = (value: string): Color => {
|
||||||
|
const color = value.trim().toLowerCase();
|
||||||
|
|
||||||
|
if (color.startsWith("#")) {
|
||||||
|
const hex = color.slice(1);
|
||||||
|
const normalized = hex.length === 3
|
||||||
|
? hex.split("").map((part) => part + part).join("")
|
||||||
|
: hex;
|
||||||
|
|
||||||
|
if (normalized.length === 6) {
|
||||||
|
return [
|
||||||
|
Number.parseInt(normalized.slice(0, 2), 16) / 255,
|
||||||
|
Number.parseInt(normalized.slice(2, 4), 16) / 255,
|
||||||
|
Number.parseInt(normalized.slice(4, 6), 16) / 255,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const channels = color.match(/-?\d*\.?\d+(?:e[+-]?\d+)?%?/g) ?? [];
|
||||||
|
|
||||||
|
if (color.startsWith("color(") && channels.length >= 3) {
|
||||||
|
const [red, green, blue] = channels as [string, string, string];
|
||||||
|
|
||||||
|
return [
|
||||||
|
clamp(Number.parseFloat(red)),
|
||||||
|
clamp(Number.parseFloat(green)),
|
||||||
|
clamp(Number.parseFloat(blue)),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (channels.length >= 3) {
|
||||||
|
const [red, green, blue] = channels as [string, string, string];
|
||||||
|
|
||||||
|
return [
|
||||||
|
parseColorChannel(red),
|
||||||
|
parseColorChannel(green),
|
||||||
|
parseColorChannel(blue),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unsupported CSS color: ${value}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const readCssColor = (
|
||||||
|
styles: CSSStyleDeclaration,
|
||||||
|
name: string,
|
||||||
|
context: CanvasRenderingContext2D,
|
||||||
|
) => {
|
||||||
|
const rawValue = readCssString(styles, name);
|
||||||
|
|
||||||
|
context.fillStyle = "#000000";
|
||||||
|
context.fillStyle = rawValue;
|
||||||
|
|
||||||
|
return parseCssColorValue(context.fillStyle);
|
||||||
|
};
|
||||||
|
|
||||||
|
const readShaderColors = (
|
||||||
|
canvas: HTMLCanvasElement,
|
||||||
|
colorContext: CanvasRenderingContext2D,
|
||||||
|
): ShaderColors => {
|
||||||
|
const styles = getComputedStyle(canvas);
|
||||||
|
const start = readCssColor(styles, "--shimmer-start", colorContext);
|
||||||
|
const highlight = readCssColor(styles, "--shimmer-highlight", colorContext);
|
||||||
|
|
||||||
|
return {
|
||||||
|
alpha: readCssNumber(styles, "--shimmer-alpha"),
|
||||||
|
grainAlpha: readCssNumber(styles, "--shimmer-grain-alpha"),
|
||||||
|
grainLuminance: readCssNumber(styles, "--shimmer-grain-luminance"),
|
||||||
|
grainContrast: readCssNumber(styles, "--shimmer-grain-contrast"),
|
||||||
|
grainSaturation: readCssNumber(styles, "--shimmer-grain-saturation"),
|
||||||
|
introAlpha: readCssNumber(styles, "--shimmer-intro-alpha"),
|
||||||
|
start,
|
||||||
|
highlightDelta: [
|
||||||
|
highlight[0] - start[0],
|
||||||
|
highlight[1] - start[1],
|
||||||
|
highlight[2] - start[2],
|
||||||
|
],
|
||||||
|
speedUpShineBoost: readCssNumber(
|
||||||
|
styles,
|
||||||
|
"--shimmer-speed-up-shine-boost",
|
||||||
|
),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const getCanvasSize = (canvas: HTMLCanvasElement): Size => {
|
||||||
|
const { width, height } = canvas.getBoundingClientRect();
|
||||||
|
// Grain cells are CSS pixels and the gradient is smooth, so rendering
|
||||||
|
// above CSS resolution adds nothing. The canvas is upscaled pixelated.
|
||||||
|
const dpr = Math.min(globalThis.devicePixelRatio || 1, 1);
|
||||||
|
const cssWidth = Math.max(1, width);
|
||||||
|
const cssHeight = Math.max(1, height);
|
||||||
|
|
||||||
|
return { width: cssWidth, height: cssHeight, dpr };
|
||||||
|
};
|
||||||
|
|
||||||
|
const resizeOglCanvas = (
|
||||||
|
canvas: HTMLCanvasElement,
|
||||||
|
renderer: Renderer,
|
||||||
|
): Size => {
|
||||||
|
const size = getCanvasSize(canvas);
|
||||||
|
|
||||||
|
renderer.dpr = size.dpr;
|
||||||
|
renderer.setSize(size.width, size.height);
|
||||||
|
canvas.style.width = "";
|
||||||
|
canvas.style.height = "";
|
||||||
|
|
||||||
|
return size;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createGradientShimmerRenderer = (
|
||||||
|
canvas: HTMLCanvasElement,
|
||||||
|
): GradientShimmerRenderer | null => {
|
||||||
|
const initialSize = getCanvasSize(canvas);
|
||||||
|
let renderer: Renderer;
|
||||||
|
|
||||||
|
try {
|
||||||
|
renderer = new Renderer({
|
||||||
|
canvas,
|
||||||
|
width: initialSize.width,
|
||||||
|
height: initialSize.height,
|
||||||
|
dpr: initialSize.dpr,
|
||||||
|
alpha: true,
|
||||||
|
antialias: false,
|
||||||
|
autoClear: false,
|
||||||
|
depth: false,
|
||||||
|
premultipliedAlpha: true,
|
||||||
|
preserveDrawingBuffer: false,
|
||||||
|
stencil: false,
|
||||||
|
webgl: 2,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { gl } = renderer;
|
||||||
|
|
||||||
|
if (!gl || !renderer.isWebgl2) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas.style.width = "";
|
||||||
|
canvas.style.height = "";
|
||||||
|
gl.clearColor(0, 0, 0, 0);
|
||||||
|
|
||||||
|
const colorCanvas = document.createElement("canvas");
|
||||||
|
const colorContext = colorCanvas.getContext("2d");
|
||||||
|
|
||||||
|
if (!colorContext) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const grainNoise = new Texture(gl, {
|
||||||
|
image: createGrainNoise(),
|
||||||
|
width: GRAIN.size,
|
||||||
|
height: GRAIN.size,
|
||||||
|
generateMipmaps: false,
|
||||||
|
minFilter: gl.NEAREST,
|
||||||
|
magFilter: gl.NEAREST,
|
||||||
|
flipY: false,
|
||||||
|
});
|
||||||
|
const uniforms = createShaderUniforms(grainNoise);
|
||||||
|
let program: Program | null = null;
|
||||||
|
let geometry: Geometry | null = null;
|
||||||
|
let mesh: Mesh | null = null;
|
||||||
|
let initialColors: ShaderColors | null = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
program = new Program(gl, {
|
||||||
|
vertex: VERTEX_SHADER_SOURCE,
|
||||||
|
fragment: FRAGMENT_SHADER_SOURCE,
|
||||||
|
uniforms,
|
||||||
|
cullFace: false,
|
||||||
|
depthTest: false,
|
||||||
|
depthWrite: false,
|
||||||
|
transparent: false,
|
||||||
|
});
|
||||||
|
geometry = createStripeGeometry(gl);
|
||||||
|
mesh = new Mesh(gl, {
|
||||||
|
geometry,
|
||||||
|
program,
|
||||||
|
frustumCulled: false,
|
||||||
|
});
|
||||||
|
initialColors = readShaderColors(canvas, colorContext);
|
||||||
|
} catch {
|
||||||
|
geometry?.remove();
|
||||||
|
program?.remove();
|
||||||
|
gl.deleteTexture(grainNoise.texture);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!program || !geometry || !mesh || !initialColors) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
let stripes = getStripeMetrics(initialSize.width);
|
||||||
|
|
||||||
|
const applySize = (size: Size) => {
|
||||||
|
stripes = getStripeMetrics(size.width);
|
||||||
|
const renderMetrics = getRenderMetrics(size, stripes);
|
||||||
|
|
||||||
|
geometry.setInstancedCount(stripes.count);
|
||||||
|
uniforms.u_size.value = [size.width, size.height];
|
||||||
|
uniforms.u_inverse_dpr.value = renderMetrics.inverseDpr;
|
||||||
|
uniforms.u_stripe_max_index.value = stripes.maxIndex;
|
||||||
|
uniforms.u_stripe_width.value = stripes.width;
|
||||||
|
uniforms.u_gradient_top.value = renderMetrics.gradientTop;
|
||||||
|
uniforms.u_gradient_vertical_span.value = renderMetrics.gradientVerticalSpan;
|
||||||
|
uniforms.u_inverse_gradient_denominator.value =
|
||||||
|
renderMetrics.inverseGradientDenominator;
|
||||||
|
uniforms.u_intro_center_index.value = stripes.introCenterIndex;
|
||||||
|
uniforms.u_intro_center_distance.value = stripes.introCenterDistance;
|
||||||
|
};
|
||||||
|
|
||||||
|
const applyColors = (colors: ShaderColors) => {
|
||||||
|
uniforms.u_start_color.value = colors.start;
|
||||||
|
uniforms.u_highlight_delta.value = colors.highlightDelta;
|
||||||
|
uniforms.u_alpha.value = colors.alpha;
|
||||||
|
uniforms.u_intro_alpha.value = colors.introAlpha;
|
||||||
|
uniforms.u_speed_up_shine_boost.value = colors.speedUpShineBoost;
|
||||||
|
uniforms.u_grain_alpha.value = colors.grainAlpha;
|
||||||
|
uniforms.u_grain_luminance.value = colors.grainLuminance;
|
||||||
|
uniforms.u_grain_contrast.value = colors.grainContrast;
|
||||||
|
uniforms.u_grain_saturation.value = colors.grainSaturation;
|
||||||
|
};
|
||||||
|
|
||||||
|
applySize(initialSize);
|
||||||
|
applyColors(initialColors);
|
||||||
|
|
||||||
|
const resize = () => {
|
||||||
|
applySize(resizeOglCanvas(canvas, renderer));
|
||||||
|
};
|
||||||
|
|
||||||
|
const readColors = () => {
|
||||||
|
applyColors(readShaderColors(canvas, colorContext));
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
resize,
|
||||||
|
readColors,
|
||||||
|
render: ({
|
||||||
|
time,
|
||||||
|
wavePhase,
|
||||||
|
secondaryWavePhase,
|
||||||
|
introStartedAt,
|
||||||
|
shineProgress,
|
||||||
|
}) => {
|
||||||
|
uniforms.u_wave_phase.value = wavePhase;
|
||||||
|
uniforms.u_secondary_wave_phase.value = secondaryWavePhase;
|
||||||
|
uniforms.u_intro_active.value = introStartedAt === null ? 0 : 1;
|
||||||
|
uniforms.u_intro_elapsed.value = introStartedAt === null
|
||||||
|
? 0
|
||||||
|
: time - introStartedAt - INTRO.delay;
|
||||||
|
uniforms.u_shine_progress.value = shineProgress;
|
||||||
|
|
||||||
|
renderer.render({
|
||||||
|
scene: mesh,
|
||||||
|
clear: true,
|
||||||
|
frustumCull: false,
|
||||||
|
sort: false,
|
||||||
|
update: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
dispose: () => {
|
||||||
|
geometry.remove();
|
||||||
|
program.remove();
|
||||||
|
gl.deleteTexture(grainNoise.texture);
|
||||||
|
},
|
||||||
|
getStripeCount: () => stripes.count,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const IDLE_SPEED_UP: WaveSpeedUpValues = {
|
||||||
|
multiplier: 1,
|
||||||
|
shineProgress: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const PEAK_SPEED_UP: WaveSpeedUpValues = {
|
||||||
|
multiplier: WAVE_SPEED_UP.multiplier,
|
||||||
|
shineProgress: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
const lerpSpeedUpValues = (
|
||||||
|
from: WaveSpeedUpValues,
|
||||||
|
to: WaveSpeedUpValues,
|
||||||
|
progress: number,
|
||||||
|
): WaveSpeedUpValues => ({
|
||||||
|
multiplier: lerp(from.multiplier, to.multiplier, progress),
|
||||||
|
shineProgress: lerp(from.shineProgress, to.shineProgress, progress),
|
||||||
|
});
|
||||||
|
|
||||||
|
const getProgress = (time: number, startedAt: number, duration: number) =>
|
||||||
|
clamp((time - startedAt) / duration);
|
||||||
|
|
||||||
|
const getSpeedUpRampUpDuration = (from: WaveSpeedUpValues) => {
|
||||||
|
const multiplierRemaining = clamp(
|
||||||
|
(WAVE_SPEED_UP.multiplier - from.multiplier)
|
||||||
|
/ (WAVE_SPEED_UP.multiplier - 1),
|
||||||
|
);
|
||||||
|
const shineRemaining = 1 - from.shineProgress;
|
||||||
|
|
||||||
|
return Math.max(
|
||||||
|
1,
|
||||||
|
WAVE_SPEED_UP.rampUpDuration
|
||||||
|
* Math.max(multiplierRemaining, shineRemaining),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const isSpeedUpAtPeak = ({ multiplier, shineProgress }: WaveSpeedUpValues) =>
|
||||||
|
multiplier >= WAVE_SPEED_UP.multiplier && shineProgress >= 1;
|
||||||
|
|
||||||
|
export const triggerSpeedUpAnimation = (
|
||||||
|
time: number,
|
||||||
|
speedUpAnimation: WaveSpeedUpAnimation | null,
|
||||||
|
): WaveSpeedUpAnimation => {
|
||||||
|
const { multiplier, shineProgress } = updateSpeedUpAnimation(
|
||||||
|
time,
|
||||||
|
speedUpAnimation,
|
||||||
|
);
|
||||||
|
const from = { multiplier, shineProgress };
|
||||||
|
|
||||||
|
if (isSpeedUpAtPeak(from)) {
|
||||||
|
return {
|
||||||
|
phase: "hold",
|
||||||
|
startedAt: time,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
phase: "ramp-up",
|
||||||
|
startedAt: time,
|
||||||
|
duration: getSpeedUpRampUpDuration(from),
|
||||||
|
from,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const updateSpeedUpAnimation = (
|
||||||
|
time: number,
|
||||||
|
speedUpAnimation: WaveSpeedUpAnimation | null,
|
||||||
|
): WaveSpeedUpAnimationState => {
|
||||||
|
if (!speedUpAnimation) {
|
||||||
|
return {
|
||||||
|
animation: null,
|
||||||
|
...IDLE_SPEED_UP,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (speedUpAnimation.phase === "ramp-up") {
|
||||||
|
const progress = getProgress(
|
||||||
|
time,
|
||||||
|
speedUpAnimation.startedAt,
|
||||||
|
speedUpAnimation.duration,
|
||||||
|
);
|
||||||
|
const values = lerpSpeedUpValues(
|
||||||
|
speedUpAnimation.from,
|
||||||
|
PEAK_SPEED_UP,
|
||||||
|
easeOutCubic(progress),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (progress >= 1) {
|
||||||
|
return {
|
||||||
|
animation: {
|
||||||
|
phase: "hold",
|
||||||
|
startedAt: time,
|
||||||
|
},
|
||||||
|
...values,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
animation: speedUpAnimation,
|
||||||
|
...values,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (speedUpAnimation.phase === "hold") {
|
||||||
|
const progress = getProgress(
|
||||||
|
time,
|
||||||
|
speedUpAnimation.startedAt,
|
||||||
|
WAVE_SPEED_UP.waveDuration,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (progress >= 1) {
|
||||||
|
return {
|
||||||
|
animation: {
|
||||||
|
phase: "ramp-down",
|
||||||
|
startedAt: time,
|
||||||
|
from: PEAK_SPEED_UP,
|
||||||
|
},
|
||||||
|
...PEAK_SPEED_UP,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
animation: speedUpAnimation,
|
||||||
|
...PEAK_SPEED_UP,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const progress = getProgress(
|
||||||
|
time,
|
||||||
|
speedUpAnimation.startedAt,
|
||||||
|
WAVE_SPEED_UP.rampDownDuration,
|
||||||
|
);
|
||||||
|
const values = lerpSpeedUpValues(
|
||||||
|
speedUpAnimation.from,
|
||||||
|
IDLE_SPEED_UP,
|
||||||
|
easeInOutCubic(progress),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
animation: progress >= 1 ? null : speedUpAnimation,
|
||||||
|
...values,
|
||||||
|
};
|
||||||
|
};
|
||||||
Loading…
Add table
Reference in a new issue