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>
This commit is contained in:
parent
6737a89a1c
commit
3b2dae0168
11 changed files with 202 additions and 27 deletions
|
|
@ -1341,7 +1341,14 @@ dans l'historique. L'édition publiée porte `flareId` et, hors valeurs par déf
|
|||
`flareMotifId`, `flarePaletteId`, `flareScope`, `flareIntensity`, `flareLevel` et
|
||||
`flareCount` : toutes les cartes de la variation (collection, fiche, ouverture une fois
|
||||
la carte révélée) les affichent. Des réglages que le catalogue ne connaît plus ne
|
||||
sont pas publiés. Les particules suivent la variation quand sa finition change.
|
||||
sont pas publiés. Les particules suivent la variation quand sa finition change. Côté
|
||||
performances, une carte au repos ne garde aucune surface de dessin (canvas ramené à
|
||||
0 x 0, réservé seulement pendant l'animation ou pour l'image fixe du mouvement réduit),
|
||||
les sprites des motifs sont construits à la première animation et partagés entre
|
||||
toutes les cartes (cache borné), et quand le pointeur quitte une carte, scintillements
|
||||
et lucioles encore en vie s'effacent ensemble en 0,5 s : aucune boucle d'animation ne
|
||||
tourne dans une grille au repos. Mesuré sur une grille de 36 mythiques à particules :
|
||||
aucune image animée au repos, 60 images par seconde au survol, défilement inchangé.
|
||||
|
||||
Les **éclairs** (`data-flare="lightning"`) sont la première animation. Un canvas (`nebula-card-flare`) posé dans
|
||||
l'illustration dessine des éclairs fractals (déplacement du point milieu) qui partent
|
||||
|
|
@ -1411,7 +1418,10 @@ __backdrop » (ou `__full`, `__full__backdrop`…) : la pleine illustration dema
|
|||
`__full`, la Parallaxe prismatique un héros détouré (`__cutout`) et un décor
|
||||
(`__backdrop`) dans le format choisi ; pour un effet, le format le plus proche
|
||||
d'être complet est cité. Choisir la parallaxe bascule sur un format qui a ses
|
||||
calques. Les menus
|
||||
calques. Le service applique la même règle : créer une variation ou changer sa finition
|
||||
vers un effet à calques (`layers: true` dans `effectPresets`) sans ces fichiers est
|
||||
refusé (`LAYERS_REQUIRED`, « Il manque les fichiers __cutout et __backdrop de cette
|
||||
carte pour cette finition. ») ; une variation déjà enregistrée reste telle quelle. Les menus
|
||||
gardent l'intitulé court à gauche du champ ; les noms accessibles restent « Palette holographique », etc. Sous les
|
||||
onglets, un résumé d'une ligne reprend tous les réglages (« Prisme spectral ·
|
||||
Solaire · Standard · Intensité normale · Vitesse normale · Particules : aucune »),
|
||||
|
|
|
|||
|
|
@ -83,6 +83,23 @@ export function publishedFlare(catalog, stored) {
|
|||
};
|
||||
}
|
||||
|
||||
// Fichiers d'illustration qu'une finition demande à une carte : l'illustration pleine pour le format pleine illustration, et
|
||||
// pour un effet à calques (`layers`, la Parallaxe prismatique) le héros détouré et le décor dans ce format. Renvoie les
|
||||
// suffixes manquants (`__full`, `__cutout`, `__full__backdrop`…), vide si la carte peut porter la finition.
|
||||
const FORMAT_FILES = {
|
||||
[STANDARD_FORMAT]: { suffix: "", image: "image", cutout: "cutoutImage", backdrop: "backdropImage" },
|
||||
[FULL_ART_FORMAT]: { suffix: "__full", image: "fullImage", cutout: "fullCutoutImage", backdrop: "fullBackdropImage" }
|
||||
};
|
||||
|
||||
export function missingFinishFiles(catalog, card, finishId) {
|
||||
const finish = catalog.finishes.find((item) => item.id === finishId);
|
||||
const files = FORMAT_FILES[finish?.formatId || STANDARD_FORMAT];
|
||||
if (!files) return [];
|
||||
if (!card?.[files.image]) return [files.suffix || "image"];
|
||||
if (!catalog.effectPresets.find((preset) => preset.id === finish?.effectPresetId)?.layers) return [];
|
||||
return [[files.cutout, "__cutout"], [files.backdrop, "__backdrop"]].filter(([field]) => !card[field]).map(([, name]) => `${files.suffix}${name}`);
|
||||
}
|
||||
|
||||
const EDITION_FLARE_FIELDS = ["flareId", "flareMotifId", "flarePaletteId", "flareScope", ...Object.values(FLARE_TUNING_FIELDS)];
|
||||
const CARD_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/(?:common|rare|epic|legendary)\/[a-z0-9_]+\.webp$/;
|
||||
const PACK_BACK_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/back\.webp$/;
|
||||
|
|
@ -199,6 +216,7 @@ export function validateCardsCatalog(catalog) {
|
|||
for (const preset of catalog.effectPresets) {
|
||||
if (!preset.label || preset.kind !== "holographic") throw new TypeError(`Invalid holographic effect preset ${preset.id}.`);
|
||||
if (preset.level != null && !validTuningScale(preset.level)) throw new TypeError(`Holographic effect preset ${preset.id} level needs a label and ${EFFECT_TUNING_STEPS} level labels.`);
|
||||
if (preset.layers != null && typeof preset.layers !== "boolean") throw new TypeError(`Holographic effect preset ${preset.id} layers flag must be a boolean.`);
|
||||
}
|
||||
if (!validTuningScale(catalog.effectIntensity)) throw new TypeError(`Cards catalog effectIntensity needs a label and ${EFFECT_TUNING_STEPS} level labels.`);
|
||||
validateFlares(catalog);
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
|
||||
import { normalizeReward } from "./rewards.js";
|
||||
import { MASS_RECYCLE_RARITIES, planRecycling, spareQuantity, validateShopSetting } from "./stardust.js";
|
||||
import { DEFAULT_EFFECT_TUNING, DEFAULT_FLARE_SCOPE, FULL_ART_FORMAT, isEffectTuning, normalizeFlare, buildPublishedCatalog, collectionDrawableEditions, createCatalogIndex, holographicFinishIds, isMythicEditionIdOf, legendaryParentEdition, MATCH_HOLO_PALETTE_ID, mythicEditionId, publicCatalog, validateRarityWeights } from "./catalog.js";
|
||||
import { DEFAULT_EFFECT_TUNING, DEFAULT_FLARE_SCOPE, FULL_ART_FORMAT, isEffectTuning, missingFinishFiles, normalizeFlare, buildPublishedCatalog, collectionDrawableEditions, createCatalogIndex, holographicFinishIds, isMythicEditionIdOf, legendaryParentEdition, MATCH_HOLO_PALETTE_ID, mythicEditionId, publicCatalog, validateRarityWeights } from "./catalog.js";
|
||||
import { computeStreak, DAILY_REPEAT_WINDOW_DAYS, dailyCandidates, dailyDayKey, dailyZoom, drawDailyPuzzle, guessHint, isDayKey, MAX_DAILY_GUESSES, nextDailyAt, shiftDayKey } from "./daily.js";
|
||||
import { calculateRecharge, pinnedRecharge, drawPack, drawShopPack, MAX_RECHARGE_INTERVAL_MS, MAX_RESERVE_OPENINGS, MIN_RECHARGE_INTERVAL_MS, spendOpening } from "./game-rules.js";
|
||||
import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedition-content.js";
|
||||
|
|
@ -54,6 +54,12 @@ function flareOfRow(row) {
|
|||
return { id: row.flare_id, motifId: row.flare_motif_id, paletteId: row.flare_palette_id, scope: row.flare_scope, intensity: row.flare_intensity, level: row.flare_level, count: row.flare_count };
|
||||
}
|
||||
|
||||
// « Il manque les fichiers __cutout et __backdrop de cette carte pour cette finition. »
|
||||
function missingFilesMessage(files) {
|
||||
const list = files.length > 1 ? `${files.slice(0, -1).join(", ")} et ${files.at(-1)}` : files[0];
|
||||
return `Il manque ${files.length > 1 ? "les fichiers" : "le fichier"} ${list} de cette carte pour cette finition.`;
|
||||
}
|
||||
|
||||
const FLARE_ERROR_MESSAGES = {
|
||||
FLARE_UNKNOWN: "Cette animation de particules n’existe pas.",
|
||||
FLARE_MOTIF_INVALID: "Choisissez un motif proposé par cette animation.",
|
||||
|
|
@ -252,6 +258,11 @@ export class CardsService {
|
|||
if (!Array.isArray(finishIds) || finishIds.some((id) => typeof id !== "string" || !holographic.has(id))) fail(400, "FINISH_INVALID", "Choisissez uniquement des finitions holographiques.");
|
||||
const needsFullImage = (id) => versioned.finishes.find((item) => item.id === id)?.formatId === FULL_ART_FORMAT;
|
||||
if (!card.fullImage && finishIds.some(needsFullImage)) fail(400, "FULL_IMAGE_REQUIRED", "Cette carte n’a pas d’illustration pleine.");
|
||||
// Une nouvelle variation à calques (Parallaxe prismatique) exige le héros détouré et le décor de la carte ; les variations
|
||||
// déjà enregistrées restent telles quelles, même si leurs fichiers manquent.
|
||||
const existing = new Set(this.db.prepare("SELECT finish_id FROM mythic_variations WHERE card_id = ?").all(cardId).map((row) => row.finish_id));
|
||||
const missing = finishIds.filter((id) => !existing.has(id)).map((id) => missingFinishFiles(versioned, card, id)).find((files) => files.length);
|
||||
if (missing) fail(400, "LAYERS_REQUIRED", missingFilesMessage(missing));
|
||||
const openingStyle = this.validateOpeningStyle(opening);
|
||||
const wanted = new Set(finishIds);
|
||||
const now = this.now();
|
||||
|
|
@ -307,6 +318,8 @@ export class CardsService {
|
|||
const finish = versioned.finishes.find((item) => item.id === finishId);
|
||||
if (!finish || !holographicFinishIds(versioned).has(finishId)) fail(400, "FINISH_INVALID", "Choisissez une finition holographique.");
|
||||
if (finish.formatId === FULL_ART_FORMAT && !card.fullImage) fail(400, "FULL_IMAGE_REQUIRED", "Cette carte n’a pas d’illustration pleine.");
|
||||
const missing = missingFinishFiles(versioned, card, finishId);
|
||||
if (missing.length) fail(400, "LAYERS_REQUIRED", missingFilesMessage(missing));
|
||||
if (row.finish_id === finishId) fail(400, "FINISH_UNCHANGED", "La variation a déjà cette finition.");
|
||||
if (this.db.prepare("SELECT 1 FROM mythic_variations WHERE card_id = ? AND finish_id = ?").get(row.card_id, finishId)) {
|
||||
fail(409, "FINISH_TAKEN", "Cette carte a déjà une variation avec cette finition.");
|
||||
|
|
|
|||
|
|
@ -44,3 +44,15 @@ test("an unavailable effect or format explains which files are missing", () => {
|
|||
assert.equal(formatMissingHint(fullLayers, "prismatic-backdrop", "standard"), "Fichiers manquants : __cutout et __backdrop");
|
||||
assert.equal(formatMissingHint(fullLayers, "prismatic-backdrop", "full-art"), null);
|
||||
});
|
||||
|
||||
test("the interface and the server agree on which finishes a card can carry", async () => {
|
||||
const { missingFinishFiles, withGeneratedFinishes } = await import("../services/cards/catalog.js");
|
||||
const full = withGeneratedFinishes(catalog);
|
||||
assert.deepEqual(full.effectPresets.filter((preset) => preset.layers).map((preset) => preset.id), ["prismatic-backdrop"]);
|
||||
const holographic = full.finishes.filter((finish) => finish.effectPresetId);
|
||||
for (const card of full.cards) {
|
||||
for (const finish of holographic) {
|
||||
assert.equal(finishAvailable(card, finish.effectPresetId, finish.formatId), missingFinishFiles(full, card, finish.id).length === 0, `${card.id} × ${finish.id}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { readFile } from "node:fs/promises";
|
|||
import test from "node:test";
|
||||
import { flareEditionFields, flareOfEdition, MATCH_HOLO_FLARE_PALETTE, NO_FLARE, resolveFlare, sameFlare } from "../website/src/features/cards/holoFlares.js";
|
||||
import { boltGeometry, boltPath, TARGET_ZONE } from "../website/src/features/cards/holoLightning.js";
|
||||
import { motifAngle } from "../website/src/features/cards/flareSprites.js";
|
||||
import { canvasBacking, motifAngle } from "../website/src/features/cards/flareSprites.js";
|
||||
import { FIREFLY_COUNTS, fireflyFade, fireflyHeading } from "../website/src/features/cards/holoFireflies.js";
|
||||
import { TWINKLE_COUNTS, twinkleState } from "../website/src/features/cards/holoTwinkle.js";
|
||||
|
||||
|
|
@ -137,3 +137,18 @@ test("a published edition reads back as editable settings, compared by what they
|
|||
assert.ok(sameFlare({ ...NO_FLARE, id: "lightning", count: 5 }, { ...NO_FLARE, id: "lightning" }, catalog));
|
||||
assert.ok(!sameFlare({ ...NO_FLARE, id: "lightning" }, NO_FLARE, catalog));
|
||||
});
|
||||
|
||||
test("a particle canvas holds pixels only while it animates", () => {
|
||||
const canvas = { width: 300, height: 150 };
|
||||
const backing = canvasBacking(canvas);
|
||||
// Un canvas neuf rend aussitôt sa surface par défaut (300 x 150) ; un redimensionnement au repos n'en réserve pas.
|
||||
assert.deepEqual([canvas.width, canvas.height], [0, 0]);
|
||||
backing.resize(280, 240, 2);
|
||||
assert.deepEqual([canvas.width, canvas.height], [0, 0]);
|
||||
backing.attach();
|
||||
assert.deepEqual([canvas.width, canvas.height], [560, 480]);
|
||||
backing.resize(100, 50, 1.5);
|
||||
assert.deepEqual([canvas.width, canvas.height], [150, 75]);
|
||||
backing.release();
|
||||
assert.deepEqual([canvas.width, canvas.height], [0, 0]);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { tmpdir } from "node:os";
|
|||
import { join } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { assertVersionedCatalogScope, buildPublishedCatalog, drawableRarities, publicCatalog, prepareVersionedCatalog, validateCardsCatalog, withGeneratedFinishes } from "../services/cards/catalog.js";
|
||||
import { assertVersionedCatalogScope, buildPublishedCatalog, drawableRarities, publicCatalog, prepareVersionedCatalog, validateCardsCatalog, withGeneratedFinishes, missingFinishFiles } from "../services/cards/catalog.js";
|
||||
import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "../services/cards/admin-seed.js";
|
||||
import { planRecycling } from "../services/cards/stardust.js";
|
||||
import { resolveMythicOpeningStyle, resolveOpeningEffect } from "../website/src/features/cards/openingEffects.js";
|
||||
|
|
@ -1295,6 +1295,29 @@ test("a mythic variation saves its particles, normalized, audited and kept acros
|
|||
database.close();
|
||||
});
|
||||
|
||||
test("a layered finish needs the card's cutout and backdrop, checked when a variation is created or changed", () => {
|
||||
const now = 1_800_000_000_000;
|
||||
const database = new CardsDatabase(":memory:");
|
||||
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
|
||||
const admin = service.upsertPlayer({ discordId: "layers-admin", displayName: "Admin", isAdmin: true });
|
||||
const cardOf = (id) => baseCatalog.cards.find((card) => card.id === id);
|
||||
assert.deepEqual(missingFinishFiles(baseCatalog, cardOf("night-of-return-dragon"), "prismatic-backdrop-solar"), ["__cutout", "__backdrop"]);
|
||||
assert.deepEqual(missingFinishFiles(baseCatalog, cardOf("night-of-return-dragon"), "full-art-prismatic-backdrop-solar"), []);
|
||||
assert.deepEqual(missingFinishFiles(baseCatalog, cardOf("night-of-return-dragon"), "spectral-prism-solar"), []);
|
||||
// La Pioche a ses calques dans les deux formats ; le Dragon de la Nuit du Retour seulement en pleine illustration.
|
||||
assert.doesNotThrow(() => service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["prismatic-backdrop-solar"] }));
|
||||
assert.throws(() => service.setCardMythicConfig(admin.id, "night-of-return-dragon", { finishIds: ["prismatic-backdrop-solar"] }), /Il manque les fichiers __cutout et __backdrop/);
|
||||
service.setCardMythicConfig(admin.id, "night-of-return-dragon", { finishIds: ["spectral-prism-solar"] });
|
||||
const dragon = service.catalog.editions.find((edition) => edition.cardId === "night-of-return-dragon" && edition.rarity === "mythic").id;
|
||||
assert.throws(() => service.setMythicFinish(admin.id, dragon, "prismatic-backdrop-cosmic"), (error) => error.code === "LAYERS_REQUIRED");
|
||||
assert.doesNotThrow(() => service.setMythicFinish(admin.id, dragon, "full-art-prismatic-backdrop-cosmic"));
|
||||
// Une variation déjà enregistrée sans ses fichiers (catalogue modifié depuis) reste enregistrable telle quelle.
|
||||
database.db.prepare("UPDATE mythic_variations SET finish_id = 'prismatic-backdrop-cosmic' WHERE edition_id = ?").run(dragon);
|
||||
const reloaded = new CardsService({ database, catalog: baseCatalog, now: () => now });
|
||||
assert.doesNotThrow(() => reloaded.setCardMythicConfig(admin.id, "night-of-return-dragon", { finishIds: ["prismatic-backdrop-cosmic", "spectral-prism-aurora"] }));
|
||||
database.close();
|
||||
});
|
||||
|
||||
test("particle animations are declared by the catalog and checked on editions", () => {
|
||||
const broken = (change) => { const catalog = structuredClone(rawCatalog); change(catalog); return () => prepareVersionedCatalog(catalog); };
|
||||
assert.throws(broken((catalog) => { catalog.flareScopes.reverse(); }), /flareScopes must start with art/);
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@
|
|||
"id": "prismatic-backdrop",
|
||||
"kind": "holographic",
|
||||
"label": "Parallaxe prismatique",
|
||||
"layers": true,
|
||||
"level": { "label": "Amplitude", "levels": ["Très douce", "Douce", "Moyenne", "Forte", "Très forte"] }
|
||||
},
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
// Rôle : sprites des motifs de particules persistantes (scintillements, lucioles) : silhouettes procédurales de rayon 1,
|
||||
// rendues une fois par couleur avec halo et cœur clair, puis seulement recopiées à chaque image.
|
||||
// Rôle : ressources communes des particules persistantes : sprites des motifs (scintillements, lucioles), silhouettes
|
||||
// procédurales de rayon 1 rendues une fois par couleur avec halo et cœur clair puis recopiées à chaque image, gardées dans un
|
||||
// cache partagé entre toutes les cartes ; et surface de dessin d'un canvas réservée seulement pendant l'animation.
|
||||
const TAU = Math.PI * 2;
|
||||
export const SPRITE_SIZE = 96;
|
||||
|
||||
|
|
@ -87,7 +88,7 @@ function bubble(context, radius, color, core) {
|
|||
|
||||
// Sprite d'un motif dans une couleur : halo, silhouette colorée lumineuse, puis cœur clair. Rendu une seule fois (le flou y
|
||||
// est permis), puis seulement recopié à chaque image.
|
||||
export function motifSprite(motifId, color, core) {
|
||||
function drawMotifSprite(motifId, color, core) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = SPRITE_SIZE;
|
||||
canvas.height = SPRITE_SIZE;
|
||||
|
|
@ -130,7 +131,7 @@ export function motifSprite(motifId, color, core) {
|
|||
}
|
||||
|
||||
// Éclat en croix de l'apogée : deux traits fins dégradés, clairs au centre.
|
||||
export function streakSprite(color, core) {
|
||||
function drawStreakSprite(color, core) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = SPRITE_SIZE * 2;
|
||||
canvas.height = SPRITE_SIZE * 2;
|
||||
|
|
@ -150,3 +151,50 @@ export function streakSprite(color, core) {
|
|||
}
|
||||
return canvas;
|
||||
}
|
||||
|
||||
// Cache partagé : une grille de cartes mythiques réutilise les mêmes sprites au lieu d'en refaire par carte. Borné, les plus
|
||||
// anciens partent d'abord.
|
||||
const SPRITE_CACHE_LIMIT = 160;
|
||||
const spriteCache = new Map();
|
||||
function cached(key, build) {
|
||||
if (!spriteCache.has(key)) {
|
||||
if (spriteCache.size >= SPRITE_CACHE_LIMIT) spriteCache.delete(spriteCache.keys().next().value);
|
||||
spriteCache.set(key, build());
|
||||
}
|
||||
return spriteCache.get(key);
|
||||
}
|
||||
|
||||
export const motifSprite = (motifId, color, core) => cached(`motif|${motifId}|${color}|${core}`, () => drawMotifSprite(motifId, color, core));
|
||||
export const streakSprite = (color, core) => cached(`streak|${color}|${core}`, () => drawStreakSprite(color, core));
|
||||
|
||||
// Surface de dessin d'un canvas : réservée (largeur x hauteur x densité de pixels) seulement quand le moteur anime ou fige une
|
||||
// image, libérée (0 x 0) au repos. Une grille de cartes au repos ne garde ainsi aucun pixel en mémoire.
|
||||
export function canvasBacking(canvas) {
|
||||
let size = { width: 0, height: 0, ratio: 1 };
|
||||
let attached = false;
|
||||
const attach = () => {
|
||||
const width = Math.max(1, Math.round(size.width * size.ratio));
|
||||
const height = Math.max(1, Math.round(size.height * size.ratio));
|
||||
if (attached && canvas.width === width && canvas.height === height) return;
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
attached = true;
|
||||
};
|
||||
const release = () => {
|
||||
canvas.width = 0;
|
||||
canvas.height = 0;
|
||||
attached = false;
|
||||
};
|
||||
release();
|
||||
return {
|
||||
resize(width, height, ratio) {
|
||||
size = { width, height, ratio };
|
||||
if (attached) {
|
||||
attached = false;
|
||||
attach();
|
||||
}
|
||||
},
|
||||
attach,
|
||||
release
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
// trajectoires sinueuses, pulsent doucement, apparaissent et s'éteignent en chemin, et s'écartent du pointeur. Nombre moyen,
|
||||
// vitesse et intensité réglables ; motifs partagés avec les scintillements ; temps réel ; aucune boucle au repos. Même
|
||||
// interface que les autres moteurs de particules.
|
||||
import { motifAngle, motifSprite, SPRITE_SIZE } from "./flareSprites.js";
|
||||
import { canvasBacking, motifAngle, motifSprite, SPRITE_SIZE } from "./flareSprites.js";
|
||||
|
||||
const TAU = Math.PI * 2;
|
||||
|
||||
|
|
@ -15,6 +15,9 @@ const SPEED = [0.03, 0.045, 0.065, 0.09, 0.125];
|
|||
const LIFETIME_MS = [8000, 6800, 5600, 4600, 3800];
|
||||
const INTENSITY_SCALE = [0.6, 0.75, 0.9, 1.1, 1.35];
|
||||
const REFERENCE_AREA = 280 * 240;
|
||||
// Quand la carte n'est plus survolée, les motifs encore en vie s'effacent ensemble en une demi-seconde au lieu de finir leur
|
||||
// vie : l'animation s'arrête vite au lieu de tourner plusieurs secondes pour rien.
|
||||
const OUTRO_MS = 500;
|
||||
|
||||
// Opacité selon l'âge relatif : apparition sur 20 % de la vie, extinction sur les 25 derniers.
|
||||
export function fireflyFade(t) {
|
||||
|
|
@ -31,6 +34,7 @@ export function fireflyHeading(firefly, seconds) {
|
|||
|
||||
export function createFireflies(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 };
|
||||
|
|
@ -41,6 +45,8 @@ export function createFireflies(canvas, options) {
|
|||
let frame = 0;
|
||||
let last = 0;
|
||||
let nextSpawn = 0;
|
||||
let leftAt = 0;
|
||||
let fade = 1;
|
||||
let destroyed = false;
|
||||
|
||||
const intensity = () => INTENSITY_SCALE[(settings.intensity || 3) - 1];
|
||||
|
|
@ -107,7 +113,7 @@ export function createFireflies(canvas, options) {
|
|||
context.save();
|
||||
context.translate(fly.x, fly.y);
|
||||
context.rotate(motifAngle(settings.motifId, fly.rotation));
|
||||
context.globalAlpha = alpha * (0.65 + 0.35 * glow);
|
||||
context.globalAlpha = fade * alpha * (0.65 + 0.35 * glow);
|
||||
context.drawImage(sprites[fly.color], -spriteSize / 2, -spriteSize / 2, spriteSize, spriteSize);
|
||||
context.restore();
|
||||
}
|
||||
|
|
@ -138,12 +144,14 @@ export function createFireflies(canvas, options) {
|
|||
}
|
||||
while (active && now >= nextSpawn && flies.length < average() * 1.6) spawn(now);
|
||||
flies = flies.filter((fly) => now - fly.born < fly.life);
|
||||
fade = leftAt ? Math.max(0, 1 - (now - leftAt) / OUTRO_MS) : 1;
|
||||
if (!fade) flies = [];
|
||||
for (const fly of flies) move(fly, now, elapsed);
|
||||
draw(now);
|
||||
if (active || flies.length) frame = requestAnimationFrame(tick);
|
||||
else {
|
||||
last = 0;
|
||||
context.clearRect(0, 0, size.width, size.height);
|
||||
backing.release();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -151,16 +159,21 @@ export function createFireflies(canvas, options) {
|
|||
if (!frame && !destroyed) frame = requestAnimationFrame(tick);
|
||||
};
|
||||
|
||||
buildSprites();
|
||||
// Sprites construits à la première animation (et pris dans le cache partagé) : une carte jamais survolée n'en crée pas.
|
||||
return {
|
||||
resize(width, height, ratio = 1) {
|
||||
size = { width, height, ratio };
|
||||
canvas.width = Math.max(1, Math.round(width * ratio));
|
||||
canvas.height = Math.max(1, Math.round(height * ratio));
|
||||
backing.resize(width, height, ratio);
|
||||
flies = [];
|
||||
if (active) schedule();
|
||||
},
|
||||
setActive(next) {
|
||||
if (!next && active) leftAt = performance.now();
|
||||
if (next) leftAt = 0;
|
||||
if (next) {
|
||||
if (!sprites.length) buildSprites();
|
||||
backing.attach();
|
||||
}
|
||||
active = next;
|
||||
if (active) schedule();
|
||||
},
|
||||
|
|
@ -169,11 +182,13 @@ export function createFireflies(canvas, options) {
|
|||
},
|
||||
setOptions(next) {
|
||||
settings = { ...settings, ...next };
|
||||
buildSprites();
|
||||
sprites = [];
|
||||
},
|
||||
// Mouvement réduit : quelques lueurs immobiles.
|
||||
renderStatic() {
|
||||
if (!size.width) return;
|
||||
if (!sprites.length) buildSprites();
|
||||
backing.attach();
|
||||
flies = [];
|
||||
const count = Math.max(2, Math.round(average() / 2));
|
||||
for (let index = 0; index < count; index++) spawn(0);
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@
|
|||
// é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).
|
||||
|
|
@ -117,6 +119,7 @@ function glow(context, x, y, radius, color, alpha) {
|
|||
|
||||
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 };
|
||||
|
|
@ -183,7 +186,7 @@ export function createLightning(canvas, options) {
|
|||
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 context.clearRect(0, 0, size.width, size.height);
|
||||
else backing.release();
|
||||
}
|
||||
|
||||
const schedule = () => {
|
||||
|
|
@ -194,8 +197,7 @@ export function createLightning(canvas, options) {
|
|||
resize(width, height, ratio = 1, focus = null) {
|
||||
size = { width, height, ratio };
|
||||
settings = { ...settings, focus };
|
||||
canvas.width = Math.max(1, Math.round(width * ratio));
|
||||
canvas.height = Math.max(1, Math.round(height * ratio));
|
||||
backing.resize(width, height, ratio);
|
||||
bolts = [];
|
||||
impacts = [];
|
||||
if (active) schedule();
|
||||
|
|
@ -203,6 +205,7 @@ export function createLightning(canvas, options) {
|
|||
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();
|
||||
},
|
||||
|
|
@ -215,6 +218,7 @@ export function createLightning(canvas, options) {
|
|||
// 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;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
// losange, cœur, flocon, bulle…) apparaissent en grossissant, vivent un instant avec un éclat en croix à leur apogée, puis
|
||||
// disparaissent en rétrécissant. Nombre moyen à l'écran, vitesse et intensité réglables ; couleurs de la palette ; temps
|
||||
// réel ; aucune boucle au repos. Même interface que le moteur des éclairs.
|
||||
import { motifAngle, motifSprite, SPRITE_SIZE, streakSprite } from "./flareSprites.js";
|
||||
import { canvasBacking, motifAngle, motifSprite, SPRITE_SIZE, streakSprite } from "./flareSprites.js";
|
||||
|
||||
const TAU = Math.PI * 2;
|
||||
|
||||
|
|
@ -16,6 +16,9 @@ const INTENSITY_SCALE = [0.55, 0.65, 0.8, 1, 1.25];
|
|||
// Surface de référence : l'illustration d'une carte `lg`. Une carte plus petite montre moins de motifs, une zone « toute la
|
||||
// carte » un peu plus.
|
||||
const REFERENCE_AREA = 280 * 240;
|
||||
// Quand la carte n'est plus survolée, les motifs encore en vie s'effacent ensemble en une demi-seconde au lieu de finir leur
|
||||
// vie : l'animation s'arrête vite au lieu de tourner plusieurs secondes pour rien.
|
||||
const OUTRO_MS = 500;
|
||||
|
||||
const easeOutBack = (t) => 1 + 2.4 * (t - 1) ** 3 + 1.4 * (t - 1) ** 2;
|
||||
|
||||
|
|
@ -35,6 +38,7 @@ export function twinkleState(t) {
|
|||
|
||||
export function createTwinkle(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 };
|
||||
|
|
@ -45,6 +49,8 @@ export function createTwinkle(canvas, options) {
|
|||
let active = false;
|
||||
let frame = 0;
|
||||
let nextSpawn = 0;
|
||||
let leftAt = 0;
|
||||
let fade = 1;
|
||||
let destroyed = false;
|
||||
|
||||
const intensity = () => INTENSITY_SCALE[(settings.intensity || 3) - 1];
|
||||
|
|
@ -90,13 +96,13 @@ export function createTwinkle(canvas, options) {
|
|||
context.save();
|
||||
context.translate(item.x, item.y);
|
||||
context.rotate(motifAngle(settings.motifId, item.rotation + item.spin * state.age));
|
||||
context.globalAlpha = state.alpha * Math.min(1, 0.75 + 0.25 * intensity());
|
||||
context.globalAlpha = fade * state.alpha * Math.min(1, 0.75 + 0.25 * intensity());
|
||||
context.drawImage(sprites[item.color], -spriteSize / 2, -spriteSize / 2, spriteSize, spriteSize);
|
||||
// Le reflet garde sa croix de lumière toute sa vie ; les autres motifs la font jaillir à leur apogée.
|
||||
const peak = settings.motifId === "glint" ? Math.max(state.peak, state.alpha * 0.7) : state.peak;
|
||||
if (peak > 0 && settings.motifId !== "bubble") {
|
||||
const streak = item.radius * 10 * (0.55 + 0.45 * peak) * Math.min(1.3, intensity());
|
||||
context.globalAlpha = peak;
|
||||
context.globalAlpha = fade * peak;
|
||||
context.drawImage(streaks[item.color], -streak / 2, -streak / 2, streak, streak);
|
||||
}
|
||||
context.restore();
|
||||
|
|
@ -121,26 +127,33 @@ export function createTwinkle(canvas, options) {
|
|||
// Plusieurs naissances par image si la fréquence l'exige (beaucoup de motifs très rapides).
|
||||
while (active && now >= nextSpawn && items.length < average() * 2.5) spawn(now);
|
||||
items = items.filter((item) => now - item.born < item.life);
|
||||
fade = leftAt ? Math.max(0, 1 - (now - leftAt) / OUTRO_MS) : 1;
|
||||
if (!fade) items = [];
|
||||
draw(now);
|
||||
if (active || items.length) frame = requestAnimationFrame(tick);
|
||||
else context.clearRect(0, 0, size.width, size.height);
|
||||
else backing.release();
|
||||
}
|
||||
|
||||
const schedule = () => {
|
||||
if (!frame && !destroyed) frame = requestAnimationFrame(tick);
|
||||
};
|
||||
|
||||
buildSprites();
|
||||
// Sprites construits à la première animation (et pris dans le cache partagé) : une carte jamais survolée n'en crée pas.
|
||||
return {
|
||||
resize(width, height, ratio = 1) {
|
||||
size = { width, height, ratio };
|
||||
canvas.width = Math.max(1, Math.round(width * ratio));
|
||||
canvas.height = Math.max(1, Math.round(height * ratio));
|
||||
backing.resize(width, height, ratio);
|
||||
items = [];
|
||||
if (active) schedule();
|
||||
},
|
||||
setActive(next) {
|
||||
if (next && !active) nextSpawn = 0;
|
||||
if (!next && active) leftAt = performance.now();
|
||||
if (next) leftAt = 0;
|
||||
if (next) {
|
||||
if (!sprites.length) buildSprites();
|
||||
backing.attach();
|
||||
}
|
||||
active = next;
|
||||
if (active) schedule();
|
||||
},
|
||||
|
|
@ -149,11 +162,14 @@ export function createTwinkle(canvas, options) {
|
|||
},
|
||||
setOptions(next) {
|
||||
settings = { ...settings, ...next };
|
||||
buildSprites();
|
||||
sprites = [];
|
||||
streaks = [];
|
||||
},
|
||||
// Mouvement réduit : quelques motifs fixes, à mi-éclat.
|
||||
renderStatic() {
|
||||
if (!size.width) return;
|
||||
if (!sprites.length) buildSprites();
|
||||
backing.attach();
|
||||
items = [];
|
||||
const count = Math.max(2, Math.round(average() / 2));
|
||||
for (let index = 0; index < count; index++) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue