Cards!
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 2m26s

This commit is contained in:
2026-09-20 03:15:16 +02:00
parent ed187af3dd
commit 770f302bc3
34 changed files with 3302 additions and 677 deletions

View File

@@ -0,0 +1,386 @@
<script setup lang="ts">
const props = withDefaults(
defineProps<{ color?: string }>(),
{ color: '#d8d2c6' }
);
const ATLAS_URL = 'https://cdn.aranroig.com/web/assets/cards.png';
const CARD_COLS = 5;
const CARD_ROWS = 11;
const CARD_BACK_FACE = 9 * CARD_COLS + 2;
const DECK_SIZE = 24;
const CARD_WIDTH = 1.15;
const CARD_DEPTH = 0.008;
const FAN_RADIUS = 1.7;
const FAN_SPREAD = 0.03;
const FOV = 40;
const FIT_HALF_H = 1.05;
const FIT_HALF_W = 1.8;
const root = ref<HTMLDivElement | null>(null);
let disposeScene: (() => void) | null = null;
let pendingColor: string | null = props.color;
let cancelled = false;
let cancelSchedule: (() => void) | null = null;
let io: IntersectionObserver | null = null;
watch(
() => props.color,
(c) => {
pendingColor = c;
}
);
const init = async () => {
const el = root.value;
if (!el || cancelled) return;
const {
Scene,
PerspectiveCamera,
WebGLRenderer,
TextureLoader,
SRGBColorSpace,
MeshBasicMaterial,
BoxGeometry,
Mesh,
Group,
Color,
Vector2,
Clock,
MathUtils
} = await import('three');
if (cancelled) return;
const scene = new Scene();
const camera = new PerspectiveCamera(FOV, 1, 0.1, 100);
const renderer = new WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
el.appendChild(renderer.domElement);
let texture;
try {
texture = await new TextureLoader().loadAsync(ATLAS_URL);
} catch (e) {
console.warn('HiboliaDeckPreview: failed to load card atlas (CORS?)', e);
el.removeChild(renderer.domElement);
return;
}
if (cancelled) {
texture.dispose();
renderer.dispose();
if (renderer.domElement.parentElement === el) el.removeChild(renderer.domElement);
return;
}
texture.colorSpace = SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const cellW = texture.image.width / CARD_COLS;
const cellH = texture.image.height / CARD_ROWS;
const cardHeight = CARD_WIDTH * (cellH / cellW);
const marginU = 0.5 / cellW;
const marginV = 0.5 / cellH;
const faceMaterial = new MeshBasicMaterial({ map: texture, transparent: true });
const backMaterial = new MeshBasicMaterial({ map: texture, transparent: true });
const sideMaterial = new MeshBasicMaterial({
color: new Color(pendingColor || '#d8d2c6'),
transparent: true
});
pendingColor = null;
// Round the card corners with an anti-aliased rounded-rect SDF in the shader.
// The half-size is widened by a sliver so the box's side faces sit strictly
// inside the SDF (they lie exactly on the boundary otherwise).
const CORNER_RADIUS = 0.09;
const CORNER_SDF_EPS = 0.01;
const BORDER_WIDTH = 0.014;
const uEdgeColor = { value: new Color().copy(sideMaterial.color) };
const applyRoundedCorners = (mat: any, withBorder: boolean) => {
mat.onBeforeCompile = (shader: any) => {
shader.uniforms.uHalfSize = {
value: new Vector2(
CARD_WIDTH / 2 + CORNER_SDF_EPS,
cardHeight / 2 + CORNER_SDF_EPS
)
};
shader.uniforms.uRadius = { value: CORNER_RADIUS };
shader.uniforms.uEdgeColor = uEdgeColor;
shader.uniforms.uBorderWidth = { value: BORDER_WIDTH };
shader.vertexShader = shader.vertexShader
.replace(
'#include <common>',
'#include <common>\nvarying vec2 vCardPos;'
)
.replace(
'#include <begin_vertex>',
'#include <begin_vertex>\nvCardPos = position.xy;'
);
shader.fragmentShader = shader.fragmentShader
.replace(
'#include <common>',
`#include <common>
varying vec2 vCardPos;
uniform vec2 uHalfSize;
uniform float uRadius;
uniform vec3 uEdgeColor;
uniform float uBorderWidth;`
)
.replace(
'#include <color_fragment>',
`#include <color_fragment>
vec2 q = abs(vCardPos) - uHalfSize + uRadius;
float sd = min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - uRadius;
float fw = fwidth(sd);${
withBorder
? `
float border = smoothstep(-uBorderWidth - fw, -uBorderWidth + fw, sd);
diffuseColor.rgb = mix(diffuseColor.rgb, uEdgeColor, border);`
: ''
}
diffuseColor.a *= 1.0 - smoothstep(-fw, fw, sd);`
);
mat.userData.shader = shader;
};
mat.needsUpdate = true;
};
applyRoundedCorners(faceMaterial, true);
applyRoundedCorners(backMaterial, true);
applyRoundedCorners(sideMaterial, false);
// BoxGeometry face order: +X, -X, +Y, -Y, +Z(front), -Z(back); 4 verts each.
const applyFaceUV = (geometry: any, vertexStart: number, face: number) => {
const col = face % CARD_COLS;
const row = Math.floor(face / CARD_COLS);
const uv = geometry.attributes.uv;
for (let i = 0; i < 4; i++) {
const idx = vertexStart + i;
const u = (col + marginU + uv.getX(idx) * (1 - 2 * marginU)) / CARD_COLS;
const v = (CARD_ROWS - 1 - row + marginV + uv.getY(idx) * (1 - 2 * marginV)) / CARD_ROWS;
uv.setXY(idx, u, v);
}
uv.needsUpdate = true;
};
const rig = new Group();
const pitchGroup = new Group();
rig.add(pitchGroup);
scene.add(rig);
const fan = new Group();
fan.rotation.x = Math.PI / 2 - 0.32;
pitchGroup.add(fan);
const geometries: any[] = [];
for (let i = 0; i < DECK_SIZE; i++) {
const geometry = new BoxGeometry(CARD_WIDTH, cardHeight, CARD_DEPTH);
applyFaceUV(geometry, 16, Math.floor(Math.random() * CARD_COLS * CARD_ROWS));
applyFaceUV(geometry, 20, CARD_BACK_FACE);
geometries.push(geometry);
const mesh = new Mesh(geometry, [
sideMaterial,
sideMaterial,
sideMaterial,
sideMaterial,
faceMaterial,
backMaterial
]);
const pivot = new Group();
pivot.rotation.z = (i - (DECK_SIZE - 1) / 2) * FAN_SPREAD;
mesh.position.y = -FAN_RADIUS;
mesh.position.z = (i - (DECK_SIZE - 1) / 2) * CARD_DEPTH;
pivot.add(mesh);
fan.add(pivot);
}
fan.position.set(
0,
FAN_RADIUS * Math.cos(fan.rotation.x),
FAN_RADIUS * Math.sin(fan.rotation.x)
);
const targetColor = new Color(sideMaterial.color);
const resize = () => {
const width = el.clientWidth;
const height = el.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height);
camera.aspect = width / height;
const tanHalfFov = Math.tan(MathUtils.degToRad(FOV / 2));
const dist = Math.max(
FIT_HALF_H / tanHalfFov,
FIT_HALF_W / (tanHalfFov * camera.aspect)
);
const elevation = 1.22;
camera.position.set(
0,
Math.sin(elevation) * dist + 0.15,
Math.cos(elevation) * dist
);
camera.lookAt(0, 0.1, 0);
camera.updateProjectionMatrix();
};
resize();
const observer = new ResizeObserver(resize);
observer.observe(el);
let yaw = 0;
let pitch = 0;
let targetYaw = 0;
let targetPitch = 0;
let dragging = false;
let interacted = false;
let lastX = 0;
let lastY = 0;
const onPointerDown = (e: PointerEvent) => {
dragging = true;
interacted = true;
lastX = e.clientX;
lastY = e.clientY;
el.setPointerCapture(e.pointerId);
};
const onPointerMove = (e: PointerEvent) => {
if (!dragging) return;
targetYaw -= (e.clientX - lastX) * 0.008;
targetPitch = MathUtils.clamp(
targetPitch + (e.clientY - lastY) * 0.006,
-1.35,
1.35
);
lastX = e.clientX;
lastY = e.clientY;
};
const onPointerUp = () => {
dragging = false;
};
el.addEventListener('pointerdown', onPointerDown);
el.addEventListener('pointermove', onPointerMove);
el.addEventListener('pointerup', onPointerUp);
el.addEventListener('pointercancel', onPointerUp);
const clock = new Clock();
let frameId = 0;
let running = false;
const animate = () => {
if (!running) return;
frameId = requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (pendingColor) {
targetColor.set(pendingColor);
pendingColor = null;
}
sideMaterial.color.lerp(targetColor, 1 - Math.exp(-10 * dt));
uEdgeColor.value.copy(sideMaterial.color);
if (!interacted) {
targetYaw = Math.sin(clock.elapsedTime * 0.45) * 0.22;
}
const ease = 1 - Math.exp(-8 * dt);
yaw += (targetYaw - yaw) * ease;
pitch += (targetPitch - pitch) * ease;
rig.rotation.z = yaw;
pitchGroup.rotation.x = pitch;
renderer.render(scene, camera);
};
// Pause the loop while the tab is hidden to free the main thread and GPU.
const startLoop = () => {
if (running) return;
running = true;
clock.getDelta();
frameId = requestAnimationFrame(animate);
};
const stopLoop = () => {
if (!running) return;
running = false;
cancelAnimationFrame(frameId);
};
const removeVisibility = onVisibility((hidden) => (hidden ? stopLoop() : startLoop()));
startLoop();
disposeScene = () => {
stopLoop();
removeVisibility();
observer.disconnect();
el.removeEventListener('pointerdown', onPointerDown);
el.removeEventListener('pointermove', onPointerMove);
el.removeEventListener('pointerup', onPointerUp);
el.removeEventListener('pointercancel', onPointerUp);
for (const geometry of geometries) {
geometry.dispose();
}
faceMaterial.dispose();
backMaterial.dispose();
sideMaterial.dispose();
texture.dispose();
renderer.dispose();
if (renderer.domElement.parentElement === el) {
el.removeChild(renderer.domElement);
}
};
};
onMounted(() => {
const el = root.value;
if (!el) return;
// Defer the heavy scene until the preview is actually near the viewport.
io = new IntersectionObserver(
(entries) => {
if (!entries.some((e) => e.isIntersecting)) return;
io?.disconnect();
io = null;
cancelSchedule = scheduleIdle(() => {
init();
});
},
{ rootMargin: '200px' }
);
io.observe(el);
});
onBeforeUnmount(() => {
cancelled = true;
io?.disconnect();
cancelSchedule?.();
disposeScene?.();
});
</script>
<template>
<div ref="root" class="three-root" role="img" aria-label="Vista previa de la baraja">
<div class="three-bg" aria-hidden="true"></div>
</div>
</template>
<style lang="scss" scoped>
.three-root {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
cursor: grab;
touch-action: none;
&:active {
cursor: grabbing;
}
.three-bg {
position: absolute;
inset: 0;
background: var(--color-background);
}
:deep(canvas) {
position: relative;
z-index: 1;
display: block;
}
}
</style>

View File

@@ -0,0 +1,303 @@
<script setup lang="ts">
const ATLAS_URL = 'https://cdn.aranroig.com/web/assets/cards.png';
const CARD_COLS = 5;
const CARD_ROWS = 11;
const CARD_COUNT = 20;
const CARD_LANES = 5;
const CARD_SPEED = 1.1;
const CARD_WIDTH = 1.15;
const CARD_BACK_FACE = 9 * CARD_COLS + 2;
const root = ref<HTMLDivElement | null>(null);
let disposeScene: (() => void) | null = null;
let cancelled = false;
let cancelSchedule: (() => void) | null = null;
const init = async () => {
const el = root.value;
if (!el || cancelled) return;
const {
Scene,
PerspectiveCamera,
WebGLRenderer,
TextureLoader,
SRGBColorSpace,
MeshBasicMaterial,
PlaneGeometry,
Mesh,
Vector2,
Vector3,
Color,
Clock,
MathUtils
} = await import('three');
if (cancelled) return;
const scene = new Scene();
const camera = new PerspectiveCamera(45, 1, 0.1, 100);
camera.position.z = 4;
const renderer = new WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(1);
el.appendChild(renderer.domElement);
let texture;
try {
texture = await new TextureLoader().loadAsync(ATLAS_URL);
} catch (e) {
console.warn('HiboliaScene: failed to load card atlas (CORS?)', e);
el.removeChild(renderer.domElement);
return;
}
if (cancelled) {
texture.dispose();
renderer.dispose();
if (renderer.domElement.parentElement === el) el.removeChild(renderer.domElement);
return;
}
texture.colorSpace = SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const cellW = texture.image.width / CARD_COLS;
const cellH = texture.image.height / CARD_ROWS;
const cardHeight = CARD_WIDTH * (cellH / cellW);
const material = new MeshBasicMaterial({
map: texture,
transparent: true
});
const backMaterial = new MeshBasicMaterial({
map: texture,
transparent: true
});
// Round the card corners with an anti-aliased rounded-rect SDF in the shader.
const CORNER_RADIUS = 0.09;
const applyRoundedCorners = (mat: any) => {
mat.onBeforeCompile = (shader: any) => {
shader.uniforms.uHalfSize = { value: new Vector2(CARD_WIDTH / 2, cardHeight / 2) };
shader.uniforms.uRadius = { value: CORNER_RADIUS };
shader.vertexShader = shader.vertexShader
.replace(
'#include <common>',
'#include <common>\nvarying vec2 vCardPos;'
)
.replace(
'#include <begin_vertex>',
'#include <begin_vertex>\nvCardPos = position.xy;'
);
shader.fragmentShader = shader.fragmentShader
.replace(
'#include <common>',
`#include <common>
varying vec2 vCardPos;
uniform vec2 uHalfSize;
uniform float uRadius;`
)
.replace(
'#include <color_fragment>',
`#include <color_fragment>
vec2 q = abs(vCardPos) - uHalfSize + uRadius;
float sd = min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - uRadius;
diffuseColor.a *= 1.0 - smoothstep(-fwidth(sd), fwidth(sd), sd);`
);
mat.userData.shader = shader;
};
mat.needsUpdate = true;
};
applyRoundedCorners(material);
applyRoundedCorners(backMaterial);
let viewHalfW = 2;
let viewHalfH = 1.66;
const updateView = () => {
viewHalfH = camera.position.z * Math.tan(MathUtils.degToRad(camera.fov / 2));
viewHalfW = viewHalfH * camera.aspect;
};
// Inset UVs half a pixel inside each atlas cell to stop neighbors bleeding in.
const marginU = 0.5 / cellW;
const marginV = 0.5 / cellH;
// Shift the plane's UVs into one cell of the atlas: col across 5 columns,
// row from the top of the image (v origin is bottom-left in three.js).
const applyCardFace = (geometry: any, face: number) => {
const col = face % CARD_COLS;
const row = Math.floor(face / CARD_COLS);
const uv = geometry.attributes.uv;
if (!geometry.userData.baseUv) {
geometry.userData.baseUv = Float32Array.from(uv.array);
}
const base = geometry.userData.baseUv;
for (let i = 0; i < uv.count; i++) {
const u = (col + marginU + base[i * 2] * (1 - 2 * marginU)) / CARD_COLS;
const v = (CARD_ROWS - 1 - row + marginV + base[i * 2 + 1] * (1 - 2 * marginV)) / CARD_ROWS;
uv.setXY(i, u, v);
}
uv.needsUpdate = true;
};
const cards: any[] = [];
const respawn = (card: any, initial: boolean) => {
const topY = viewHalfH + cardHeight;
const bottomY = -viewHalfH - cardHeight;
card.mesh.position.set(
-viewHalfW + (viewHalfW * 2 / CARD_LANES) * (card.slot % CARD_LANES + 0.5) + MathUtils.randFloatSpread(0.3),
initial
? bottomY + (topY - bottomY) * (1 - (card.slot + 0.5) / CARD_COUNT)
: topY,
MathUtils.randFloat(-1.5, 0.5)
);
card.mesh.rotation.set(
MathUtils.randFloat(-0.3, 0.3),
MathUtils.randFloat(-0.4, 0.4),
MathUtils.randFloat(-0.3, 0.3)
);
card.spin.set(
MathUtils.randFloatSpread(1.6),
MathUtils.randFloatSpread(1.6),
MathUtils.randFloatSpread(0.9)
);
applyCardFace(card.geometry, Math.floor(Math.random() * CARD_COLS * CARD_ROWS));
};
for (let i = 0; i < CARD_COUNT; i++) {
const geometry = new PlaneGeometry(CARD_WIDTH, cardHeight);
const mesh = new Mesh(geometry, material);
const backGeometry = new PlaneGeometry(CARD_WIDTH, cardHeight);
applyCardFace(backGeometry, CARD_BACK_FACE);
const backMesh = new Mesh(backGeometry, backMaterial);
backMesh.rotation.y = Math.PI;
backMesh.position.z = -0.001;
mesh.add(backMesh);
scene.add(mesh);
const card = { mesh, geometry, backGeometry, slot: i, spin: new Vector3() };
respawn(card, true);
cards.push(card);
}
const resize = () => {
const width = el.clientWidth;
const height = el.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
updateView();
};
resize();
const observer = new ResizeObserver(resize);
observer.observe(el);
// Solid canvas background tracking the active theme's --color-background.
const applyBackground = () => {
const bg = getComputedStyle(document.documentElement)
.getPropertyValue('--color-background')
.trim();
renderer.setClearColor(new Color(bg || '#0e0e0e'), 1);
};
applyBackground();
const themeObserver = new MutationObserver(applyBackground);
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme']
});
const clock = new Clock();
let frameId = 0;
let running = false;
const animate = () => {
if (!running) return;
frameId = requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
for (const card of cards) {
card.mesh.position.y -= CARD_SPEED * dt;
card.mesh.rotation.x += card.spin.x * dt;
card.mesh.rotation.y += card.spin.y * dt;
card.mesh.rotation.z += card.spin.z * dt;
if (card.mesh.position.y < -viewHalfH - cardHeight) {
respawn(card, false);
}
}
renderer.render(scene, camera);
};
// Pause the loop while the tab is hidden to free the main thread and GPU.
const startLoop = () => {
if (running) return;
running = true;
clock.getDelta();
frameId = requestAnimationFrame(animate);
};
const stopLoop = () => {
if (!running) return;
running = false;
cancelAnimationFrame(frameId);
};
const removeVisibility = onVisibility((hidden) => (hidden ? stopLoop() : startLoop()));
startLoop();
disposeScene = () => {
stopLoop();
removeVisibility();
observer.disconnect();
themeObserver.disconnect();
for (const card of cards) {
card.geometry.dispose();
card.backGeometry.dispose();
}
material.dispose();
backMaterial.dispose();
texture.dispose();
renderer.dispose();
if (renderer.domElement.parentElement === el) {
el.removeChild(renderer.domElement);
}
};
};
onMounted(() => {
cancelSchedule = scheduleIdle(() => {
init();
});
});
onBeforeUnmount(() => {
cancelled = true;
cancelSchedule?.();
disposeScene?.();
});
</script>
<template>
<div ref="root" class="three-root">
<div class="three-bg" aria-hidden="true"></div>
</div>
</template>
<style lang="scss" scoped>
.three-root {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
.three-bg {
position: absolute;
inset: 0;
background: var(--color-background);
}
:deep(canvas) {
position: relative;
z-index: 1;
display: block;
}
}
</style>