/** * Emojis con volumen ("emoji inflado"). * * - `emojiTexture(emoji, px)`: textura cuadrada (CanvasTexture, alfa NO premultiplicado), cacheada. * - `emojiMesh(emoji, size, opts)`: plano iluminado con mapa de normales generado desde la silueta * (transformada de distancia → perfil de almohada → normales), especular suave, sombra con la silueta. * - `emojiReady()`: resuelve cuando la fuente Noto Color Emoji está cargada. Las texturas creadas antes * se redibujan solas al llegar la fuente (y su mapa de normales se regenera). * * Bordes limpios: el mesh usa una textura premultiplicada (el filtrado no arrastra negro desde los texels * transparentes) y el shader la des-premultiplica antes de iluminar. Con MSAA se usa alpha-to-coverage. */ import '@fontsource/noto-color-emoji/index.css'; import * as THREE from 'three'; import { attachDomEmoji } from './emojiDom'; import { toonMaterial, type ToonMaterial } from './materials'; export const EMOJI_FONT = '"Noto Color Emoji", "Segoe UI Emoji", "Apple Color Emoji", sans-serif'; interface Entry { emoji: string; px: number; canvas: HTMLCanvasElement; /** Textura pública (alfa recto). */ tex: THREE.CanvasTexture; /** Variante premultiplicada para los meshes (creada a demanda). */ pm?: THREE.Texture; /** Mapa de normales (creado a demanda). */ normal?: THREE.CanvasTexture; /** Recorte de la silueta en uv (minU, minV, maxU, maxV) para ajustar la geometría. */ fontOk: boolean; /** Textura de respaldo (sin mipmaps) si se creó. */ safe?: THREE.Texture; } const cache = new Map(); const pending = new Set>(); let fontFace = false; /** Pinta el emoji centrado en un lienzo de `size` px con la fuente dada. */ function paint(g: CanvasRenderingContext2D, emoji: string, size: number, font: string): void { g.clearRect(0, 0, size, size); g.textAlign = 'center'; g.textBaseline = 'middle'; g.font = `${Math.floor(size * 0.8)}px ${font}`; g.fillText(emoji, size / 2, size / 2 + size * 0.045); } /** Tamaño seguro: Chrome en Android no pinta en canvas glifos de color grandes (los traza como contorno y * los emojis de mapa de bits quedan vacíos). A este tamaño se pinta bien y luego se amplía. */ const SAFE_PX = 96; let scratch: HTMLCanvasElement | null = null; function draw(e: Entry): void { const { canvas: c, px } = e; const g = c.getContext('2d', { willReadFrequently: true })!; if (!scratch) { scratch = document.createElement('canvas'); scratch.width = scratch.height = SAFE_PX; } const s = scratch.getContext('2d', { willReadFrequently: true })!; // Referencia a tamaño pequeño (ahí Android sí pinta el glifo relleno). paint(s, e.emoji, SAFE_PX, EMOJI_FONT); const ref = coverage(s, SAFE_PX); const good = () => { const cv = coverage(g, px); return cv >= MIN_COVER && cv >= ref * 0.6; }; paint(g, e.emoji, px, EMOJI_FONT); if (good()) return; // Algunos navegadores cargan Noto (COLRv1) pero no la pintan en canvas: fuente del sistema. paint(g, e.emoji, px, SYSTEM_EMOJI_FONT); if (good()) return; // Android: el glifo grande sale vacío o en contorno. Se pinta pequeño y se amplía con suavizado. if (ref < MIN_COVER) paint(s, e.emoji, SAFE_PX, EMOJI_FONT); if (isBlank(s, SAFE_PX)) paint(s, e.emoji, SAFE_PX, SYSTEM_EMOJI_FONT); if (isBlank(s, SAFE_PX)) paint(s, e.emoji, SAFE_PX, 'sans-serif'); g.clearRect(0, 0, px, px); g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high'; g.drawImage(scratch, 0, 0, px, px); } const SYSTEM_EMOJI_FONT = '"Segoe UI Emoji", "Apple Color Emoji", "Noto Color Emoji", sans-serif'; /** * ¿El glifo salió mal? Vacío, o solo su contorno: Chrome en Android, con la fuente web cargada, traza los emojis * grandes como un contorno fino. No está vacío, pero el recorte por alfa lo borraba entero (emojis invisibles). * Se mide qué parte del lienzo es opaca: un emoji de verdad cubre bastante más. */ function isBlank(g: CanvasRenderingContext2D, px: number): boolean { return coverage(g, px) < MIN_COVER; } const MIN_COVER = 0.12; /** Fracción del lienzo con alfa alto (muestreo en rejilla). */ function coverage(g: CanvasRenderingContext2D, px: number): number { const d = g.getImageData(0, 0, px, px).data; const stride = 4 * 3; let n = 0, solid = 0; for (let i = 3; i < d.length; i += stride) { n++; if (d[i] > 160) solid++; } return n ? solid / n : 0; } /** Cobertura del emoji ya pintado (para el diagnóstico). */ export function emojiCoverage(emoji: string, px = 256): number { const e = cache.get(`${emoji}@${px}`); if (!e) return -1; return coverage(e.canvas.getContext('2d', { willReadFrequently: true })!, px); } function refresh(e: Entry): void { draw(e); e.tex.needsUpdate = true; if (e.pm) fillPM(e, e.pm as THREE.DataTexture); if (e.safe) e.safe.needsUpdate = true; if (e.normal) buildNormalMap(e, e.normal.image as HTMLCanvasElement), (e.normal.needsUpdate = true); } function fontAvailable(): boolean { return typeof document !== 'undefined' && !!document.fonts; } /** Pide a la fuente los glifos del emoji (la fuente va troceada por unicode-range) y redibuja al llegar. */ function requestGlyph(e: Entry): void { if (!fontAvailable()) return; const p = document.fonts .load(`64px "Noto Color Emoji"`, e.emoji) .then((faces) => { if (faces.length) { fontFace = true; e.fontOk = true; refresh(e); } }) .catch(() => {}) .finally(() => pending.delete(p)); pending.add(p); } /** Resuelve cuando la fuente de emojis (y los glifos pedidos hasta ahora) están listos. */ export function emojiReady(): Promise { if (!fontAvailable()) return Promise.resolve(); const base = document.fonts.load(`64px "Noto Color Emoji"`, '😀').then(() => { fontFace = true; }).catch(() => {}); return Promise.all([base, ...pending]).then(() => undefined); } /** true cuando la fuente propia ya se ha cargado al menos una vez. */ export function emojiFontLoaded(): boolean { return fontFace; } function entry(emoji: string, px: number): Entry { const key = `${emoji}@${px}`; let e = cache.get(key); if (e) return e; const canvas = document.createElement('canvas'); canvas.width = canvas.height = px; const tex = new THREE.CanvasTexture(canvas); tex.colorSpace = THREE.SRGBColorSpace; tex.anisotropy = 4; tex.generateMipmaps = true; tex.minFilter = THREE.LinearMipmapLinearFilter; tex.userData.shared = true; e = { emoji, px, canvas, tex, fontOk: false }; cache.set(key, e); draw(e); requestGlyph(e); return e; } /** Textura cuadrada con el emoji centrado. Cacheada y compartida: no la liberes. */ export function emojiTexture(emoji: string, px = 256): THREE.Texture { return entry(emoji, px).tex; } /** * Píxeles del emoji premultiplicados por el alfa (en sRGB) y con las filas invertidas para WebGL. * Se rellenan a mano para no depender de la subida de canvas con «premultiplyAlpha» ni de mipmaps sRGB: * en varias GPU de celular esas dos vías dejaban la textura vacía y el emoji desaparecía. */ function fillPM(e: Entry, t: THREE.DataTexture): void { const px = e.px; const src = e.canvas.getContext('2d', { willReadFrequently: true })!.getImageData(0, 0, px, px).data; const dst = t.image.data as Uint8Array; for (let y = 0; y < px; y++) { const sr = y * px * 4; const dr = (px - 1 - y) * px * 4; for (let x = 0; x < px * 4; x += 4) { const a = src[sr + x + 3]; const k = a / 255; dst[dr + x] = Math.round(src[sr + x] * k); dst[dr + x + 1] = Math.round(src[sr + x + 1] * k); dst[dr + x + 2] = Math.round(src[sr + x + 2] * k); dst[dr + x + 3] = a; } } t.needsUpdate = true; } /** * Textura del emoji con alfa premultiplicado, en RGBA8 lineal (sin formato sRGB): el shader del material * (premultipliedMap) des-premultiplica y convierte a lineal. Compartida; no la liberes. */ export function emojiTexturePM(emoji: string, px = 256): THREE.Texture { const e = entry(emoji, px); if (!e.pm) { const t = new THREE.DataTexture(new Uint8Array(px * px * 4), px, px, THREE.RGBAFormat, THREE.UnsignedByteType); t.colorSpace = THREE.NoColorSpace; t.generateMipmaps = true; t.minFilter = THREE.LinearMipmapLinearFilter; t.magFilter = THREE.LinearFilter; t.anisotropy = 4; t.userData.shared = true; t.userData.emojiPM = true; e.pm = t; fillPM(e, t); } return e.pm; } // ───────────────────────────── Mapa de normales desde la silueta ───────────────────────────── /** * Genera el mapa de normales del "inflado": distancia al borde (chamfer 3-4) → perfil circular * (almohada) → suavizado → gradiente. Añade un relieve leve de los rasgos (ojos/boca hundidos). */ function buildNormalMap(e: Entry, out: HTMLCanvasElement): void { const src = e.canvas.getContext('2d', { willReadFrequently: true })!.getImageData(0, 0, e.px, e.px).data; const n = Math.min(128, e.px); const step = e.px / n; out.width = out.height = n; const N = n * n; const alpha = new Float32Array(N); const lum = new Float32Array(N); for (let y = 0; y < n; y++) { for (let x = 0; x < n; x++) { const i = ((Math.floor(y * step + step / 2) * e.px) + Math.floor(x * step + step / 2)) * 4; const a = src[i + 3] / 255; alpha[y * n + x] = a; lum[y * n + x] = a > 0.01 ? (src[i] * 0.3 + src[i + 1] * 0.55 + src[i + 2] * 0.15) / 255 : 1; } } // transformada de distancia (interior) en píxeles const BIG = 1e6; const d = new Float32Array(N); for (let i = 0; i < N; i++) d[i] = alpha[i] > 0.4 ? BIG : 0; for (let y = 0; y < n; y++) { for (let x = 0; x < n; x++) { const i = y * n + x; if (!d[i]) continue; let v = d[i]; if (x > 0) v = Math.min(v, d[i - 1] + 1); if (y > 0) { v = Math.min(v, d[i - n] + 1); if (x > 0) v = Math.min(v, d[i - n - 1] + 1.4142); if (x < n - 1) v = Math.min(v, d[i - n + 1] + 1.4142); } else v = Math.min(v, 1); if (x === 0 || x === n - 1) v = Math.min(v, 1); d[i] = v; } } for (let y = n - 1; y >= 0; y--) { for (let x = n - 1; x >= 0; x--) { const i = y * n + x; if (!d[i]) continue; let v = d[i]; if (x < n - 1) v = Math.min(v, d[i + 1] + 1); if (y < n - 1) { v = Math.min(v, d[i + n] + 1); if (x < n - 1) v = Math.min(v, d[i + n + 1] + 1.4142); if (x > 0) v = Math.min(v, d[i + n - 1] + 1.4142); } else v = Math.min(v, 1); d[i] = v; } } let maxD = 1; for (let i = 0; i < N; i++) if (d[i] > maxD) maxD = d[i]; // radio del "bisel": parte de la forma, con tope para que las formas grandes no queden planas const R = Math.max(3, Math.min(maxD, n * 0.3)); const h = new Float32Array(N); for (let i = 0; i < N; i++) { const t = Math.min(1, d[i] / R); const pillow = Math.sqrt(1 - (1 - t) * (1 - t)); h[i] = pillow * R * 0.9 - (1 - lum[i]) * 1.3 * Math.min(1, t * 3); } blur(h, n, 2); // normales (canvas: y hacia abajo; uv: v hacia arriba) const img = out.getContext('2d')!.createImageData(n, n); const o = img.data; const k = 0.55; for (let y = 0; y < n; y++) { for (let x = 0; x < n; x++) { const i = y * n + x; const hx = h[y * n + Math.min(n - 1, x + 1)] - h[y * n + Math.max(0, x - 1)]; const hy = h[Math.min(n - 1, y + 1) * n + x] - h[Math.max(0, y - 1) * n + x]; let nx = -hx * k, ny = hy * k, nz = 1; const l = Math.hypot(nx, ny, nz); nx /= l; ny /= l; nz /= l; o[i * 4] = (nx * 0.5 + 0.5) * 255; o[i * 4 + 1] = (ny * 0.5 + 0.5) * 255; o[i * 4 + 2] = (nz * 0.5 + 0.5) * 255; o[i * 4 + 3] = 255; } } out.getContext('2d')!.putImageData(img, 0, 0); } /** Desenfoque de caja separable, `passes` veces (≈ gaussiano). */ function blur(a: Float32Array, n: number, passes: number): void { const tmp = new Float32Array(a.length); for (let p = 0; p < passes; p++) { for (let y = 0; y < n; y++) { for (let x = 0; x < n; x++) { const i = y * n + x; tmp[i] = (a[y * n + Math.max(0, x - 1)] + a[i] + a[y * n + Math.min(n - 1, x + 1)]) / 3; } } for (let y = 0; y < n; y++) { for (let x = 0; x < n; x++) { a[y * n + x] = (tmp[Math.max(0, y - 1) * n + x] + tmp[y * n + x] + tmp[Math.min(n - 1, y + 1) * n + x]) / 3; } } } } /** Mapa de normales del emoji inflado (compartido, cacheado). */ export function emojiNormalMap(emoji: string, px = 256): THREE.Texture { const e = entry(emoji, px); if (!e.normal) { const c = document.createElement('canvas'); buildNormalMap(e, c); const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.NoColorSpace; t.userData.shared = true; e.normal = t; } return e.normal; } // ───────────────────────────── Mesh ───────────────────────────── export interface EmojiMeshOpts { /** Brilla (se suma al bloom). */ glow?: boolean; /** Proyecta sombra. Por defecto true. */ shadow?: boolean; opacity?: number; /** Fuerza del brillo con glow (por defecto 1). */ glowIntensity?: number; /** Relieve del inflado 0..2 (por defecto 1; 0 = plano). */ puff?: number; /** Brillo especular 0..1 (por defecto 0.55). */ gloss?: number; /** Luz de borde (por defecto 0.35). */ rim?: number; /** Resolución de la textura (por defecto 256). */ px?: number; /** Recibe sombras (por defecto true). */ receiveShadow?: boolean; } let planeGeo: THREE.PlaneGeometry | null = null; const depthMats = new Map(); const distMats = new Map(); function sharedPlane(): THREE.PlaneGeometry { if (!planeGeo) { planeGeo = new THREE.PlaneGeometry(1, 1); planeGeo.userData.shared = true; } return planeGeo; } /** Material de silueta para sombras (alphaTest sobre el mapa). */ function shadowMats(map: THREE.Texture): [THREE.MeshDepthMaterial, THREE.MeshDistanceMaterial] { let dm = depthMats.get(map); if (!dm) { dm = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, map, alphaTest: 0.5, side: THREE.DoubleSide }); dm.userData.shared = true; depthMats.set(map, dm); } let xm = distMats.get(map); if (!xm) { xm = new THREE.MeshDistanceMaterial({ map, alphaTest: 0.5, side: THREE.DoubleSide }); xm.userData.shared = true; distMats.set(map, xm); } return [dm, xm]; } /** Material "emoji inflado" (uno nuevo por llamada; texturas compartidas). */ export function emojiMaterial(emoji: string, opts: EmojiMeshOpts = {}): ToonMaterial { const px = opts.px ?? 256; const map = emojiTexturePM(emoji, px); const puff = opts.puff ?? 1; const opacity = opts.opacity ?? 1; const mat = toonMaterial({ color: 0xffffff, map, gloss: opts.gloss ?? 0.55, rim: opts.rim ?? 0.35, rimPower: 3, normalMap: puff > 0 ? emojiNormalMap(emoji, px) : null, side: THREE.DoubleSide, transparent: blend || opacity < 1, opacity, alphaTest: blend ? 0 : opacity < 1 ? 0.02 : 0.5, premultipliedMap: true, }); if (puff > 0) mat.normalScale.set(puff, puff); // Sin alpha-to-coverage: en varias GPUs móviles hacía desaparecer el emoji. El recorte por alphaTest // funciona en todas partes (y el MSAA sigue suavizando la geometría). if (opts.glow) { mat.emissive.set(0xffffff); mat.emissiveMap = map; mat.emissiveIntensity = 0.9 * (opts.glowIntensity ?? 1); } else { // Un plano de cara a la cámara recibe poca luz directa: un poco de color propio mantiene // el emoji tan vivo como en el teléfono (sin llegar al umbral del bloom). mat.emissive.set(0xffffff); mat.emissiveMap = map; mat.emissiveIntensity = 0.28; } return mat; } /** Plano de `size` unidades de alto con el emoji, iluminado y con volumen. Origen en el centro. */ // ───────────────────────────── Respaldo para GPUs problemáticas ───────────────────────────── let fallback = false; /** Activa el material de respaldo (sencillo, sin shaders propios) para todos los emojis que se creen. */ export function setEmojiFallback(on: boolean): void { fallback = on; } export function emojiFallbackActive(): boolean { return fallback; } const safeTex = new Map(); /** Textura recta sin mipmaps: la vía de subida más compatible que existe. */ function emojiTextureSafe(emoji: string, px = 256): THREE.Texture { const key = `${emoji}@${px}`; let t = safeTex.get(key); if (!t) { const e = entry(emoji, px); t = new THREE.CanvasTexture(e.canvas); t.colorSpace = THREE.SRGBColorSpace; t.generateMipmaps = false; t.minFilter = THREE.LinearFilter; t.magFilter = THREE.LinearFilter; t.userData.shared = true; safeTex.set(key, t); e.safe = t; } return t; } function fallbackMaterial(emoji: string, opts: EmojiMeshOpts): THREE.MeshBasicMaterial { const opacity = opts.opacity ?? 1; const mat = new THREE.MeshBasicMaterial({ map: emojiTextureSafe(emoji, opts.px ?? 256), alphaTest: blend ? 0 : opacity < 1 ? 0.02 : 0.5, transparent: blend || opacity < 1, opacity, side: THREE.DoubleSide, }); if (opts.glow) mat.color.setScalar(1 + 0.25 * (opts.glowIntensity ?? 1)); return mat; } /** Resultado de la prueba de dibujo de emojis (ver emojiSelfTest). */ export interface EmojiTestResult { ok: boolean; pixels: number; canvasBlank: boolean; error?: string } /** Emojis por mezcla de transparencia en vez de recorte (alphaTest/discard): remedio para GPUs con MSAA problemático. */ let blend = false; export function setEmojiBlend(on: boolean): void { blend = on; } export function emojiBlendActive(): boolean { return blend; } export interface EmojiTestOpts { /** Muestras MSAA del destino (0 = sin MSAA). */ samples?: number; /** Formato del destino: como el del juego (media precisión) o RGBA8. */ halfFloat?: boolean; /** Prueba el modo mezcla en lugar del recorte. */ blend?: boolean; } /** * Dibuja una moneda fuera de pantalla con la misma configuración que el juego (MSAA, formato, material) y cuenta * los píxeles. Sirve para elegir al arrancar una configuración que funcione en la GPU de cada teléfono. */ export function emojiSelfTest(renderer: THREE.WebGLRenderer, opts: EmojiTestOpts = {}): EmojiTestResult { const res: EmojiTestResult = { ok: false, pixels: 0, canvasBlank: false }; const prevBlend = blend; try { const e = entry('🪙', 256); const g = e.canvas.getContext('2d', { willReadFrequently: true })!; res.canvasBlank = isBlank(g, 256); blend = !!opts.blend; const scene = new THREE.Scene(); scene.fog = new THREE.Fog(0xffffff, 50, 100); scene.add(new THREE.HemisphereLight(0xffffff, 0x888888, 1.2)); const sun = new THREE.DirectionalLight(0xffffff, 2); sun.position.set(1, 2, 3); sun.castShadow = true; scene.add(sun); // un cubo opaco detrás, como el resto del escenario const back = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.3, 0.3), new THREE.MeshStandardMaterial({ color: 0x334455 })); back.position.set(0.45, 0.45, -1); scene.add(back); const mesh = emojiMesh('🪙', 1, { glow: true, glowIntensity: 0.35 }); mesh.position.x = -0.05; scene.add(mesh); const cam = new THREE.OrthographicCamera(-0.6, 0.6, 0.6, -0.6, 0.1, 10); cam.position.z = 2; const N = 32; const target = new THREE.WebGLRenderTarget(N, N, { samples: opts.samples ?? 0, type: opts.halfFloat ? THREE.HalfFloatType : THREE.UnsignedByteType, }); const prevTarget = renderer.getRenderTarget(); const prevColor = renderer.getClearColor(new THREE.Color()); const prevAlpha = renderer.getClearAlpha(); renderer.setClearColor(0x000000, 0); renderer.setRenderTarget(target); renderer.clear(); renderer.render(scene, cam); // Copia (resuelve el MSAA) a un RGBA8 sencillo para leer, igual que hace la cadena de post. const read = new THREE.WebGLRenderTarget(N, N); const quadScene = new THREE.Scene(); const quadMat = new THREE.MeshBasicMaterial({ map: target.texture, transparent: false }); const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), quadMat); quadScene.add(quad); const quadCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1); renderer.setRenderTarget(read); renderer.clear(); renderer.render(quadScene, quadCam); const px = new Uint8Array(N * N * 4); renderer.readRenderTargetPixels(read, 0, 0, N, N, px); renderer.setRenderTarget(prevTarget); renderer.setClearColor(prevColor, prevAlpha); // píxeles de la moneda: dorados (rojo alto, azul bajo) en la mitad izquierda for (let y = 0; y < N; y++) { for (let x = 0; x < N * 0.62; x++) { const i = (y * N + x) * 4; if (px[i] > 90 && px[i] > px[i + 2] + 30) res.pixels++; } } res.ok = res.pixels > 30; target.dispose(); read.dispose(); quadMat.dispose(); quad.geometry.dispose(); back.geometry.dispose(); (back.material as THREE.Material).dispose(); (mesh.material as THREE.Material).dispose(); } catch (err) { res.error = String(err); } blend = prevBlend; return res; } export function emojiMesh(emoji: string, size = 1, opts: EmojiMeshOpts = {}): THREE.Mesh { if (fallback) { const m = new THREE.Mesh(sharedPlane(), fallbackMaterial(emoji, opts)); m.scale.set(size, size, size); m.castShadow = false; m.name = `emoji:${emoji}`; attachDomEmoji(m, emoji, !!opts.glow); return m; } const mat = emojiMaterial(emoji, opts); const mesh = new THREE.Mesh(sharedPlane(), mat); mesh.scale.set(size, size, size); mesh.castShadow = opts.shadow ?? true; mesh.receiveShadow = opts.receiveShadow ?? true; const [dm, xm] = shadowMats(mat.map!); mesh.customDepthMaterial = dm; mesh.customDistanceMaterial = xm; mesh.name = `emoji:${emoji}`; attachDomEmoji(mesh, emoji, !!opts.glow); return mesh; } /** * Emoji sin luz que siempre mira a cámara (iconos flotantes, indicadores). No proyecta sombra. * `glow` lo hace superar el umbral del bloom. */ export function emojiSprite(emoji: string, size = 1, opts: { glow?: number; opacity?: number } = {}): THREE.Sprite { const mat = new THREE.SpriteMaterial({ map: fallback ? emojiTextureSafe(emoji) : emojiTexturePM(emoji), transparent: true, opacity: opts.opacity ?? 1, premultipliedAlpha: !fallback, depthWrite: false, }); if (opts.glow) mat.color.setScalar(1 + opts.glow); const s = new THREE.Sprite(mat); s.scale.set(size, size, 1); attachDomEmoji(s, emoji, !!opts.glow); return s; }