// Biblioteca de personagens: assets/characters//character.json. Um personagem é criado uma vez (da // descrição, ajustado no formulário ou pelo agente) e reaproveitado em qualquer história: o elenco da história // fica em stories//cast.json e a montagem Cartoon usa a mesma aparência em todas as cenas. // O contrato da aparência é o do pacote cartoon (cartoon/src/character.ts), importado direto daqui. import fs from "node:fs"; import path from "node:path"; import { DEFAULT_LOOK, EXPRESSIONS, POSES, validateLook, type Character, type CharacterLook, type Expression, type Pose, } from "cenaforge-cartoon/character"; import { REPO_ROOT, SLUG_RE, rel, storyDir } from "./paths"; import { UserError } from "./stories"; export type { Character, CharacterLook, Expression, Pose }; export { EXPRESSIONS, POSES }; export const CHARACTERS_DIR = path.join(REPO_ROOT, "assets", "characters"); const fileOf = (id: string) => path.join(CHARACTERS_DIR, id, "character.json"); function mustId(id: string): string { if (!SLUG_RE.test(id)) throw new UserError("Identificador de personagem inválido."); return id; } export function slugify(name: string): string { return name.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "personagem"; } export function listCharacters(): Character[] { if (!fs.existsSync(CHARACTERS_DIR)) return []; return fs.readdirSync(CHARACTERS_DIR, { withFileTypes: true }) .filter((d) => d.isDirectory() && SLUG_RE.test(d.name)) .map((d) => readCharacter(d.name)) .filter((c): c is Character => !!c) .sort((a, b) => a.name.localeCompare(b.name, "pt-BR")); } function readCharacter(id: string): Character | null { try { const data = JSON.parse(fs.readFileSync(fileOf(id), "utf8")) as Character; if (data.schemaVersion !== 1 || data.id !== id || validateLook(data.look).length) return null; return data; } catch { return null; } } export function getCharacter(id: string): Character | null { return readCharacter(mustId(id)); } function clean(raw: unknown, max: number): string { return String(raw ?? "").replace(/\s+/g, " ").trim().slice(0, max); } /** Cria (id novo) ou salva (id existente). A aparência é conferida pelo contrato do cartoon. */ export function saveCharacter(input: { id?: unknown; name?: unknown; caption?: unknown; description?: unknown; kind?: unknown; look?: unknown; godot?: unknown }, create = false): Character { const name = clean(input.name, 40); if (name.length < 2) throw new UserError("Dê um nome ao personagem."); const kind = input.kind === "3d" ? "3d" : "cartoon"; const look = (input.look ?? DEFAULT_LOOK) as CharacterLook; const errors = validateLook(look); if (errors.length) throw new UserError(`Aparência inválida: ${errors.join("; ")}`); let id = input.id ? mustId(String(input.id)) : slugify(name); const existing = fs.existsSync(fileOf(id)) ? readCharacter(id) : null; if (create && existing) { let n = 2; while (fs.existsSync(fileOf(`${id}-${n}`))) n++; id = `${id}-${n}`; } if (!create && !existing) throw new UserError("Personagem não encontrado."); const now = new Date().toISOString(); const character: Character = { schemaVersion: 1, id, name, kind, look, caption: clean(input.caption, 50) || undefined, description: clean(input.description, 600) || undefined, ...(kind === "3d" && input.godot && typeof input.godot === "object" ? { godot: input.godot as Record } : {}), createdAt: create || !existing ? now : existing.createdAt, updatedAt: now, }; fs.mkdirSync(path.dirname(fileOf(id)), { recursive: true }); fs.writeFileSync(fileOf(id), JSON.stringify(character, null, 2) + "\n", "utf8"); return character; } export function deleteCharacter(id: string): void { const dir = path.join(CHARACTERS_DIR, mustId(id)); if (!fs.existsSync(dir)) throw new UserError("Personagem não encontrado."); const used = listCastUsage(id); if (used.length) throw new UserError(`Este personagem está no elenco de: ${used.join(", ")}. Tire-o do elenco antes de apagar.`); fs.rmSync(dir, { recursive: true, force: true }); } // ---------- descrição → aparência (regras; o agente pode refinar depois) ---------- const COLORS: [RegExp, string][] = [ [/verde/, "#56704a"], [/azul/, "#2f6db3"], [/vermelh/, "#c8443a"], [/amarel/, "#e8b13a"], [/roxo|lilas/, "#8e6ad8"], [/rosa/, "#e27ba8"], [/preto|preta/, "#26262e"], [/branc/, "#e9ecef"], [/cinza/, "#7c828c"], [/laranja/, "#e07b39"], [/marrom/, "#7a5232"], [/bege/, "#cdb48a"], ]; const HAIR_COLORS: [RegExp, string][] = [ [/grisalh|cabelo branco|cabelos brancos/, "#c9c9cf"], [/loir/, "#e8c35a"], [/ruiv/, "#b4532a"], [/castanh/, "#6b4226"], [/cabelo preto|cabelos pretos/, "#1e1612"], ]; const PROFESSIONS: [RegExp, { top: CharacterLook["top"]; caption: string }][] = [ [/engenheir/, { top: { style: "uniform", color: "#56704a", accent: "#e8b13a" }, caption: "Engenheiro" }], [/policial|delegad/, { top: { style: "uniform", color: "#2b3a67", accent: "#e8b13a" }, caption: "Policial" }], [/medic|enfermeir/, { top: { style: "jacket", color: "#e9ecef", accent: "#4fb0e8" }, caption: "Saúde" }], [/bombeir/, { top: { style: "uniform", color: "#c8352f", accent: "#f2c230" }, caption: "Bombeiro" }], [/militar|soldad/, { top: { style: "uniform", color: "#5b6b3a", accent: "#3a4a2a" }, caption: "Militar" }], [/professor/, { top: { style: "jacket", color: "#7a5232", accent: "#e9ecef" }, caption: "Professor" }], [/tecnico|treinador/, { top: { style: "jacket", color: "#1f3a7a", accent: "#f2c230" }, caption: "Técnico" }], [/porteiro|seguranca|vigia/, { top: { style: "jacket", color: "#2f4f86", accent: "#e9ecef" }, caption: "Porteiro" }], [/merendeir|cozinheir/, { top: { style: "shirt", color: "#c85a5a" }, caption: "Merendeira" }], [/roupeiro/, { top: { style: "jacket", color: "#56704a", accent: "#e9ecef" }, caption: "Roupeiro" }], [/obra|pedreiro|operario/, { top: { style: "shirt", color: "#56704a" }, caption: "Operário" }], [/empresari|executiv|advogad/, { top: { style: "jacket", color: "#3a3f4f", accent: "#e9ecef" }, caption: "Empresário" }], ]; /** Aparência e legenda a partir de uma descrição curta ("Otávio, 58, engenheiro, barba grisalha, óculos"). */ export function describeToLook(description: string): { look: CharacterLook; caption?: string } { const t = description.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase(); const age = Number(/\b(\d{1,2})\s*(anos)?\b/.exec(t)?.[1] ?? NaN); const female = /\b(ela|mulher|moca|senhora|dona|menina|garota|vo|avo|tia|mae|filha|esposa)\b/.test(t); const child = /\b(crianca|menino|menina|garoto|garota)\b/.test(t) || (age > 0 && age <= 12); const old = age >= 55 || /\b(idos|velh|senhor|senhora|vo|avo)\w*/.test(t); const hairColor = HAIR_COLORS.find(([re]) => re.test(t))?.[1] ?? (old ? "#c9c9cf" : "#3a2a1e"); const style: CharacterLook["hair"]["style"] = /careca|calvo/.test(t) ? "bald" : /coque/.test(t) ? "bun" : /bone\b/.test(t) ? "cap" : /cachead|crespo|black power/.test(t) ? "curly" : /espetad/.test(t) ? "spiky" : /cabelo (longo|comprido)|cabelos longos/.test(t) ? "long" : /repartid|de lado/.test(t) ? "side" : female ? (old ? "bun" : "long") : "short"; const beard: CharacterLook["beard"]["style"] = female ? "none" : /barba por fazer/.test(t) ? "stubble" : /cavanhaque/.test(t) ? "goatee" : /bigode/.test(t) && !/barba/.test(t) ? "mustache" : /barba( \w+)? (longa|comprida)|barbas? ate o peito/.test(t) ? "long" : /barb/.test(t) ? "full" : "none"; // Cor de cabelo, barba e roupa não diz nada da pele ("barba branca", "cabelo preto", "túnica branca"). const ts = t.replace(/\b(cabelos?|barbas?|bigode|tunica|roupa|camisa|camiseta|vestido|jaqueta|casaco|bone|calca|sapato)\s+(\w+\s+)?(branc|pret|loir|ruiv)\w*/g, " "); const skin = /\b(negr[oa]|pret[oa]|pele escura)\b/.test(ts) ? "#8d5a3b" : /\b(moren[oa]|pard[oa])\b/.test(ts) ? "#c98a5e" : /\b(branc[oa]|pele clara|loir[oa]|ruiv[oa])\b/.test(ts) ? "#f1c7a3" : "#e0b48f"; const profession = PROFESSIONS.find(([re]) => re.test(t))?.[1]; const clothColor = COLORS.find(([re]) => new RegExp(`(roupa|camisa|camiseta|vestido|jaqueta|casaco|moletom|blusa|tunica|manto)\\s+\\w*\\s*${re.source}`).test(t))?.[1]; const topStyle: CharacterLook["top"]["style"] = /tunica|manto|roupa antiga|bata/.test(t) ? "robe" : /vestido/.test(t) ? "dress" : /jaqueta|casaco/.test(t) ? "jacket" : /moletom/.test(t) ? "hoodie" : /uniforme|macacao/.test(t) ? "uniform" : profession?.top.style ?? (female && old ? "dress" : "shirt"); // Túnica sem cor dita: tecido cru com faixa marrom (roupa antiga). const top = { ...(profession?.top ?? (topStyle === "robe" ? { style: topStyle, color: female ? "#8a6f9e" : "#a8865a", accent: "#6b4a2a" } : { style: topStyle, color: "#4f7a4a" })), style: topStyle, ...(clothColor ? { color: clothColor } : {}) }; const look: CharacterLook = { build: /\b(gord[oa]|fort[e]|robust[oa]|grand[e]|gordinh[oa])\b/.test(t) ? "heavy" : /\b(magr[oa]|magrel[oa]|franzin[oa])\b/.test(t) || child ? "slim" : "average", height: child ? 0.78 : /\b(alt[oa])\b/.test(t) ? 1.08 : /\b(baix[oa]|baixinh[oa])\b/.test(t) ? 0.92 : female ? 0.96 : 1, skin, hair: { style, color: style === "cap" ? (COLORS.find(([re]) => new RegExp(`bone\\s+${re.source}`).test(t))?.[1] ?? "#2f6db3") : hairColor }, beard: { style: beard, color: hairColor === "#c9c9cf" ? "#a9a9b0" : hairColor }, glasses: /oculos escuros/.test(t) ? "sun" : /oculos quadrad/.test(t) ? "square" : /oculos/.test(t) ? "round" : "none", brows: old || /sobrancelha grossa|bravo|serio/.test(t) ? "thick" : "thin", top: top as CharacterLook["top"], bottom: { style: /\b(short|bermuda)\b/.test(t) || child ? "shorts" : /\bsaia\b/.test(t) ? "skirt" : "pants", color: female && /saia/.test(t) ? top.color : "#2c3346" }, shoes: /sandalia/.test(t) ? "#6b4a2a" : child ? "#f2f2f2" : "#1d1d24", ...(/sandalia/.test(t) ? { footwear: "sandals" as const } : /descalc|pe no chao/.test(t) ? { footwear: "bare" as const } : {}), }; // Detalhe de ilustração: nariz, pálpebra, rugas, formato da cabeça, barriga e acessórios pela descrição. look.nose = /narigud|nariz grande|nariz comprido/.test(t) ? "long" : /nariz largo|nariz de batata/.test(t) ? "wide" : old && !female ? "curve" : child ? "button" : female ? "button" : "round"; look.lids = Math.min(0.6, (old ? 0.3 : 0.1) + (/cansad|sonolent|olhar caido|palpebras? caid|desconfiad/.test(t) ? 0.2 : 0)); look.wrinkles = /rugas|enrugad/.test(t) ? 0.85 : age >= 60 || /idos|velh/.test(t) ? 0.7 : age >= 45 ? 0.4 : old ? 0.6 : 0; look.head = /rosto quadrado|queixo quadrado/.test(t) ? "square" : /rosto fino|rosto comprido/.test(t) ? "oval" : look.build === "heavy" ? "wide" : "round"; if (/barrig|panca/.test(t) || (look.build === "heavy" && age >= 40 && !female)) look.belly = true; const acc = new Set[number]>(); if (/tecnico|treinador|juiz|arbitr|professor de educacao fisica/.test(t)) { acc.add("whistle"); acc.add("watch"); } if (/obra|pedreiro|operario|mestre de obra/.test(t)) { acc.add("helmet"); acc.add("vest"); look.accessoryColor = "#ff8a2a"; } if (/porteiro|seguranca|vigia|crach/.test(t)) acc.add("badge"); if (/merendeir|cozinheir|padeir|avental/.test(t)) { acc.add("apron"); look.accessoryColor ??= "#f4f1e8"; } if (/roupeiro|massagista|toalha/.test(t)) acc.add("towel"); if (/empresari|executiv|advogad|gerente|gravata/.test(t)) { acc.add("tie"); acc.add("watch"); } if (/cachecol|lenco/.test(t)) acc.add("scarf"); if (/fone|locutor|radialista|atendente/.test(t)) acc.add("headset"); if (/correntao|corrente de ouro|cordao/.test(t)) acc.add("chain"); if (/capacete/.test(t)) acc.add("helmet"); if (/colete/.test(t)) acc.add("vest"); if (/relogio/.test(t)) acc.add("watch"); if (acc.size) look.accessories = [...acc]; const caption = [profession?.caption, age > 0 ? `${age} anos` : ""].filter(Boolean).join(" · ") || undefined; return { look, caption }; } // ---------- elenco da história ---------- const castFile = (storyId: string) => path.join(storyDir(storyId), "cast.json"); /** Elenco da história: ids dos personagens da biblioteca (os que sumiram da biblioteca são ignorados). */ export function getCast(storyId: string): Character[] { try { const ids = JSON.parse(fs.readFileSync(castFile(storyId), "utf8")) as { cast?: string[] }; return (ids.cast ?? []).map((id) => (SLUG_RE.test(id) ? readCharacter(id) : null)).filter((c): c is Character => !!c); } catch { return []; } } export function setCast(storyId: string, ids: unknown): Character[] { if (!Array.isArray(ids) || ids.length > 12) throw new UserError("Elenco inválido (até 12 personagens)."); const valid = [...new Set(ids.map(String))].filter((id) => SLUG_RE.test(id) && readCharacter(id)); fs.mkdirSync(storyDir(storyId), { recursive: true }); fs.writeFileSync(castFile(storyId), JSON.stringify({ cast: valid }, null, 2) + "\n", "utf8"); return getCast(storyId); } function listCastUsage(id: string): string[] { const root = path.join(REPO_ROOT, "stories"); if (!fs.existsSync(root)) return []; return fs.readdirSync(root).filter((s) => { try { return (JSON.parse(fs.readFileSync(castFile(s), "utf8")) as { cast?: string[] }).cast?.includes(id); } catch { return false; } }); } export const characterFileRel = (id: string) => rel(fileOf(mustId(id)));