import { ItemId } from "/shared/definitions/items.js"; import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js"; const bottleCache = new Map(); const fillCache = new Map(); const urlCache = new Map(); function loadImage (src) { return new Promise((resolve, reject) => { const img = new Image(); img.onload = () => resolve(img); img.onerror = () => reject(new Error(`Failed to load ${src}`)); img.src = src; }); } async function getBottle () { if (!bottleCache.has("bottle")) { bottleCache.set("bottle", loadImage("/assets/items/glass-bottle/glass-bottle.png")); } return bottleCache.get("bottle"); } async function getFill (level) { const key = Math.max(1, Math.min(5, level | 0 || 4)); if (!fillCache.has(key)) { fillCache.set(key, loadImage(`/assets/items/potion/fill-${key}.png`)); } return fillCache.get(key); } function colorKey (color) { if (!color) { return "0,0,0"; } const r = Math.round((color.r ?? 0) * 255); const g = Math.round((color.g ?? 0) * 255); const b = Math.round((color.b ?? 0) * 255); return `${r},${g},${b}`; } /** * Build a data-URL icon: clear bottle + fill mask tinted to potion color. * UI-only; world ground items use the same bake then lit darkness shader. */ export async function potionIconDataUrl (instance) { const fillLevel = Math.max(1, Math.min(5, instance?.fillLevel | 0 || 4)); const key = `${fillLevel}|${colorKey(instance?.color)}`; if (urlCache.has(key)) { return urlCache.get(key); } const [bottle, fill] = await Promise.all([getBottle(), getFill(fillLevel)]); const canvas = document.createElement("canvas"); canvas.width = SPRITE_SIZE_PX; canvas.height = SPRITE_SIZE_PX; const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(fill, 0, 0); const image = ctx.getImageData(0, 0, canvas.width, canvas.height); const data = image.data; const r = Math.round((instance?.color?.r ?? 0.4) * 255); const g = Math.round((instance?.color?.g ?? 0.4) * 255); const b = Math.round((instance?.color?.b ?? 0.7) * 255); for (let i = 0; i < data.length; i += 4) { if (data[i + 3] < 8) { continue; } const a = data[i + 3] / 255; data[i] = r; data[i + 1] = g; data[i + 2] = b; data[i + 3] = Math.round(220 * a); } ctx.putImageData(image, 0, 0); ctx.drawImage(bottle, 0, 0); const url = canvas.toDataURL("image/png"); urlCache.set(key, url); return url; } export function isPotionStack (stack) { return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion"; } /** Sync helper: set img.src to recolored potion or fall back to asset path. */ export function applyItemIcon (img, stack, fallbackPath) { if (!img) { return; } if (!isPotionStack(stack)) { img.src = fallbackPath; return; } img.src = fallbackPath; potionIconDataUrl(stack.instance).then((url) => { img.src = url; }).catch(() => { img.src = fallbackPath; }); }