Files
personal/components/webgl/StickerLayer.ts
T

472 lines
14 KiB
TypeScript

import * as THREE from "three";
/**
* Sticker particle layer — pixel-faithful re-implementation of the
* haoqi.design falling-sticker system.
*
* Reverse-engineered constants (from the production bundle):
* particleCount: 12 (one per texture)
* spawnWidth: 32
* clickSpawnWidth: 24
* spawnHeight: 24
* clickSpawnHeight: 24
* positionY: 24
* fallDistance: 48
* zDepth: 4
* zOffset: -6
* windStrength: 1.8
* windFrequency: 0.3
* scale: 1.4
* clickScale: 1.4
* rotationSpeed: 0.8
* fallSpeed: 1.8
* enterDurationRatio 0.05 (scale-in over first 5% of fall)
* exit over last 10% of fall
* one-shot cap: 384
* burst count: particleCount (12 per click)
* burst emit spacing 0.04 + 0.04s random
* respawn delay 0.04 + 0.04s random
*/
export const STICKER_CONFIG = {
particleCount: 12,
spawnWidth: 32,
clickSpawnWidth: 24,
spawnHeight: 24,
clickSpawnHeight: 24,
positionY: 24,
fallDistance: 48,
zDepth: 4,
zOffset: -6,
windStrength: 1.8,
windFrequency: 0.3,
scale: 1.4,
clickScale: 1.4,
rotationSpeed: 0.8,
fallSpeed: 1.8,
enterDurationRatio: 0.05,
oneShotCap: 384,
burstCount: 12,
maxVisible: 2048
} as const;
type StickerConfig = typeof STICKER_CONFIG;
type Particle = {
position: THREE.Vector3;
startY: number;
fallSpeed: number;
rotation: number;
rotationSpeed: number;
scale: number;
textureIndex: number;
windPhase: number;
windAmplitude: number;
emitAt: number;
hasStarted: boolean;
dead: boolean;
isOneShot: boolean;
originX: number;
originY: number;
originZ: number;
};
const VERTEX_SHADER = /* glsl */ `
attribute vec4 uvRect;
varying vec2 vAtlasUv;
void main() {
vAtlasUv = uvRect.xy + uv * uvRect.zw;
vec4 mvPosition = modelViewMatrix * instanceMatrix * vec4(position, 1.0);
gl_Position = projectionMatrix * mvPosition;
}
`;
const FRAGMENT_SHADER = /* glsl */ `
uniform sampler2D map;
varying vec2 vAtlasUv;
void main() {
vec4 color = texture2D(map, vAtlasUv);
if (color.a < 0.01) discard;
gl_FragColor = color;
#include <tonemapping_fragment>
#include <colorspace_fragment>
}
`;
function nextPow2(v: number) {
return Math.pow(2, Math.ceil(Math.log2(Math.max(1, v))));
}
function makeParticle(textureCount: number, isOneShot: boolean): Particle {
return {
position: new THREE.Vector3(),
startY: 0,
fallSpeed: 0,
rotation: 0,
rotationSpeed: 0,
scale: 1,
textureIndex: Math.floor(Math.random() * textureCount),
windPhase: 0,
windAmplitude: 0,
emitAt: 0,
hasStarted: true,
dead: false,
isOneShot,
originX: 0,
originY: 0,
originZ: 0
};
}
/** Shuffle texture indices across the initial particle pool. */
function makePool(count: number, textureCount: number, isOneShot: boolean): Particle[] {
const pool = Array.from({ length: count }, () => makeParticle(textureCount, isOneShot));
if (count > 0 && count <= textureCount) {
const indices = Array.from({ length: textureCount }, (_, i) => i);
for (let i = indices.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[indices[i], indices[j]] = [indices[j], indices[i]];
}
for (let i = 0; i < count; i++) pool[i].textureIndex = indices[i];
}
return pool;
}
/** Keep the one-shot population bounded (cap 384, newest kept). */
function compactOneShots(particles: Particle[]): Particle[] {
const alive = particles.filter((p) => !p.isOneShot || !p.dead);
const persistent = alive.filter((p) => !p.isOneShot);
const oneShots = alive.filter((p) => p.isOneShot);
if (oneShots.length <= STICKER_CONFIG.oneShotCap) return alive;
oneShots.sort((a, b) => b.emitAt - a.emitAt);
return persistent.concat(oneShots.slice(0, STICKER_CONFIG.oneShotCap));
}
/** Spawn a particle at a randomized position (mode: "scroll" | "click"). */
function spawn(p: Particle, cfg: StickerConfig, mode: "scroll" | "click") {
const {
spawnWidth, clickSpawnWidth, positionY, spawnHeight, clickSpawnHeight,
scale, clickScale, rotationSpeed, windStrength, zDepth, zOffset, fallSpeed
} = cfg;
const height = mode === "click" ? clickSpawnHeight : spawnHeight;
const jitter = Math.min(0.5 * Math.max(height, 0), 8);
const offset = mode === "click"
? positionY + (2 * Math.random() - 1) * jitter
: positionY + Math.random() * Math.max(height, 0);
p.position.set(
p.originX + (Math.random() - 0.5) * (mode === "click" ? clickSpawnWidth : spawnWidth),
p.originY + offset,
p.originZ + (Math.random() - 0.5) * zDepth + zOffset
);
p.startY = p.position.y;
p.fallSpeed = fallSpeed * (0.6 + 0.8 * Math.random());
p.rotation = Math.random() * Math.PI * 2;
p.rotationSpeed = (Math.random() - 0.5) * rotationSpeed * 2;
p.scale = mode === "click" ? clickScale : scale;
p.windPhase = Math.random() * Math.PI * 2;
p.windAmplitude = 0.3 + Math.random() * windStrength;
p.dead = false;
p.hasStarted = true;
p.emitAt = 0;
}
/**
* Pick a texture index not currently in flight (falls back to a random one).
*/
function pickUnusedTexture(count: number, used: Set<number>): number {
if (count <= 0) return 0;
if (used.size >= count) return Math.floor(Math.random() * count);
const free: number[] = [];
for (let i = 0; i < count; i++) if (!used.has(i)) free.push(i);
return free[Math.floor(Math.random() * free.length)];
}
type AtlasResult = {
texture: THREE.CanvasTexture;
uvRects: Float32Array;
aspects: number[];
};
type Loaded = { image: HTMLImageElement; width: number; height: number };
function buildAtlas(loaded: Loaded[]): AtlasResult | null {
if (loaded.length === 0) return null;
const maxWidth = Math.max(...loaded.map((l) => l.width));
const maxHeight = Math.max(...loaded.map((l) => l.height));
const cols = Math.ceil(Math.sqrt(loaded.length));
const rows = Math.ceil(loaded.length / cols);
const cellW = maxWidth + 4;
const cellH = maxHeight + 4;
const size = nextPow2(Math.max(cols * cellW, rows * cellH));
const cw = nextPow2(cols * cellW);
const ch = nextPow2(rows * cellH);
const canvas = document.createElement("canvas");
canvas.width = cw;
canvas.height = ch;
const ctx = canvas.getContext("2d");
if (!ctx) return null;
ctx.clearRect(0, 0, cw, ch);
const uvRects = new Float32Array(4 * loaded.length);
const aspects: number[] = [];
loaded.forEach((item, i) => {
const row = Math.floor(i / cols);
const x = (i % cols) * cellW + 2;
const y = row * cellH + 2;
ctx.drawImage(item.image, x, y, item.width, item.height);
const k = 4 * i;
uvRects[k] = (x + 0.5) / cw;
uvRects[k + 1] = 1 - (y + item.height - 0.5) / ch;
uvRects[k + 2] = (item.width - 1) / cw;
uvRects[k + 3] = (item.height - 1) / ch;
aspects.push(item.width / item.height);
});
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.wrapS = THREE.ClampToEdgeWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
texture.generateMipmaps = false;
texture.needsUpdate = true;
return { texture, uvRects, aspects };
}
function loadImage(url: string): Promise<Loaded> {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => resolve({ image, width: image.naturalWidth, height: image.naturalHeight });
image.onerror = () => reject(new Error(`Failed to load ${url}`));
image.src = url;
});
}
/** Insert keeping ascending-z order (far → near, matches painter order). */
function insertSorted(list: Particle[], p: Particle) {
const z = p.position.z;
let lo = 0;
let hi = list.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (list[mid].position.z <= z) lo = mid + 1;
else hi = mid;
}
list.push(p);
for (let i = list.length - 1; i > lo; i--) list[i] = list[i - 1];
list[lo] = p;
}
export class StickerLayer {
private scene: THREE.Scene;
private config: StickerConfig;
private mesh: THREE.InstancedMesh | null = null;
private geometry: THREE.PlaneGeometry | null = null;
private material: THREE.ShaderMaterial | null = null;
private atlas: AtlasResult | null = null;
private particles: Particle[] = [];
private sortBuffer: Particle[] = [];
private dummy = new THREE.Object3D();
private time = 0;
private lastEmit = 0;
private usedTextures = new Set<number>();
private initialized = false;
private disposed = false;
private loader: THREE.TextureLoader | null = null;
constructor(scene: THREE.Scene, config?: Partial<StickerConfig>) {
this.scene = scene;
this.config = { ...STICKER_CONFIG, ...config };
}
/** Load all sticker textures and build the shared atlas + instanced mesh. */
async load(images: string[]) {
if (this.initialized || this.disposed) return;
const loader = new THREE.TextureLoader();
this.loader = loader;
// Load via Image elements (needed for the canvas atlas anyway).
const loaded = await Promise.all(images.map(loadImage));
if (this.disposed) return;
this.atlas = buildAtlas(loaded);
if (!this.atlas) return;
const geometry = new THREE.PlaneGeometry(2, 2);
geometry.setAttribute(
"uvRect",
new THREE.InstancedBufferAttribute(new Float32Array(STICKER_CONFIG.maxVisible * 4), 4)
);
const material = new THREE.ShaderMaterial({
uniforms: { map: { value: this.atlas.texture } },
vertexShader: VERTEX_SHADER,
fragmentShader: FRAGMENT_SHADER,
transparent: true,
depthWrite: false,
side: THREE.FrontSide,
toneMapped: false
});
const mesh = new THREE.InstancedMesh(
geometry,
material,
STICKER_CONFIG.maxVisible
);
mesh.frustumCulled = false;
mesh.count = 0;
this.geometry = geometry;
this.material = material;
this.mesh = mesh;
this.scene.add(mesh);
// Seed the persistent pool: one particle per texture, shuffled.
const particles = makePool(
Math.max(1, this.config.particleCount ?? images.length),
this.atlas.aspects.length,
false
); for (const p of particles) spawn(p, this.config, "scroll");
this.particles = particles;
this.initialized = true;
// Debug hook for browser-console inspection.
if (typeof window !== "undefined") {
(window as unknown as Record<string, unknown>).__stickerLayer = this;
}
}
/** Spawn a one-shot burst at a world-space point. */
burst(point: THREE.Vector3) {
if (!this.atlas || !this.initialized) return;
const pool = makePool(this.config.burstCount, this.atlas.aspects.length, true);
let delay = 0.05 * Math.random();
for (const p of pool) {
p.hasStarted = false;
p.dead = false;
p.emitAt = delay;
delay += 0.04 + 0.04 * Math.random();
}
const originX = point.x;
const originY = point.y - this.config.positionY;
for (const p of pool) {
p.originX = originX;
p.originY = originY;
p.originZ = 0;
p.emitAt += this.time;
}
this.particles = compactOneShots(this.particles.concat(pool));
}
/** Advance the simulation and update instance buffers. dt in seconds. */
update(dt: number) {
const mesh = this.mesh;
const atlas = this.atlas;
if (!mesh || !atlas || !this.initialized) return;
const step = Math.min(dt, 0.1);
this.time += step;
const used = this.usedTextures;
used.clear();
for (const p of this.particles) {
if (!p.isOneShot && !p.dead && p.hasStarted) used.add(p.textureIndex);
}
const sortBuffer = this.sortBuffer;
sortBuffer.length = 0;
const { fallDistance, windFrequency, enterDurationRatio } = this.config;
for (const p of this.particles) {
// Both persistent respawns and queued one-shots wait for emitAt,
// then spawn with click-mode jitter (same as the original).
if (!p.hasStarted) {
if (this.time < p.emitAt) continue;
spawn(p, this.config, "click");
}
if (p.dead) continue;
p.position.y -= p.fallSpeed * step;
const wind = Math.sin(this.time * windFrequency + p.windPhase) * p.windAmplitude;
p.position.x += wind * step;
p.rotation += p.rotationSpeed * step;
const progress = (p.startY - p.position.y) / fallDistance;
const clamped = THREE.MathUtils.clamp(progress, 0, 1);
let factor = 1;
const enter = enterDurationRatio ?? 0.05;
if (enter > 0 && clamped < enter) factor = clamped / enter;
else if (clamped > 0.9) factor = (1 - clamped) / 0.1;
factor = THREE.MathUtils.clamp(factor, 0, 1);
if (p.position.y < p.startY - fallDistance) {
if (p.isOneShot) {
p.dead = true;
continue;
}
// Retire, then respawn with a different texture after a short delay.
used.delete(p.textureIndex);
p.textureIndex = pickUnusedTexture(atlas.aspects.length, used);
p.emitAt = Math.max(this.lastEmit, this.time) + (0.04 + 0.04 * Math.random());
this.lastEmit = p.emitAt;
p.hasStarted = false;
continue;
}
p.scale = factor;
if (sortBuffer.length < 96) insertSorted(sortBuffer, p);
else sortBuffer.push(p);
}
if (sortBuffer.length > 96) sortBuffer.sort((a, b) => a.position.z - b.position.z);
const uvRect = mesh.geometry.getAttribute("uvRect") as THREE.InstancedBufferAttribute;
const count = Math.min(sortBuffer.length, this.config.maxVisible);
const dummy = this.dummy;
for (let i = 0; i < count; i++) {
const p = sortBuffer[i];
const aspect = atlas.aspects[p.textureIndex] ?? 1;
const size = (p.isOneShot ? this.config.clickScale : this.config.scale) * p.scale;
const k = 4 * p.textureIndex;
dummy.position.copy(p.position);
dummy.rotation.set(0, 0, p.rotation);
dummy.scale.set(size * aspect, size, 1);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
uvRect.setXYZW(i, atlas.uvRects[k], atlas.uvRects[k + 1], atlas.uvRects[k + 2], atlas.uvRects[k + 3]);
}
mesh.count = count;
mesh.visible = count > 0;
mesh.instanceMatrix.needsUpdate = true;
uvRect.needsUpdate = true;
}
dispose() {
this.disposed = true;
if (this.mesh) {
this.scene.remove(this.mesh);
this.mesh.dispose();
this.mesh = null;
}
this.geometry?.dispose();
this.material?.dispose();
if (this.atlas) {
this.atlas.texture.dispose();
this.atlas = null;
}
this.loader = null;
this.particles = [];
}
}