All checks were successful
Build and Deploy Nuxt / build (push) Successful in 2m26s
387 lines
10 KiB
Vue
387 lines
10 KiB
Vue
<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>
|