sokko-g/website/src/features/cards/holoLightning.js
Shinuwa 3b2dae0168
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 22m53s
Validate and deploy Sokko G / deploy (push) Successful in 14s
Refuse layered finishes without their files and lighten idle particle cards
The catalog now marks the prismatic parallax as a layered effect, and the
service refuses to create a variation or change its finish to it when the card
lacks the cutout and backdrop for that format; existing variations stay as they
are. A test keeps the interface and the server in agreement for every card and
finish. Particle cards no longer hold canvas pixels at rest, build their motif
sprites on first use from a cache shared by all cards, and fade remaining
twinkles and fireflies within half a second once the pointer leaves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:06:20 +01:00

241 lines
11 KiB
JavaScript

// Rôle : moteur des éclairs holographiques d'une carte mythique, dessinés sur un Canvas 2D posé dans l'illustration. Des
// éclairs fractals partent des bords, progressent vers un point libre autour du héros avec une pointe lumineuse, se
// ramifient, puis frappent dans un éclat bref avant de s'éteindre. Couleurs de la palette, temps réel (indépendant de
// la fréquence d'affichage), aucune boucle quand la carte est au repos.
import { canvasBacking } from "./flareSprites.js";
const TAU = Math.PI * 2;
// Paliers 1 à 5 : intensité (épaisseur, halo, éclat d'impact) et fréquence (intervalle moyen entre deux éclairs, éclairs simultanés).
const INTENSITY_SCALE = [0.6, 0.8, 1, 1.25, 1.5];
const SPAWN_INTERVAL_MS = [1800, 1250, 850, 560, 360];
const MAX_BOLTS = [2, 2, 3, 3, 4];
const GROW_MS = [170, 260];
const HOLD_MS = 140;
const FADE_MS = [420, 620];
const IMPACT_MS = 320;
const between = (random, [min, max]) => min + random() * (max - min);
const pick = (random, items) => items[Math.floor(random() * items.length) % items.length];
// Tracé fractal par déplacement du point milieu : chaque subdivision décale le milieu perpendiculairement au segment, de
// moins en moins à chaque niveau. 2^depth segments (32 par défaut), extrémités conservées.
export function boltPath(start, end, random, { depth = 5, roughness = 0.24 } = {}) {
let points = [start, end];
let offset = Math.hypot(end.x - start.x, end.y - start.y) * roughness;
for (let level = 0; level < depth; level++) {
const next = [points[0]];
for (let index = 1; index < points.length; index++) {
const from = points[index - 1];
const to = points[index];
const dx = to.x - from.x;
const dy = to.y - from.y;
const length = Math.hypot(dx, dy) || 1;
const shift = (random() - 0.5) * offset;
next.push({ x: (from.x + to.x) / 2 - (dy / length) * shift, y: (from.y + to.y) / 2 + (dx / length) * shift }, to);
}
points = next;
offset *= 0.55;
}
return points;
}
// Point d'arrivée tiré dans une zone ovale autour du centre de l'illustration, à une distance comprise entre `min` et `max`
// (fractions de la largeur et de la hauteur) : un éclair peut s'arrêter plus haut, plus à droite, ou dépasser le milieu.
function targetIn(center, width, height, random, [min, max]) {
const angle = random() * TAU;
const distance = min + Math.sqrt(random()) * (max - min);
return { x: center.x + Math.cos(angle) * width * distance, y: center.y + Math.sin(angle) * height * distance * 0.9 };
}
// Géométrie d'un éclair dans une zone width x height : départ sur une ellipse qui déborde des bords (le canvas coupe),
// arrivée en un point libre de la zone centrale de `focus` (la boîte de l'illustration dans le canvas, tout le canvas par
// défaut : sur toute la carte, les éclairs partent des bords de la carte et visent toujours le héros). Derrière un héros détouré, la zone va jusqu'au cœur : le héros le
// recouvre. Sans héros détouré, elle garde un petit vide au centre pour épargner son visage.
export const TARGET_ZONE = { behind: [0, 0.32], flat: [0.14, 0.38] };
export function boltGeometry(width, height, angle, random, { behindSubject = false, focus = null } = {}) {
const box = focus || { x: 0, y: 0, width, height };
const center = { x: box.x + box.width / 2, y: box.y + box.height * 0.48 };
const zone = behindSubject ? TARGET_ZONE.behind : TARGET_ZONE.flat;
const startAngle = angle + (random() - 0.5) * 0.9;
const start = { x: width / 2 + Math.cos(startAngle) * width * 0.66, y: height / 2 + Math.sin(startAngle) * height * 0.62 };
const end = targetIn(center, box.width, box.height, random, zone);
const main = boltPath(start, end, random);
// Une ou deux ramifications partent du premier tiers du tronc vers un autre point de la zone, sans l'atteindre : elles
// s'écartent du tronc puis s'éteignent en chemin.
const branches = [];
const branchCount = random() < 0.7 ? (random() < 0.35 ? 2 : 1) : 0;
for (let index = 0; index < branchCount; index++) {
const from = main[Math.floor(main.length * (0.25 + random() * 0.3))];
const aim = targetIn(center, box.width, box.height, random, zone);
const reach = 0.45 + random() * 0.25;
branches.push(boltPath(from, { x: from.x + (aim.x - from.x) * reach, y: from.y + (aim.y - from.y) * reach }, random, { depth: 4, roughness: 0.2 }));
}
return { center, main, branches };
}
function partialPath(context, points, fraction) {
const span = (points.length - 1) * Math.min(1, fraction);
const whole = Math.floor(span);
context.beginPath();
context.moveTo(points[0].x, points[0].y);
for (let index = 1; index <= whole; index++) context.lineTo(points[index].x, points[index].y);
let tip = points[whole];
if (whole < points.length - 1) {
const next = points[whole + 1];
const rest = span - whole;
tip = { x: tip.x + (next.x - tip.x) * rest, y: tip.y + (next.y - tip.y) * rest };
context.lineTo(tip.x, tip.y);
}
return tip;
}
// Trois passes additives au lieu d'un `shadowBlur`, coûteux : halo large et pâle, gaine colorée, cœur clair.
function strokeBolt(context, points, fraction, { color, core, width, alpha }) {
const passes = [[width * 6, color, 0.2], [width * 2.6, color, 0.75], [width, core, 1]];
let tip = points[0];
for (const [lineWidth, strokeStyle, opacity] of passes) {
context.globalAlpha = alpha * opacity;
context.lineWidth = lineWidth;
context.strokeStyle = strokeStyle;
tip = partialPath(context, points, fraction);
context.stroke();
}
return tip;
}
function glow(context, x, y, radius, color, alpha) {
const gradient = context.createRadialGradient(x, y, 0, x, y, radius);
gradient.addColorStop(0, color);
gradient.addColorStop(1, "transparent");
context.globalAlpha = alpha;
context.fillStyle = gradient;
context.beginPath();
context.arc(x, y, radius, 0, TAU);
context.fill();
}
export function createLightning(canvas, options) {
const context = canvas.getContext("2d");
const backing = canvasBacking(canvas);
const random = options.random || Math.random;
let settings = { ...options };
let size = { width: 0, height: 0, ratio: 1 };
let bolts = [];
let impacts = [];
let pointer = null;
let active = false;
let frame = 0;
let nextSpawn = 0;
let destroyed = false;
const scale = () => INTENSITY_SCALE[(settings.intensity || 3) - 1];
const level = () => (settings.level || 3) - 1;
function spawn(now) {
// Une fois sur deux, l'éclair vient du côté où se trouve le pointeur : la carte « répond » à la main qui la tient.
const angle = pointer && random() < 0.5
? Math.atan2(pointer.y - 0.48, pointer.x - 0.5) + (random() - 0.5) * 0.8
: random() * TAU;
const color = pick(random, settings.colors);
bolts.push({ ...boltGeometry(size.width, size.height, angle, random, settings), color, born: now, grow: between(random, GROW_MS), fade: between(random, FADE_MS), struck: false, width: (2 + random() * 1.2) * scale() });
nextSpawn = now + SPAWN_INTERVAL_MS[level()] * (0.6 + random() * 0.8);
}
function draw(now) {
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
context.lineCap = "round";
context.lineJoin = "round";
const core = settings.core || "#ffffff";
for (const bolt of bolts) {
const age = now - bolt.born;
const fraction = age / bolt.grow;
const fading = age - bolt.grow - HOLD_MS;
// Pendant le maintien, l'éclair vacille ; ensuite il s'éteint.
const alpha = fading > 0 ? Math.max(0, 1 - fading / bolt.fade) : fraction >= 1 ? 0.7 + 0.3 * random() : 1;
const style = { color: bolt.color, core, width: bolt.width, alpha };
const tip = strokeBolt(context, bolt.main, fraction, style);
// Les ramifications naissent quand le tronc les atteint.
for (const branch of bolt.branches) strokeBolt(context, branch, Math.max(0, fraction * 1.3 - 0.35), { ...style, width: bolt.width * 0.55, alpha: alpha * 0.85 });
if (fraction < 1) glow(context, tip.x, tip.y, bolt.width * 7, core, 1);
if (fraction >= 1 && !bolt.struck) {
bolt.struck = true;
impacts.push({ x: tip.x, y: tip.y, color: bolt.color, born: now });
}
}
for (const impact of impacts) {
const progress = (now - impact.born) / IMPACT_MS;
glow(context, impact.x, impact.y, (10 + progress * 26) * scale(), impact.color, Math.max(0, 1 - progress));
glow(context, impact.x, impact.y, (4 + progress * 8) * scale(), core, Math.max(0, 1 - progress * 1.3));
}
context.globalAlpha = 1;
context.globalCompositeOperation = "source-over";
}
function tick(now) {
frame = 0;
if (destroyed || !size.width) return;
if (active && now >= nextSpawn && bolts.length < MAX_BOLTS[level()]) spawn(now);
bolts = bolts.filter((bolt) => now - bolt.born < bolt.grow + HOLD_MS + bolt.fade);
impacts = impacts.filter((impact) => now - impact.born < IMPACT_MS);
draw(now);
// Au repos, on laisse les derniers éclairs s'éteindre puis la boucle s'arrête.
if (active || bolts.length || impacts.length) frame = requestAnimationFrame(tick);
else backing.release();
}
const schedule = () => {
if (!frame && !destroyed) frame = requestAnimationFrame(tick);
};
return {
resize(width, height, ratio = 1, focus = null) {
size = { width, height, ratio };
settings = { ...settings, focus };
backing.resize(width, height, ratio);
bolts = [];
impacts = [];
if (active) schedule();
},
setActive(next) {
// Un premier éclair part dès que la carte s'anime.
if (next && !active) nextSpawn = 0;
if (next) backing.attach();
active = next;
if (active) schedule();
},
setPointer(next) {
pointer = next;
},
setOptions(next) {
settings = { ...settings, ...next };
},
// Mouvement réduit : une image fixe de deux éclairs posés, sans boucle.
renderStatic() {
if (!size.width) return;
backing.attach();
const now = 0;
bolts = [0.8, 3.6].map((angle) => ({ ...boltGeometry(size.width, size.height, angle, random, settings), color: settings.colors[0], born: now - 10_000, grow: 1, fade: 1, struck: true, width: 1.3 * scale() }));
const { width, height, ratio } = size;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
context.globalCompositeOperation = "lighter";
context.lineCap = "round";
context.lineJoin = "round";
for (const bolt of bolts) {
strokeBolt(context, bolt.main, 1, { color: bolt.color, core: settings.core || "#ffffff", width: bolt.width, alpha: 0.55 });
}
context.globalCompositeOperation = "source-over";
bolts = [];
},
destroy() {
destroyed = true;
cancelAnimationFrame(frame);
}
};
}