Compare commits

..
31 Commits
Author SHA1 Message Date
MateuusandClaude Opus 5.5 d9bf411e7a Clipador: chat da Kick pelo Centrifugo (a chave fixa do Pusher parou de valer)
A Kick passou a escolher o provedor de tempo real por canal (POST web.kick.com/api/v1/realtime/channels/<id>/chat/
connection) e hoje responde Centrifugo; o Pusher com a chave antiga recusava com "App key not in this cluster" e o
chat de toda fonte da Kick ficava em erro. Agora: token de convidado (/v1/realtime/auth/connection, sem login) →
connect → subscribe chatrooms.<sala>.v2; ping {} respondido; token expira e o laço reconecta. Se a Kick indicar
Pusher, usa a chave e o cluster que ela informar. Testado ao vivo no chat de kick.com/peusantista.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:46:13 -03:00
MateuusandClaude Opus 5.5 dbb5e8ef92 Sincronização: detecção do jogo + revisão/final, dublagem, falantes, expressões e Equipe de IA
Conflitos resolvidos juntando os dois lados:
- db.py: v16 (detecção do jogo) e v17 (Equipe de IA) em sequência.
- judge.py: a varredura exige os campos das duas frentes (screen_game_confidence/screen_evidence e lines).
- proxy do painel: libera judge/report e sessions/id/game/detect.
- skill: detecção do jogo vira a 1.55.0 (gotcha 180 → 186), acima da 1.54.0 das cinco frentes.

Suíte do Clipador inteira passa; painel: tsc + 119 testes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:11:47 -03:00
MateuusandClaude Opus 5.5 b923132a69 Cartoon: estudo de handoff do personagem (.studies) e AGENTS.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:08:57 -03:00
MateuusandClaude Opus 5.5 215faa331c Skill cenaforge: detecção do jogo (edição de outra sessão, commitada na sincronização)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:08:57 -03:00
MateuusandClaude Opus 5.5 44bb961d1a Clipador: detecção do jogo cruzando categoria e tela (confiança, evidência e sugestão de troca)
Trabalho de outra sessão, commitado na sincronização de 18/11/2026 (doc/clipador/DETECCAO-JOGO.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:08:57 -03:00
MateuusandClaude Opus 5.5 96619c223b Doc: migrações corretas em FALANTES.md (v15) e EQUIPE-IA.md (v16 = detecção do jogo)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:53:58 -03:00
MateuusandClaude Opus 5.5 b11090ffa3 Skill cenaforge 1.54.0: Clipador (revisão × final, dublagem, falantes, expressões, Equipe de IA)
Dois arquivos novos em references/ (clipper-video.md, clipper-ai-team.md), banco em v17,
seção de expressões, gotchas 180–185 e ponteiros em panel/publishing/ai/tools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:53:34 -03:00
Mateuus e4a5bc026c Cartoon: corpo contínuo sem juntas e novas mãos em 2 camadas 2026-11-18 04:50:20 -03:00
MateuusandClaude Opus 5.5 08ab68d16e Clipador: v16 = detecção do jogo (colunas da sessão em andamento na pasta principal)
O banco real já foi migrado com essa v16 (game_status, game_detect_json) pelo código ainda não commitado da frente de
detecção do jogo. A v16 sem efeito do main passa a ser exatamente essa migração, para o banco real e o main ficarem
coerentes e o merge daquela frente ser trivial. A Equipe de IA continua na v17.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:49:25 -03:00
MateuusandClaude Opus 5.5 7bf9fddab6 Integração: Equipe de IA + expressões (v16 fica sem efeito: as expressões não precisaram de migração)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:47:16 -03:00
Mateuus 22673c4b5f Merge branch 'clipper/roles' into clipper/integ 2026-11-18 04:45:34 -03:00
MateuusandClaude Opus 5.5 76b722c499 Doc: Equipe de IA (doc/clipador/EQUIPE-IA.md) e contrato por papel em doc/ia.md
- EQUIPE-IA.md: papéis e configuração (judge.roles, migração), juiz de contexto e as regras
  de decisão pelo código, linha do tempo JSON + mosaico, medição (ai_calls, owner_label,
  GET /v1/judge/report) e o medido no corte 291 (analista −45%, varredura −38%, editor −20%;
  ≈ −29% por hora já com o juiz; 1 chamada real do juiz no Codex: 9.624 tokens de entrada).
- doc/ia.md: reserva por papel, codex exec --json e leitura de uso por CLI.
- README do Clipador: rotas /v1/judge e /v1/judge/report.
- judge.describe: uma checagem por provedor para todas as cadeias (o painel lê o status a
  cada poucos segundos); sem analista, o editor recebe as imagens no modo escolhido.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:44:56 -03:00
MateuusandClaude Opus 5.5 26c9afa13a Painel: Equipe de IA no lugar do provedor único, juiz de contexto no modal e medição
- Ajustes → Juiz: "Usar IA" + um cartão por papel (varredura, analista, editor, juiz) com
  provedor, modelo do provedor escolhido, raciocínio (Codex), imagens (mosaico/quadros/nenhuma),
  liga/desliga (o editor não desliga), instruções padrão só leitura (fonte PT/EN) e instruções
  do administrador; regras do juiz (checagens críticas, ajustar trecho, frase de contexto,
  desconto por checagem). Opção "Linha do tempo em JSON" para comparar com o formato antigo.
- Cartão de medição (GET judge/report, liberado no proxy): chamadas e tokens por hora por
  papel, aprovação, descartes do juiz e concordância juiz x dono.
- Modal do corte: veredito do juiz de contexto em português (decisão, o que um espectador
  frio entende, frase de contexto, checagens) e "Sua avaliação" (bom/ruim/sem contexto);
  botão "Sem contexto" ao rejeitar; lista marca "descartado pelo juiz".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:38:34 -03:00
MateuusandClaude Opus 5.5 cb8450399d Clipador: Equipe de IA (papéis com IA própria), juiz de contexto e linha do tempo JSON
- roles.py: varredura, analista, editor e juiz, cada um com provedor, modelo, raciocínio
  (Codex), liga/desliga (o editor não desliga) e instruções do administrador somadas às
  padrão; gravado em settings `judge.roles`, com migração automática da configuração antiga
  (provedor/modelo único vira o de todos; o modelo do analista é respeitado). A reserva vale
  por papel.
- Juiz de contexto (só texto): vê só o que vai no corte (+20 s antes/15 s depois marcados
  out=1), escreve o que um espectador frio entende e responde sim/não; context_judge.decide
  decide pelo código: aprova, ajusta o trecho e confere uma vez de novo, frase de contexto
  na tela (vira o texto de abertura do projeto) ou descarta com motivo em português
  (forçável). Corte manual só recebe aviso.
- timeline.py: linha do tempo JSON curta (fala com falante, chat, rosto, volume e a frase
  de tela que a varredura/analista escrevem ao ver os quadros, em scene_notes); mosaico 4x2
  (media.mosaic) no lugar dos quadros soltos; perfil do jogo enxuto. O formato antigo fica
  atrás da opção timelineJson.
- Medição (F0): ai_calls por chamada (papel, IA, tamanho do prompt/imagens, tokens quando a
  CLI informa: codex --json, claude e gemini), avaliação do dono (owner_label: bom/ruim/sem
  contexto) e GET /v1/judge/report (taxa de aprovação, decisões do juiz, concordância).
- Banco v17 (v16 fica reservada às expressões, como marcador sem efeito).
- Testes: test_roles.py e test_context_judge.py; os testes bloqueiam qualquer CLI de IA real.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:36:25 -03:00
Mateuus 393d1f74b2 Merge branch 'clipper/expressions' into clipper/integ 2026-11-18 04:19:30 -03:00
MateuusandClaude Opus 5.5 44f78bd483 Clipador: mapa de expressões do streamer (expressões novas, pose e corpo)
- Expressões novas dos blendshapes que já vinham do MediaPipe: gargalhada, alegria
  (no mapa), medo, espanto, nojo, tristeza, tensão e bocejo (que deixou de contar
  como grito); raiva também por olhos semicerrados + lábios apertados. Canais novos
  opcionais na série (brow_inner, mouth_frown, squint, press, stretch, upper_lip,
  pucker), z relativo ao neutro do próprio streamer só com os segundos que têm o campo.
- Pose da cabeça pela matriz de transformação facial (yaw/pitch/roll) e balanço/aceno
  por zigue-zague; YuNet nos quadros sem rosto dá a caixa da cabeça (streamer de perfil).
- Corpo mesmo sem expressão: balançando, acenando, agitado, chegou perto e saiu do
  quadro, sem contar rastreio perdido como movimento.
- API /face com expr/body por segundo e lista do corpo; linha do juiz com o corpo;
  painel com os rótulos novos e o "Mapa de expressões" no modal do corte.
- Calibrado nas sessões 7, 8, 11 e 15 (doc/clipador/EXPRESSOES.md); intensidade dos
  picos inalterada (canais novos só rotulam). Testes em tests/test_expressions.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:16:25 -03:00
MateuusandClaude Opus 5.5 5be6c09c16 Doc: pesquisa e proposta do juiz de contexto e da linha do tempo em JSON (doc/clipador/PESQUISA-JUIZ.md)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:05:31 -03:00
MateuusandClaude Opus 5.5 1ea8445808 Painel: libera POST clips/id/translate e GET sessions/id/speakers no proxy do Clipador
O botão "Traduzir a fala" recebia 404 (rota não liberada) e a rota de vozes da sessão é nova.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:00:29 -03:00
MateuusandClaude Opus 5.5 439e111052 Integração: falantes + dublagem + vídeo final
- editor_api: importa dub e speakers juntos.
- voice_chunks (falantes) vira a migração v15, depois da v14 do vídeo final (antes era criada fora das migrações).
- dub.voice_for: qualquer voz que não é o streamer (other1, other2…) usa a segunda voz da dublagem.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:59:44 -03:00
MateuusandClaude Opus 5.5 377536f778 Clipador: quem fala cada palavra (streamer × outra pessoa) e legenda em duas linhas
A fala de colegas no Discord e de outros jogadores saía na legenda como se fosse do
streamer. Agora cada palavra tem falante:

- voz: cada trecho de fala vira uma impressão de voz (WeSpeaker ResNet34-LM, ONNX,
  pesos CC-BY-4.0) na análise do bloco (~0,2 s de CPU por bloco); as vozes da sessão
  são agrupadas sob demanda (0,05 s) e a do streamer é a que mexe a boca na webcam
  (YuNet, nova série `mouth` no rastreio) ou a mais alta no áudio. Sem prova, tudo
  continua como do streamer.
- dados: `scoring.Word.speaker`; `words_json` aceita o 4º elemento; tabela
  `voice_chunks` (CREATE TABLE IF NOT EXISTS, fora da lista de migrações).
- legenda: streamer na posição normal e outra pessoa logo abaixo, em outra cor
  (`caption.otherColor`/`otherSize`); blocos nunca misturam falantes; os dois juntos
  = duas linhas; gancho desvia as duas; vertical e horizontal.
- tradução com `speaker` por linha; juízes recebem a transcrição marcada.
- painel: cor da outra pessoa na configuração, falante na transcrição do editor
  (com correção manual), prévia em duas linhas e "O que falam" no modal.
- doc/clipador/FALANTES.md com abordagem, licenças e qualidade medida na sessão 15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:57:00 -03:00
MateuusandClaude Opus 5.5 e96e180da5 Integração: vídeo final ao aprovar + dublagem em português
Conflito em editor_api.render_clip_edit (as duas frentes mexeram na chamada de render): passa a tradução, `dev`
e o dublador juntos. review_layers: a dublagem sai das frases traduzidas, então sem frase (fonte em português) não
houve dublagem e o vídeo de revisão já é o final.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:49:39 -03:00
Mateuus 06f463e684 Merge branch 'clipper/final' into clipper/integ 2026-11-18 03:45:49 -03:00
MateuusandClaude Opus 5.5 7a428ee5da Clipador: dublagem em português por TTS no vídeo de revisão (dev.dub)
- app/dub.py: frases traduzidas → uma fala TTS por frase no serviço de voz
  (POST /v1/synthesize, WAV), cache em disco por (voz, velocidade, texto),
  encaixe sem sincronia labial (velocidade natural, escorre até 1,5 s sem
  acumular atraso, acelera no máximo 1,2× e corta com fade só se preciso,
  nunca duas falas juntas), frase partida no meio vira uma fala só, voz
  reserva offline e faixa única do trecho nivelada pelo volume do corte.
- editor_render.render_project: o áudio original abaixa (dubDuck, rampa
  de 0,15 s) só onde há dublagem; nada muda com dev=False. Devolve resumo.
- layout: dev.dubVoice, dev.dubVoiceOther (speaker "other") e dev.dubDuck.
- editor_api: prévia e render da fila passam o dublador; translation_for
  também traduz quando só a dublagem está ligada.
- Painel: switch "Dublagem em português (teste)", vozes TTS prontas (sem
  clone) e volume do original.
- doc/clipador/DUBLAGEM.md e tests/test_dub.py (TTS falso).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:45:14 -03:00
MateuusandClaude Opus 5.5 dc0917b114 Clipador: vídeo final sem camadas de teste ao aprovar; publicação só usa o final
Pedido do dono: o vídeo da fila é de revisão (com as camadas `dev`, ex.: tradução);
ao aprovar, o serviço renderiza de novo sem elas, e só esse vai para as redes.

- db v14: clips.review_dev_json (camadas que entraram na revisão) e final_status/
  final_file/final_thumb/final_cover/final_error/final_at; backfill dos cortes antigos.
- Motor: queue_final/drop_final/render_final; fila renderiza finais primeiro com
  render_clip_edit(dev=False) em clip-<id>-final.mp4; revisão sem camada de teste
  vira o final sem render novo; prune guarda os blocos de quem ainda precisa do final.
- API: clip traz review.devLayers, final e publishFile; aprovar enfileira o final;
  desaprovar, mudar trecho, exportar, re-render e rejudge derrubam o final;
  POST /v1/clips/{id}/final (tentar de novo).
- Painel: etiqueta na lista, player Final/Revisão e estado do final no modal
  (gerando/pronto/erro com "Tentar de novo"), aviso no "Publicar"; o despachante
  relê o corte antes de enviar e espera o final (clipPublishFile), nunca a revisão.
- Testes: clipper/tests/test_final_render.py e testes do despachante no painel.
- Doc: doc/clipador/REVISAO.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:27:26 -03:00
MateuusandClaude Opus 5.5 ad36f0faf4 Cartoon: foco da cena segue a narração e personagens no barco quando há água
- focusOf ignora objeto procurado, não encontrado ou só "parecido" (não mostra pronto o que o texto nega)
- stageFocus: com chão de água e arca em cena, quem aparece fica dentro do barco
- assunto grande mais à frente (z 0,35) e maior (arca 1,35; demais 1,4)
- Noé e a Arca ep01: tomadas regeradas e narração em velocidade 1,1
- .gitignore: worktrees temporárias dos subagentes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:25:39 -03:00
MateuusandClaude Opus 5.5 54eac7cebf Clipador: grupo dev (camadas só do vídeo de revisão) e render com dev=False
Base comum para três frentes em paralelo (vídeo final ao aprovar, dublagem, falantes):
- layout: grupo `dev` {translation, dub}; `dev_flags(cfg, dev)` desliga tudo no vídeo final;
  `caption.translation` vira legado de `dev.translation`.
- editor_render.build_project_ass / render_project e editor_api.translation_for: parâmetro
  `dev` (padrão True = revisão; False = final, sem camadas de desenvolvimento).
- Painel: switch da tradução passa a gravar em `dev.translation`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:09:31 -03:00
MateuusandClaude Opus 5.5 20a9805d2a Clipador: fontes em inglês (juízes em inglês, painel em português) e monitor de uso da IA
Clipador em inglês (doc/clipador/IDIOMAS.md):
- Fonte en-US: analista, editor e varredura com prompts, glossário de chat e saída em inglês;
  a mesma resposta traz o bloco `pt` (tradução para o painel, sem chamada extra).
- Fala do corte traduzida por frase (clips.translation_json, migração v13) e
  POST /v1/clips/{id}/translate.
- caption.translation (só para desenvolver): português embaixo da legenda em inglês.
- Risada e gírias do chat em inglês na heurística (LMAO, LOL, 💀, 😭, no way, bruh...).
- Idioma do público → código do Whisper (en-US dava 422 no serviço de voz).
- Painel: bloco "Em português" no corte, análise/resumo em PT, título traduzido na lista,
  coluna "Ao vivo" mostra a gravação ativa da fonte.

IA: monitor de uso do limite (ai-usage) e 4º provedor (Antigravity CLI).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:07:09 -03:00
MateuusandClaude Opus 5.5 ed31d52df0 IA: Claude, Codex e Gemini com login, chave de API e IA reserva; Configurações em subpáginas
- Configurações → IA (/settings/ai): um cartão por IA para instalar/atualizar a CLI pelo painel, ligar,
  entrar com a conta (OAuth pela própria CLI, num terminal) ou colar a chave de API, e testar.
  Chaves cifradas com a DPAPI do Windows em data/ai/vault.bin; só vão para a CLI no ambiente da chamada.
- Gemini CLI como terceiro agente do painel (stream-json, edição automática, shell só o liberado).
- IA reserva: execução que cai por indisponibilidade (cota, 429, login, chave, rede) pausa a IA e recomeça
  a mesma tarefa na próxima pronta da ordem; migração v10 (agent_runs.fallback_of).
- Configurações viraram subpáginas (IA, Publicação, Apps das redes, Navegador, Sobre os modos), também no
  menu lateral; links antigos apontam para a subpágina certa.
- Contrato com o Clipador em doc/ia.md; skill do CenaForge atualizada até a 1.51.0.

O login gratuito do Gemini CLI para conta pessoal foi encerrado pelo Google (IneligibleTierError): para
conta pessoal, use a chave do AI Studio.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 01:51:12 -03:00
MateuusandClaude Opus 5.5 0567c7454a Clipador: subpáginas, jogos, idioma por canal e juiz com Gemini e IA reserva
- Clipador em subpáginas (Cortes, Sessões, Fontes, Jogos, Ajustes) com moldura comum, lista + diálogo
  dos cortes e submenu na barra lateral.
- Perfis de jogo (o que a IA sabe de cada jogo), parar pausa o monitor e idioma por fonte e por canal
  de publicação (migração v9: accounts.language).
- Juiz: Gemini CLI como terceiro provedor e IA reserva por chamada — se a IA escolhida cair por cota,
  login, chave ou rede, a próxima da ordem de Configurações → IA responde (com pausa da que caiu).
  Lê data/ai/settings.json e o cofre data/ai/vault.bin (DPAPI) escritos pelo painel; contrato em doc/ia.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 01:51:12 -03:00
MateuusandClaude Opus 5.5 2d8b1a582d Cartoon: mãos, membros e cenários novos; elenco de Noé e a Arca
- Mãos com formas e rotações próprias, membros articulados (limbs) e animais.
- Elementos de cenário separados (natureza, construções, interiores) e testes de lugares.
- Personagens reaproveitáveis de Noé e a Arca (Noé, esposa, Sem, Cam e Jafé) e a fonte Barlow Semi Condensed.
- História noe-e-a-arca: pauta, bíblia, roteiro do ep. 1, tomadas Cartoon e montagem.
- Montagem: narração mais corrida (tira silêncios longos) e cabeçalho com o número do vídeo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 01:51:11 -03:00
MateuusandClaude Opus 5.5 3f600c55b1 Cartoon: rig, movimento e lip sync dos personagens
- cartoon/src/rig.ts, motion.ts e lipsync.ts: esqueleto do personagem,
  curvas de movimento e sincronia labial no estilo Cartoon (Remotion)
- CharacterFigure/CharacterCard/Shot/overlays e spec atualizados
- Painel: estúdio de personagens e montagem cartoon ajustados
- Documentação em doc/cartoon/animacao.md e personagens.md; skill atualizada

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:39:12 -03:00
264 changed files with 43175 additions and 3622 deletions
+131
View File
@@ -7,6 +7,137 @@ Versão semântica da **skill** (não do projeto):
Mantido pelo subagente `cenaforge-skill-updater`. Entradas mais novas no topo.
## 1.55.0 — 18/11/2026
Clipador: detecção automática do jogo da live.
- `references/clipper.md`: banco em v17 (v16 = detecção do jogo); seção nova "Detecção do jogo da live" (pistas e pesos,
estados `user|agreed|probable|conflict|unknown`, regras de troca e de sugestão, "Detectar agora", API, painel);
`GAME_CHECK_S` 600 → 180; juiz com `screen_game_confidence`/`screen_evidence` e `Judge.detect_game`; "Testes e evidência".
- `references/gotchas.md`: 186 (jogo não detectado: serviço sem reiniciar, jogo não cadastrado, sem IA/visão, `game_id` ×
`slug`, e proxy do painel sem `game/detect`).
- `SKILL.md`: versão, `description`, linha do Clipador em "Onde mexer", faixa de itens.
- Evidência (reexecutada): suíte do Clipador exit 0 com 440 testes (15 em `test_game_detect.py`); `npx tsc --noEmit -p panel`
exit 0. Conferidos no código: `db.py` v16, rotas `PUT …/game` e `POST …/game/detect`, `session_view`, constantes de `intel.py`.
Não verificado: IA real, painel no navegador, banco real em v16. Corrigido depois: `ALLOWED` de
`panel/src/lib/clipper.ts` agora libera `sessions/<id>/game/detect` (`game(\/detect)?`).
- Sincronização com a 1.54.0 (outra sessão): versão renumerada, item de gotchas 180 → 186, banco descrito em v17.
## 1.54.0 — 18/11/2026
Clipador: vídeo de revisão × final, dublagem, falantes, expressões e Equipe de IA.
- `references/clipper-video.md` (novo): revisão × final (grupo `dev`, `dev_flags`, migração v14, `publishFile`, `POST /v1/clips/{id}/final`,
quando o final some), dublagem (`dev.dub*`, `dub.py`, cache, encaixe sem sincronia labial, tempos medidos) e falantes (WeSpeaker
ResNet34-LM CC-BY-4.0 + boca/volume, migração v15, legenda em duas linhas, `GET /v1/sessions/{id}/speakers`).
- `references/clipper-ai-team.md` (novo): papéis (`judge.roles`), juiz de contexto (7 checagens, o código decide), linha do tempo JSON +
mosaico 4×2 (`timelineJson`), medição F0 (`ai_calls`, `scene_notes`, v17, `GET /v1/judge/report`, rótulo "sem contexto"), tokens medidos.
- `references/clipper.md`: banco em v17 (v16 só citada: detecção do jogo, doc ainda fora desta branch); 4 linhas novas em "Onde mexer";
seção de expressões/pose/corpo em "Rastreio de reação" (calibração, canais novos só rotulam); `dev.translation` no lugar de
`caption.translation`; fontes em teste; bloco de evidência.
- `references/gotchas.md`: 180 (publicar só o final), 181 (proxy 404), 182 (falantes), 183 (dublagem), 184 (worktree no Windows), 185 (serviços do usuário).
- `references/panel.md`, `publishing.md`, `ai.md`, `tools.md`: ponteiros e linha do peso WeSpeaker. `SKILL.md`: versão, `description`, invariante de publicação, faixa de itens.
- Evidência: conferido no código (`db.py` v14–v17, `layout.py` `dev`/`DEFAULTS`, rotas em `main.py`, regex `ALLOWED`, `models.lock.json`,
`OPTION_DEFAULTS.timelineJson`); `onnxruntime` 1.32.0 e `mediapipe` 1.2.3 no `clipper/.venv`. Suíte do Clipador (inteira) e painel
(`tsc` + 119 testes) **informados pelo coordenador, não reexecutados**. Medidas de tempo/tokens/estabilidade vêm de `doc/clipador/`.
Não verificado: serviços reais com o código novo, UI no navegador, IA/TTS reais além dos cortes citados.
## 1.53.0 — 18/11/2026
IA: monitor de uso do limite e 4º provedor (Antigravity CLI).
- `references/ai.md`: seções "Monitor de uso e limite" (leituras sem gastar token, `overLimit`, `usage.json`, `over_limit` no
Clipador, regra de "pronta") e "Antigravity (`agy`)"; tabela "Onde mexer" com `ai-usage.ts`, `antigravityArgs`, ação `usage`.
- `references/gotchas.md`: 175 (OAuth do Gemini, AI Pro/Ultra), 176 (`/usage` no Git Bash), 177 (permissões do `agy`),
178 (handshake do `codex app-server`), 179 (IA "pronta" sem estar).
- `references/tools.md`: Antigravity CLI como candidata (1.5.10, desligada, sem tarefa real); `references/panel.md`: 4 provedores.
- `SKILL.md`: versão, `description`, linha "IA" em "Onde mexer", faixa de itens.
- Evidência: `pnpm --filter cenaforge-panel run test:panel` 117/117 (reexecutado); `agy` 1.5.10, `claude` 2.1.314,
`codex-cli` 0.169.0 (`--version`). Informado, não reexecutado: `ai.test.ts` 30, Clipador 346, leituras reais de uso, "Testar"
do Antigravity em 15 s. Não verificado: troca antecipada em tarefa real, UI no navegador, Gemini com chave.
## 1.52.0 — 18/11/2026
Clipador: fontes em inglês (vídeo em inglês, equipe vê português).
- `references/clipper.md`: banco em v13 (`clips.translation_json`); linha "Onde mexer" e seção "Fonte em inglês" (prompts `*_EN`,
bloco `pt` na mesma chamada, `translate_clip`/`translate_lines`, `caption.translation` com estilo `Trans`, `scoring.py` em
inglês, `voice_language`, como começar uma fonte gringa, painel); "Idioma" e "Testes e evidência" atualizados.
- `references/gotchas.md`: 173 (`en-US` voltava 422 no serviço de voz) e 174 (coluna "Ao vivo" com checagem velha).
- `references/panel.md`: linhas de `/clipper` e `/clipper/sources`.
- `SKILL.md`: versão, `description` (fonte em inglês), linha do Clipador, faixa de itens.
- Evidência: `pnpm test:clipper` → 346 passed (reexecutado, 101 s); conferidos no código `VOICE_LANGUAGES`, migração v13,
`caption.translation`, estilo `Trans`, `Intel.lang`, rota `translate`; corte 259 (sessão 15, Tfue) informado, não reexecutado.
Não verificado: IA real, painel no navegador, `pnpm typecheck`.
## 1.51.0 — 18/11/2026
IA: três provedores (Claude Code, Codex, Gemini CLI), login ou chave de API no cofre e IA reserva.
- `references/ai.md` (novo): onde mexer (`panel/src/lib/ai.ts`, `agents.ts`, `app/api/ai/`, `ai-settings.tsx`,
`clipper/app/ai_settings.py`, `judge.py`), regras (só o painel escreve `data/ai/`, chave só no ambiente da chamada,
quando a reserva troca), estado verificado. Contrato completo em `doc/ia.md`.
- `references/panel.md`: banco v10 (`agent_runs.fallback_of`); "Agentes e modelos" com 3 provedores, reserva e
Configurações em subpáginas (`SETTINGS_SECTIONS`).
- `references/clipper.md`: juiz com `gemini` e reserva por chamada; chave só pelo cofre do painel.
- `references/gotchas.md`: seção "IA" com 168–172 (OAuth do Gemini encerrado, `CODEX_API_KEY`, terminal de login no
Windows, custo da DPAPI, CLI fora do PATH). O 167 já era do perfil de jogo (1.50.0); numeração ajustada.
- `references/tools.md`: Gemini CLI como candidata (não instalada aqui, nunca executada); `--version` de Claude e Codex.
- `SKILL.md`: versão, `description`, esquema v10, linha "IA" em "Onde mexer", invariante da chave de API.
- Evidência (reexecutada): `claude` 2.1.314, `codex-cli` 0.169.0, `gemini` ausente; `ai.test.ts` 21/21; `pnpm test:clipper`
335 passed. Informado, não reexecutado: painel 104/104, ida e volta do cofre. Não verificado: Gemini com chave, `@arquivo`
de imagem no juiz, envelope de erro do `-o json`, UI no navegador.
## 1.50.0 — 18/11/2026
Clipador: perfis de jogo bilíngues, missões e gatilhos de fim, cadastro de jogo pelo painel, semente do GTA VI.
- `references/clipper.md`: banco em v12; seção "Perfil do jogo" reescrita (`profile` pt × `profileAi` en, aliases,
`missions`, `end_triggers`, rotas novas `POST/DELETE /v1/games`, `translate`, `PUT ?lang=`, seções novas do refine,
sementes, proxy/timeouts); linhas de "Onde mexer" e de páginas; evidência.
- `references/panel.md`: `/clipper/games` em lista + modal (`clipper-game-dialog.tsx`, `clipper-game-parts.tsx`);
ícones dos subitens da sidebar.
- `references/gotchas.md`: novo 167 (serviço sem reiniciar, `profileAi: null`, alias, missões não oficiais do GTA VI).
- `SKILL.md`: versão, `description` (perfil bilíngue, missões, cadastro de jogo) e faixa de itens do Clipador.
- Evidência: conferido em `clipper/app/main.py`, `db.py` (v12), `judge.py` (`mission_lines`), `intel.py`,
`panel/src/lib/clipper.ts` e `doc/clipador/JOGOS.md`; `pnpm test:clipper` → 335 passed (reexecutado). Não verificado:
IA real, UI no navegador, banco real em v12, `pnpm typecheck`.
## 1.49.0 — 18/11/2026
Clipador: interface em subpáginas, parar à mão pausa o monitor, idioma por fonte/sessão/canal.
- `references/clipper.md`: banco em v11; linha "Páginas `/clipper/*`" reescrita (grupo `(studio)`, provider, shell, páginas);
linha nova de pausa do monitor e idioma em "Onde mexer"; seção "Parar é parar e idioma"; evidência.
- `references/panel.md`: seção `/clipper` reescrita (tabela rota, conteúdo, arquivos; `clipper-studio.tsx` apagado,
`clipper-queue.tsx` e `clipper-sessions.tsx` reduzidos); esquema do painel v9 (`accounts.language`, `languages.ts`).
- `references/gotchas.md`: novo 166 (fonte que não volta a gravar depois de parar à mão; rotas novas exigem reiniciar o Clipador).
- `SKILL.md`: versão, `description`, linhas de página e de armadilhas.
- Evidência: conferido em `doc/clipador/REDESIGN.md`, `clipper-shell.tsx` (`CLIPPER_SECTIONS`), `clipper/app/db.py` (v11),
`main.py` (`StopIn`, `check_language`), `panel/src/lib/db.ts` (v9) e `languages.ts`; `pnpm test:clipper` → 287 passed
(reexecutado). Não verificado: páginas no navegador, banco real em v11, `pnpm typecheck` e testes do painel.
## 1.48.0 — 17/11/2026
Cartoon: acabamento de ilustração dos personagens (detalhe de rosto/corpo, acessórios, enquadramento e textura).
- `references/cartoon.md`: campos opcionais do `look` (`head`, `nose`, `lids`, `wrinkles`, `belly`, `accessories`,
`accessoryColor`); `lid` em `FaceParams`; `framing` do ator e `grain` do spec; acabamento do `CharacterFigure`;
`describeToLook` com regras de detalhe e profissões novas; `planCartoon` escolhe `framing`; campos novos no studio; medição.
- `references/gotchas.md`: novos 163 (curva da boca — registrado de fato só agora; o 1.47.0 o citava sem ele existir no
arquivo), 164 (Python grava JSON sem `encoding="utf-8"` estraga acento), 165 (sombra em elipse parece mancha).
- `SKILL.md`: versão, `description`, linha do personagem, faixa de itens do Cartoon (156, 157, 160–165). Sem crescer.
- Evidência: conferido em `character.ts`, `rig.ts`, `spec.ts`, `Shot.tsx`, `overlays.tsx`, `characters.ts`,
`montage-cartoon.ts`; `cd cartoon && npx tsx --test tests/*.test.ts` → 16 pass (reexecutado). Informados, não
reexecutados: painel 78/78, `tsc`, 4 personagens por descrição, close falando renderizado.
## 1.47.0 — 17/11/2026
Cartoon: rig de expressões, ações de movimento combináveis e fala sincronizada (ferramenta, não template).
- `references/cartoon.md`: nova seção "Rig, movimento e fala" (`rig.ts`: `FaceParams`/`BodyParams`, 20 expressões e 17 poses
como atalhos; `motion.ts`: `Action`, 19 ações, `evaluate`, `startOf`/`cue`, `validateTimeline`; `lipsync.ts`: `visemeAt`,
`emphasisAt`, `speak`); contrato do ator com `face`/`body`/`timeline` e `spec.audioEnv`; `timelineFor`/`audioEnvelope` no
plano do painel; exports `./motion` e `./rig`; prévia de movimento no `character-studio`; medições.
- `references/gotchas.md`: novo 163 (curva quadrática da boca só chega à metade do controle).
- `references/tools.md`: contagem de testes (cartoon 16, painel 10 no arquivo do Cartoon).
- `SKILL.md`: versão, `description`, linha de personagem com rig/movimento e `animacao.md`; resumo de armadilhas enxugado
(a lista longa de itens saiu: vale o `gotchas.md`).
- Evidência: conferido no código (`package.json` exports, `rig.ts`, `motion.ts`, `lipsync.ts`, `montage-cartoon.ts`);
`cd cartoon && npx tsx --test tests/*.test.ts` → 16 pass (reexecutado). Informados, não reexecutados: painel 78/78, `tsc`,
grade das 20 expressões, narração real da ilha ep01-01 e sequência de 7 s renderizada em 5,6 s.
## 1.46.0 — 17/11/2026
Cartoon por peças: lugares montados pelo texto e biblioteca de personagens reaproveitados entre histórias.
File diff suppressed because one or more lines are too long
+71
View File
@@ -0,0 +1,71 @@
# IA: provedores, login/chave, IA reserva e monitor de uso
Fonte do contrato: **`doc/ia.md`** (arquivos, ambiente de cada chamada, o que conta como indisponível, Gemini
headless). Não duplique aqui; este arquivo diz onde mexer e o que não quebrar. Sempre pela **CLI oficial**
(`claude`, `codex`, `gemini`, `agy`), nunca SDK/HTTP direto. `antigravity` é o 4º provedor (começa **desligado**).
## Onde mexer
| Mudança | Arquivo(s) | Também atualizar |
|---|---|---|
| Configurações, cofre, detecção, instalação, login, teste, `providerEnv`, `isAvailabilityError`, pausa, `readyChain`/`nextFallback` | `panel/src/lib/ai.ts` | `panel/src/lib/ai.test.ts`, `doc/ia.md` |
| Agente do painel por provedor (`geminiArgs`, `normalizeGemini`, `antigravityArgs`, `normalizeAntigravity`, `--resume`/`--conversation`, shell liberado), troca de IA ao cair | `panel/src/lib/agents.ts` (`prompts.ts`, `types.ts` para `AgentProvider`) | `ai.test.ts` (argumentos e eventos do Gemini) |
| Execução que continua outra que caiu | coluna `agent_runs.fallback_of` (migração v10 em `panel/src/lib/db.ts`), `followUpRunOf` (segue `resume_of` **e** `fallback_of`) | `publishing-db.test.ts` (conta de migrações) |
| Monitor de uso (leitura sem gastar token, `overLimit`, `usage.json`) | `panel/src/lib/ai-usage.ts` (`refreshUsage`, `ensureUsageMonitor`, `normalizeClaude`), `overLimit` em `lib/ai.ts`; `refreshUsage({maxAgeMs: 60_000})` nos 4 pontos que chamam `startRun` (`actions.ts`, `api/agent/runs`, `api/stories`, `api/characters/[id]/agent`); juiz: `AiConfig.over_limit` em `clipper/app/ai_settings.py` | `ai.test.ts`, `test_ai_fallback.py`, `doc/ia.md` |
| API | `panel/src/app/api/ai/route.ts` (`GET/PUT /api/ai`), `.../ai/[provider]/route.ts` (`POST {action: install\|login\|verify\|test\|resume\|usage}`, `PUT/DELETE` = chave) | guarda `Origin`/JSON (gotchas, item 125) |
| Tela | `panel/src/components/ai-settings.tsx` em `panel/src/app/settings/ai/page.tsx`; seletor de provedor em `agent-console.tsx` e `story-composer.tsx` | — |
| Subpáginas de Configurações | `panel/src/app/settings/{ai,publishing,apps,browser,modes}/page.tsx` + `layout.tsx`; seções em `SETTINGS_SECTIONS` de `components/settings-shell.tsx` (o menu lateral `sidebar-nav.tsx` as lê como `children`); `/settings` redireciona para `/settings/ai` | seção nova = entrada em `SETTINGS_SECTIONS` + pasta |
| Papéis do juiz (varredura/analista/editor/juiz de contexto, cada um com provedor+modelo+raciocínio+instruções; reserva por papel) | `clipper/app/roles.py`, `judge.py` (`Judge.ask(role=…)`), `panel/src/components/clipper-ai-team.tsx` — [clipper-ai-team.md](clipper-ai-team.md) | `clipper/tests/test_roles.py` |
| Juiz do Clipador (3 provedores, reserva por chamada) | `clipper/app/judge.py` (`_gemini`, `find_gemini`, `parse_gemini_output`), leitura de settings e cofre `clipper/app/ai_settings.py` (DPAPI por `ctypes`), `main.py`, `config.py`, `intel.py` | `clipper/tests/test_ai_fallback.py`, `conftest.py`, `clipper/README.md` |
## Regras
- **Só o painel escreve** `data/ai/settings.json` e `data/ai/vault.bin`; o Clipador só lê (relê por `mtime`). Cofre =
DPAPI `CurrentUser`, entropia `CenaForge.AI.vault.v1`; a chave nunca volta à tela (só "existe" + 4 últimos
caracteres). Nunca copie chave para skill, log ou prompt.
- Chave de API entra **só no ambiente da chamada** (`providerEnv`); não troque o login global da CLI.
- **Reserva:** erro de indisponibilidade (cota, 429, login, chave, rede, CLI fora, tempo) → a IA entra em pausa
(`cooldownMin`, em memória por processo) e a **mesma tarefa recomeça** na próxima IA pronta de `order`. Erro de
conteúdo (JSON/schema inválido) **não** troca. O juiz faz o mesmo por chamada.
- Gemini no agente: `-o stream-json --approval-mode auto_edit --skip-trust`, `--resume <sessão>`, shell só os comandos de
`GEMINI_ALLOWED_SHELL` via `--allowed-tools run_shell_command(...)`. No juiz: `-o json --approval-mode plan`, prompt
pelo stdin, frames copiados para pasta temporária **fora do repo** (`@arquivo` respeita o `.gitignore`).
- Status de login: `claude auth status --json` (`loggedIn`, `authMethod`, `subscriptionType`); `codex login status`
(texto, "Logged in using ChatGPT").
- Instalação: Claude pelo instalador nativo (`irm https://claude.ai/install.ps1 | iex`); Codex e Gemini por
`npm install -g`. O painel procura também em `~/.local/bin` e `%APPDATA%\npm`.
## Monitor de uso e limite
- **Leituras sem gastar token** (`ai-usage.ts`): Claude `claude -p "/usage"` (texto, US$ 0, modelo `<synthetic>`) e
`rate_limit_event` de cada execução (`normalizeClaude`); Codex `codex app-server` (`account/rateLimits/read`);
Antigravity `agy -p "/usage" --output-format stream-json`. **Gemini CLI: sem leitura**, só reativo (429).
- Renova a cada 5 min (`ensureUsageMonitor`, ligado pelo `GET /api/ai`) e antes de cada tarefa (`maxAgeMs: 60_000`).
- `overLimit` (`lib/ai.ts`): a IA bateu o limite, ou janela ainda valendo >= `fallback.usageLimitPercent` (padrão 90,
faixa 50-100). Leitura com mais de 30 min não decide. `startRun` troca para a próxima IA livre; **em retomada
(`resume`) não troca**.
- O painel escreve `data/ai/usage.json`; o Clipador lê por `AiConfig.over_limit` e põe a IA acima do limite depois das
livres em `fallback_chain`. UI: bloco "Uso do limite" por cartão, campo do limite no cartão da reserva,
`POST /api/ai/[provider] {action:"usage"}`.
- **Pronta:** IA cujo último teste falhou por indisponibilidade (login/cota) **não** é "pronta"; Gemini em modo conta só
conta como pronto depois de um teste que passou. "Testar" continua habilitado.
## Antigravity (`agy`)
- `agy.exe` em `~/.gemini/bin` (fora do PATH; `AGY_BIN` sobrescreve). Sem instalador por linha de comando
(`install.command` null; a UI mostra o site). Login conferido por `agy models`; atualizar = `agy update`.
- Agente: `agy -p <prompt> --output-format stream-json --mode accept-edits [--conversation <id>]`; shell **só** por regra
exata `command(<linha>)` via `--settings` (gotchas 177). Eventos e formatos: `doc/ia.md`, "Antigravity no painel".
- Começa desligado. **Aviso de termos:** a FAQ do Google diz que embrulhar o `agy` em programa de terceiro "não é
suportado" nos planos pessoais; a decisão de ligar é do usuário. O juiz do Clipador **não** usa antigravity.
## Estado verificado (18/11/2026)
- Nesta máquina: `claude` 2.1.314, `codex` 0.169.0, `agy` 1.5.10 (`--version` reconferido); `gemini` **não instalado**.
- `pnpm --filter cenaforge-panel run test:panel`: 117/117 (reexecutado pela skill). `ai.test.ts` 30 testes (informado).
Clipador: 346 passed (informado; reexecutado na 1.52.0).
- Leituras reais informadas: Claude 4% / 67%; Codex janela de 5 h em 100% (`rate_limit_reached`), semanal 29%;
Antigravity 12% / 5%. "Testar" do Antigravity respondeu "ok" em 15 s.
- **Não verificado:** Gemini com chave real, `@arquivo` de imagem no juiz, envelope de erro do `-o json`, a UI
`/settings/ai` no navegador, troca de IA no meio de um agente real, troca antecipada por `overLimit` em tarefa real.
Armadilhas: gotchas, itens 168-172 e 175-179.
+70 -11
View File
@@ -8,7 +8,7 @@ cena é montada **por peças** a partir do texto (parque de dia, cemitério, bun
criados uma vez, na biblioteca, e reaproveitados em várias histórias. Não crie "cena pronta" nova; crie peça ou regra.
Guias do projeto (fonte de detalhe, não duplicar aqui): `doc/cartoon/cenas.md` (camadas, receitas por situação,
composição), `doc/cartoon/personagens.md` (ficha, agente), estudo de referência `doc/estudo-estilo-cartoon-explicativo.md`.
composição), `doc/cartoon/personagens.md` (ficha, agente), `doc/cartoon/animacao.md` (expressões e movimento, guia do agente), estudo de referência `doc/estudo-estilo-cartoon-explicativo.md`.
## Contrato da cena (`cartoon/src/spec.ts`, `schemaVersion` 1; `validateSpec` recusa o resto)
@@ -22,7 +22,11 @@ composição), `doc/cartoon/personagens.md` (ficha, agente), estudo de referênc
`z` 0 = frente, 1 = fundo. 24 peças em `ELEMENTS`: tree, deadtree, pine, bush, rock, mountain, cloud, bench, lamp,
gravestone, cross, fence, house, building, car, sign, door, window, table, bed, shelf, crate, tent, fire.
Peça nova = entrada em `ELEMENTS` + desenho em `cartoon/src/places.tsx`.
- `actors`: `person` com `character {name, caption, look}`, `expression`, `pose`, `item` (objeto na mão), `flip`
- `grain` (0 desliga, padrão 0,11): textura de papel sobre a cena (`Grain` em `overlays.tsx`, feTurbulence com mix-blend overlay;
também no `CharacterCard`).
- `actors`: `person` com `character {name, caption, look}`, `expression`, `pose`, `item` (objeto na mão), `flip`,
`framing` `full|medium|close` (Shot: zoom 1/1,9/2,9 e base y = `y`/0,98/1,15; a etiqueta vai para o lado),
`face`/`body` (ajustes finos do rig), `timeline` (ações de movimento, até 40); `spec.audioEnv {fps, values}`
(campos antigos `label`/`hair`/`glasses`/`pointing` ainda valem); `crowd` (entra antes do personagem, atrás, pés em y 0,6).
## Peças (`cartoon/src/`)
@@ -46,22 +50,61 @@ personagem:** `tsx cartoon/render.ts --still --props x.json --out y.png [--frame
- **Contrato** `cartoon/src/character.ts` (`Character`, `schemaVersion` 1): `id`, `name`, `caption`, `description`,
`kind` `cartoon|3d`, `look {build slim|average|heavy, height 0,6–1,2, skin, hair{style short|side|bun|long|curly|spiky|
bald|cap, color}, beard none|stubble|mustache|full|goatee, glasses none|round|square|sun, brows thin|thick,
top{shirt|jacket|hoodie|dress|uniform, color, accent}, bottom pants|shorts|skirt, shoes}`. `EXPRESSIONS`: neutral, happy,
sad, worried, angry, surprised, scared. `POSES`: stand, point, wave, hold, arms_up, shrug, think. `validateLook`.
- **Desenho** `CharacterFigure.tsx`: SVG puro (sem Remotion), `viewBox` 200×440, pés em (100,440); `t` anima respirar,
piscar e acenar. O painel importa o mesmo componente (prévia ao vivo): dependência `"cenaforge-cartoon": "workspace:*"` em
`panel/package.json`, `transpilePackages` em `panel/next.config.ts`, `exports` do pacote `./character`, `./figure`, `./spec`.
top{shirt|jacket|hoodie|dress|uniform, color, accent}, bottom pants|shorts|skirt, shoes}`. `EXPRESSIONS`/`POSES`
vêm do rig (reexportados). `validateLook`.
**Acabamento (17/11/2026), campos OPCIONAIS do `look`:** `head` (`HEAD_SHAPES` round|oval|square|wide), `nose` (`NOSES`
button|curve|round|long|wide), `lids` (0–0,8, pálpebra de base), `wrinkles` (0–1), `belly` (bool), `accessories`
(`ACCESSORIES`: towel, whistle, tie, vest, helmet, watch, badge, apron, scarf, headset, chain) e `accessoryColor`.
- **Desenho** `CharacterFigure.tsx`: SVG puro (sem Remotion), `viewBox` 200×440, pés em (100,440), escrito sobre o rig (seção
"Rig, movimento e fala"). O painel importa o mesmo componente (prévia ao vivo): dependência `"cenaforge-cartoon": "workspace:*"` em
`panel/package.json`, `transpilePackages` em `panel/next.config.ts`, `exports` do pacote `./character`, `./figure`, `./spec`, `./motion`, `./rig`.
- **Arquivos:** `assets/characters/<id>/character.json`; elenco da história `stories/<id>/cast.json` (`{"cast":[ids]}`).
- **Painel** `panel/src/lib/characters.ts`: `listCharacters`/`getCharacter`/`saveCharacter`/`deleteCharacter` (não apaga
quem está em elenco), `describeToLook` (descrição pt-BR → `look` + `caption` por regras: idade, gênero, criança,
profissão → uniforme/cor, cabelo, barba, óculos, corpo, cor de roupa), `getCast`/`setCast`. Rotas: `GET/POST
profissão → uniforme/cor, cabelo, barba, óculos, corpo, cor de roupa; **e o acabamento**: `nose`, `lids`, `wrinkles`,
`head`, `belly` e `accessories` por idade, "barrigudo", "narigudo", "cansado" e profissão — técnico: apito + relógio;
obra: capacete + colete laranja; porteiro: crachá; merendeira: avental; roupeiro: toalha; empresário: gravata + relógio;
`PROFESSIONS` inclui técnico, porteiro, merendeira, roupeiro, operário, empresário), `getCast`/`setCast`. Rotas: `GET/POST
/api/characters`, `GET/PUT/DELETE /api/characters/[id]`, `POST /api/characters/[id]/agent`, `GET/PUT
/api/stories/[storyId]/cast`. Página `/characters` (aba "Personagens"; `components/character-studio.tsx`: criar pela
descrição, prévia com expressão/pose, formulário peça por peça, "Refinar com o agente", apagar).
descrição, prévia com expressão/pose, formulário peça por peça — inclui Cabeça, Nariz, Pálpebra, Rugas, Barriga, Cor dos acessórios e chips de Acessórios —,
"Refinar com o agente", apagar).
- **Agente:** `AgentKind` `"character"` (`types.ts`; `agents.ts`: orçamento US$ 0,5, Sonnet, Claude preferido; `prompts.ts`
manda ler SÓ `doc/cartoon/personagens.md` e gravar a ficha).
- Para testar a API com acento use Python/UTF-8 (gotchas 153); o `id` sai do nome sem acento.
## Rig, movimento e fala (FERRAMENTA, não template)
Princípio do dono: expressão e movimento são **parâmetros contínuos e ações combináveis**; os presets são só atalhos.
Detalhe e exemplos: `doc/cartoon/animacao.md`.
- **`rig.ts`:** `FaceParams` (`browL/browR {y, tilt}` tilt + = ponta de dentro sobe, `eyeL/eyeR` 0–1,35, `pupil`,
`gazeX/gazeY`, `mouthOpen`, `smile` −1…1, `mouthWidth`, `mouthRound`, `lid` (pálpebra, somada ao `lids` do personagem: surpreso/medo −0,5, sono 0,6, desconfiado 0,45; os presets usam `lid` em vez de fechar o olho), `teeth`, `blush`, `sweat`, `tears`, `anger`) e
`BodyParams` (`lean`, `headTilt`, `headTurn` −1…1, `headNod`, `armL/armR/legL/legR {raise, bend}` em 2 segmentos, `crouch`).
20 `EXPRESSION_PRESETS` (neutral, smile, happy, laugh, proud, sad, cry, worried, angry, furious, surprised, scared,
shocked, suspicious, smirk, confused, disgusted, sleepy, determined, embarrassed) e 17 `POSE_PRESETS` (stand, point, wave,
hold, arms_up, celebrate, shrug, think, hands_on_hips, cross_arms, facepalm, cover_mouth, defend, reach, sit, kneel,
lean_in). `faceOf`/`bodyOf(nome, ajuste)`, `withFace`/`withBody` (aceitam `brows`/`eyes`/`arms`/`legs`), `blendFace`/`blendBody`.
- **`motion.ts`:** `Action {do, at|atP|cue, dur, cueEnd, expression/face, pose/body, to, dir, times, height, text}`; `ACTIONS`:
express, pose, walk, run, enter, exit, jump, nod, shake_head, tremble, bounce, fall, sit, stand_up, turn, talk, look, emote,
wave. `evaluate(actor, t, durationS, seed, {words, env})` → `{face, body, x, dx, dy, rot, sx, sy, flip, emote}`; `startOf`
resolve `cue` pela palavra falada (prefixo normalizado); piscar em intervalos variados, respirar e balanço sempre ligados;
`validateTimeline` (até 40 ações). `Shot.tsx` aplica `evaluate` por ator (posição/giro/escala/espelho no container).
- **`lipsync.ts`:** `visemeAt(palavras, t, env)` (forma por letra: a abre, e/i esticam, o/u arredondam, m/b/p fecham, f/v
dentes; vogal pesa 1,7 e consoante 0,8; coarticulação na 2ª metade da letra; fecha 60 ms após a palavra; `env` fecha nas
pausas), `emphasisAt` (sobrancelhas no pico), `speak(face, viseme)` (mantém cantos/sobrancelhas/olhos da expressão). `talk`
usa as palavras entre `cue` e `cueEnd`, ou `text` repartido por `dur`.
- **Desenho:** prop `state` (de `evaluate`); sem ele usa `expression`/`pose` + vida. Boca contínua com `clipPath`; olho de
riso em arco; balão de emote; mão no rosto desenhada por cima da cabeça. **Acabamento do desenho:** pálpebra recortada
(`clipPath` por olho) com borda mais escura; 5 narizes; rugas; cabeça por formato (`headPath`) com sombra de baixo e
brilho na testa; orelha com dobra; mão com polegar; tronco com sombra lateral, gola em V e zíper; barriga = elipse + curva
de volume (**só a sombra em elipse parecia mancha**); `Accessories` (capacete e fone na cabeça, relógio no pulso esquerdo).
**Armadilha:** a curva quadrática só chega à
METADE do controle, então os controles da boca ficam no dobro da abertura.
- **Painel:** `character-studio.tsx` lista as 20 expressões e 17 poses em pt-BR e tem "Movimento (prévia)" (`MovePreview`,
loop de 2,6 s). `CharacterCard` aceita framing `"face"` (recorte do rosto). Agente `character` lê `animacao.md` se o
pedido falar de expressão/movimento.
## Plano no painel (`panel/src/lib/montage-cartoon.ts`, sem banco)
- Tipos vêm de `"cenaforge-cartoon/spec"` (não há mais espelho). `planCartoon(shot, ctx, variant)` com
@@ -71,6 +114,8 @@ personagem:** `tsx cartoon/render.ts --still --props x.json --out y.png [--frame
paleta/luz própria). Sem lugar reconhecido cai nas cenas antigas.
- **Personagem:** `expressionOf`/`poseOf` pelo texto; quem é citado pelo nome entra com a aparência da biblioteca; com 1
personagem só, ele aparece nos trechos pares ou quando o texto diz "ele/ela"; objeto pequeno vai para a mão (`item`).
- **Enquadramento do personagem** (`framing`): `close` quando ele fala sozinho (há `talk`, 1 personagem); `medium` sozinho
sem objetos nem multidão; `full` no resto.
- Ícones por palavra-chave; "pessoas/vizinhos" vira multidão; "nunca/não" + perigo risca o objeto; sons viram
onomatopeia (motor só com gerador/motor/moto/carro perto; barulho genérico = "Crec"); texto na tela numérico vira `big`,
senão etiqueta; `variant` troca arranjo e seed.
@@ -85,13 +130,27 @@ personagem:** `tsx cartoon/render.ts --still --props x.json --out y.png [--frame
geração); "Gerar de novo" troca `cartoonVariant`; `hudFor` = 2 primeiras palavras do título + "Ep. N".
- **UI** (`montage-editor.tsx`, recebe `storyId`): opção de estilo, bloco `CartoonSetup` (paleta da série + elenco por chips,
só no estilo Cartoon), botão "Cartoon" no trecho, `CartoonPreview`.
- **Testes:** `panel/src/lib/montage-cartoon.test.ts` (9).
- **Movimento pelo texto:** `timelineFor(texto, x)` (`EMOTIONS` por palavra → `express` com `cue`; `MOVES` por verbo → ações;
`quoteOf`: fala entre aspas/travessão → `talk` com `cue`/`cueEnd`; começa `neutral` se houver `express`).
`audioEnvelope(file)` (FFmpeg mono 8 kHz, RMS por quadro normalizado pelo p95; ~199 quadros para 6,6 s) →
`cartoonSpec(scene, dur, words, env)`; `montage.ts` passa o env.
- **Testes:** `panel/src/lib/montage-cartoon.test.ts` (10).
## Medido (17/11/2026)
Mesmo personagem em parque (`day`), cemitério (`dusk` + fog + `vignette`) e bunker (`sepia` + `spot` + indoor): 3 trechos de
4 s em ~2,6–2,8 s cada. Plano com elenco "Marta" → parque de dia (acenando) e cemitério (com medo, "Crec") renderizados.
Testes: painel 77/77, cartoon 5/5; `tsc` ok nos dois (informados pelo dono; cartoon 5/5 reexecutado na skill).
Testes (antes do rig): painel 77/77, cartoon 5/5.
Rig/movimento (17/11/2026, informado pelo dono): grade das 20 expressões conferida de perto; personagem falando narração
real (ilha ep01-01) com `worried` mantida e "não" balançando a cabeça na palavra; sequência enter→jump→sit→stand_up→wave→
scared+"!"→tremble→fall de 7 s renderizada em 5,6 s. Testes: painel 78/78 e `tsc` ok (informados); cartoon 16/16
(`tests/motion.test.ts` 11 novos) reexecutado na skill. Renders não reexecutados.
Acabamento de ilustração (17/11/2026, informado pelo dono; referência: reel de série de cartoon, cujos personagens são
ilustrações paradas com textura, só a câmera desliza — o rig mantém a animação): 4 personagens criados só pela descrição
(porteiro 64, técnico barrigudo 52, mestre de obra 38, merendeira 70) saíram com os detalhes certos; close falando
renderizado. Testes: cartoon 16/16 reexecutado na skill; painel 78/78 e `tsc` informados. Renders não reexecutados.
## Ainda não existe (próximo passo)
@@ -0,0 +1,74 @@
# Clipador — Equipe de IA: papéis, juiz de contexto, linha do tempo JSON e medição (18/11/2026)
Fontes do contrato: `doc/clipador/EQUIPE-IA.md` (o que foi feito, F0 + F1) e `doc/clipador/PESQUISA-JUIZ.md` (pesquisa; F2
OCR do HUD/YAMNet e F3 VLM local **não** entraram — são só candidatas). Visão geral: [clipper.md](clipper.md); provedores e
reserva: [ai.md](ai.md). Migração v17 (`ai_calls`, `scene_notes`, `clips.owner_label/owner_note`).
## Papéis (`clipper/app/roles.py`, `settings` chave `judge.roles`)
| `id` | Faz | Imagem | Desligável |
|---|---|---|---|
| `scan` (varredura) | assiste por janelas, propõe momentos, descreve os quadros (`lines`) | mosaico 4×2 (padrão), soltos ou nenhuma | sim (`scanEnabled`) |
| `analyst` | diz O QUE aconteceu no candidato | idem | sim (o editor passa a receber imagens) |
| `editor` | decide corte, trecho, título, legenda, hashtags | só se o analista falhou/está off | **não** |
| `judge` | só texto: o corte faz sentido para quem nunca viu a live? | nunca | sim |
- Cada papel: `enabled`, `provider`, `model` (`""` = padrão do provedor), `effort` (só Codex; `""` = low; juiz começa em
`medium`), `extra` = **instruções do administrador** (≤ 2.000 caracteres, entram DEPOIS das padrão, que ficam no código e o
painel mostra só para leitura: `GET /v1/judge` → `roleDefaults.<papel>.pt|en`). Juiz também: `critical`
(`setup`,`payoff`,`standalone`), `allowFix`, `allowContextLine`, `penalty` (0,5). Validação: `roles.normalize_roles`.
- Banco sem `judge.roles` migra sozinho (o provedor/modelo único vira o de todos; `judge_analyst_model` fica no analista).
`judge_provider = "off"` continua = equipe inteira desligada. `PUT /v1/judge` sem `roles` (painel antigo) vale para todos.
Reserva por papel: `fallback_chain(primary)` começa na IA do papel. Tradução, perfil do jogo e câmera usam a IA do **editor**.
## Juiz de contexto (`context_judge.py`, `judge.check_context`)
Roda depois que o editor MANTEVE (nota ≥ mínima). Vê só o que vai no corte + 20 s antes/15 s depois marcados `out=1`, título,
legenda, abertura, `what_happened` e linha do jogo. Escreve `viewer_summary` e responde 7 checagens: `setup`, `payoff`,
`standalone` (críticas) · `who_what`, `intelligible`, `faithful`, `strong_open`. **O código decide** (`context_judge.decide`):
1. crítica falha + `fix` (e `allowFix`) → recalcula com `fit_window`; mudou ≥ 1 s = **ajusta** e confere **uma** vez; falhou = descarta;
2. crítica falha sem ajuste → **descarta** com motivo em português;
3. `standalone`/`who_what` falhos + `context_line` curta (≤ 10 palavras, ≤ 60 caracteres) → aprova e a frase vira o texto de abertura;
4. não críticas falhas tiram `penalty` da nota; abaixo da mínima → descarta;
5. corte manual: só **avisa** (`decision: "warn"`); falha da IA do juiz: vale o editor (`context: {error}`).
Gravado em `judge_json.context`; descartado pelo juiz = `status = discarded` + `judge_json.discardedBy = "context"` (aparece em
"Descartados"; **Forçar render** funciona). Fonte em inglês: `CONTEXT_SCHEMA_EN` com bloco `pt`. Fora do F1: 2ª opinião
com outro provedor, few-shot do dono, "testar nos últimos 10 cortes".
## Linha do tempo JSON e mosaico (`timeline.py`, `media.mosaic`)
- JSON Lines com chaves curtas: `t,d` · `v` (o que está na tela, ≤ 12 palavras; vem de `lines` da varredura/analista e fica em
`scene_notes`) · `sp` (fala literal ≤ 25 palavras; `[other1]` = outra pessoa) · `face` (rótulo de `reaction.label` com
intensidade ≥ 3) · `lvl` (só se ≥ 6 ou ≤ 1) · `chat`. Entrada nova a cada pausa > 1,2 s (se a atual tem ≥ 4 s), troca de
falante ou 8 s. Orçamento de caracteres por papel (analista 9.000, editor 7.000, juiz 6.000, varredura 9.000): passou, a
fala encurta (25 → 12 → 6 palavras). Perfil do jogo enxuto (`judge.lean_profile`).
- Imagens: 8 quadros de 384×216 numa grade 4×2 = 1 imagem 1536×432; falhou = quadros soltos.
- Opção **`timelineJson`** (`PUT /v1/judge`, padrão ligada): desligada = formato antigo (transcrição + chat + quadros de
768 px). Cada chamada grava o modo em `ai_calls.mode` (`timeline+mosaic`, `legacy+frames`…) — é como se compara.
- **Medido** (corte 291, sessão 15, tfue, IA falsa que guarda o prompt; fórmulas de imagem da pesquisa): analista 5.638 →
3.104 tokens (−45 %), editor 2.795 → 2.250 (−20 %), varredura 5.330 → 3.311 (−38 %), juiz novo ≈ 1.420. Por hora (tfue):
≈ 317 mil → ≈ 224 mil **com** o juiz (−29 %). **Uma** chamada real do juiz (Codex `gpt-6-luna`, esforço médio): 9.624 de
entrada, 1.400 de saída, 27 s ⇒ o **fixo da CLI do Codex ≈ 8 mil tokens por chamada** é o maior item e o próximo alvo
(gotchas, item 136; [token-economy.md](token-economy.md)).
## Medição (F0)
- `ai_calls` (v17): por tentativa — `role`, `purpose`, `provider`, `model`, `ok/error`, `ms`, tamanhos de prompt/imagem,
`tokens_in/out/cached` (quando a CLI informa: `codex exec --json`, `claude --output-format json`, `gemini -o json`),
`session_id`, `clip_id`, `mode`. O `codex exec` agora roda com `--json` (a resposta continua em `-o`).
- Avaliação do dono: `clips.owner_label` (`good|bad|no_context`) + `owner_note`. `PATCH /v1/clips/{id}` com
`{"label": "no_context"}` (vale para qualquer corte, não muda o estado) ou `{"status": "rejected", "label": "no_context"}`
(botão **Sem contexto** no modal). Sem rótulo: aprovado/publicado = bom, rejeitado = ruim.
- `GET /v1/judge/report?days=7` (ou `?session=N`): chamadas por papel × IA × modo, tokens por hora, cortes, juiz
(aprovou/ajustou/descartou/avisou/erro), concordância e κ de Cohen. Painel: Ajustes → Juiz → Medição. Rota na regex
`ALLOWED` do painel (`judge(\/report)?`).
## Onde está cada coisa
`roles.py` (papéis, validação, migração) · `judge.py` (`Judge.ask(role=…)`, `check_context`, `build_*_prompt`, `lean_profile`,
`codex_usage`/`claude_usage`/`gemini_usage`, `scope`) · `context_judge.py` · `timeline.py` · `worker.py` (`judge_clip`:
analista → editor → juiz; `_context_check`; `record_ai_call`) · `intel.py` (`visual`, varredura, `timelineJson`) · `report.py`.
Painel: `clipper-ai-team.tsx` (cartões e medição), `clipper-judge.tsx`, `clipper-clip-parts.tsx` (`ContextVerdict`,
`OwnerLabelControl`). Testes: `test_roles.py`, `test_context_judge.py`; `conftest._no_real_ai_cli` bloqueia qualquer CLI real.
@@ -0,0 +1,92 @@
# Clipador — vídeo de revisão × final, dublagem e falantes (18/11/2026)
Fontes do contrato (leia antes de mexer, não duplique aqui): `doc/clipador/REVISAO.md`, `DUBLAGEM.md`, `FALANTES.md`.
Visão geral do serviço: [clipper.md](clipper.md). Só vale depois de reiniciar o Clipador (gotchas, item 144).
## Revisão × final (`doc/clipador/REVISAO.md`, migração v14)
Regra do dono: o vídeo que a equipe aprova tem camadas **só de desenvolvimento**; ao aprovar, o Clipador renderiza de novo
**sem elas** e só esse vai para as redes.
```
fila de render ─► clip-<id>.mp4 REVISÃO (dev=True) ─► Aprovar ─► clip-<id>-final.mp4 (+ -final.jpg, -final-cover.jpg) (dev=False)
review_dev_json = [] ? ─► o de revisão JÁ É o final (sem render novo; final.reused = true)
```
- **Camadas `dev`** (grupo `dev` da configuração do corte, `layout.py`): `translation` (português embaixo da legenda) e
`dub` (dublagem). `layout.dev_flags(cfg, dev=False)` desliga todas. `caption.translation` é legado: conta como
`dev.translation`.
- Render da fila = `worker._render_clip` → `editor_api.render_clip_edit(..., dev=True)`; grava `clips.review_dev_json`
(camadas que entraram de fato, `editor_api.review_layers`). Final: `Engine.render_pending` (finais primeiro, até 3 por
volta), mesmo projeto de edição, `dev=False`, não grava `review_dev_json`.
- Banco v14: `clips.review_dev_json` (`[]` = nenhuma; NULL = desconhecido), `final_status` (`pending|rendering|ready|error`;
NULL = sem final), `final_file/thumb/cover/error/at`. Falha no final = `error` + `final_error`; o corte segue aprovado e
nada é publicado. Serviço caído no meio: `rendering` volta a `pending` na subida.
- **O final some** (`drop_final`) ao: desfazer aprovação/rejeitar; mudar `startS/endS` de aprovado; `POST /export`,
`/render`, `/rejudge`; qualquer render de revisão novo. Desaprovar durante o render do final descarta o resultado.
`clip_delete` apaga `clip-<id>-*` e recusa enquanto o final renderiza.
- API: cada corte traz `review: {devLayers}`, `final: {status,file,thumb,cover,error,at,reused} | null` e `publishFile`
(= `final.file` se `approved|published` com final `ready`; senão `null`). `file`/`thumb` continuam os de revisão.
`POST /v1/clips/{id}/final` (re)gera ("Tentar de novo"; 409 se não aprovado). Rota na regex `ALLOWED` e em `METHODS`
(`panel/src/lib/clipper.ts`).
- **Publicação (painel):** `clipPublishFile(clip)` em `panel/src/lib/publishing-rules.ts` devolve `publishFile` ou o motivo
de esperar; **nunca** `file` quando o Clipador manda o campo (Clipador antigo, sem `publishFile`, segue com `file`).
`sendDue` (`publishing.ts`) relê o corte (`clipFinalForJob`): sem final pronto o job espera ("Esperando o vídeo final…");
com final, troca `file` (e a capa) e envia. Capa: a do final primeiro. Regras gerais: [publishing.md](publishing.md).
- `prune` (`CLIPPER_KEEP_HOURS`) guarda o trecho de quem ainda vai precisar do final (aprovado com final pendente/erro;
pronto com camada de teste ou desconhecida). Corte sem camada de teste não segura blocos.
- Painel: etiqueta `revisão · teste` / `gerando final` / `final` / `final com erro` na lista; modal com player
**Final / Revisão**, "Tentar de novo" e "Gerar vídeo final"; aviso no diálogo Publicar. Teste:
`clipper/tests/test_final_render.py`, `publishing-rules.test.ts`, `publishing-db.test.ts`.
- Sem tradução (fonte em português) não há dublagem nem tradução: o de revisão já é o final.
## Dublagem em português (`dub.py`, `doc/clipador/DUBLAGEM.md`)
Para fonte em inglês, só no vídeo de revisão, para a equipe entender o contexto. **Sem sincronia labial** (pedido do dono).
| Chave (`dev.*`) | Padrão | O quê |
|---|---|---|
| `dub` | `false` | liga a dublagem no vídeo de revisão (aba Legenda → "Dublagem em português (teste)") |
| `dubVoice` | `pt-br-antonio` | voz do streamer (Edge, online) |
| `dubVoiceOther` | `kokoro-pm-alex` | voz das falas `speaker: "other…"` (Kokoro, offline) |
| `dubDuck` | `0.25` | volume do áudio original enquanto a dublagem toca (0–1) |
- **Só vozes TTS prontas**; nunca clonar a voz do streamer (terceiro sem consentimento); o painel não lista clonadas.
- Frases de `clips.translation_json` → tempo de saída → `POST /v1/synthesize` do serviço de voz (`format: "wav"`,
`speed: 1.05`; voz que falha cai em `pt-br-faber`). Cache `data/clipper/dub/` por (voz, velocidade, texto), −16 LUFS,
48 kHz mono, 30 dias sem uso apaga. Encaixe `fit`: fala em velocidade natural, pode escorrer até 1,5 s sobre a próxima
frase (sem acumular); só então acelera até 1,2× e, se ainda não couber, corta com fade. Original abaixa para `dubDuck`
(rampa 0,15 s) só onde há dublagem; dublagem 6 dB acima do volume médio do corte (−20…+3 dB).
- Prévia do editor e render da fila usam o mesmo caminho (`dub.for_engine`). Serviço de voz fora = sai sem dublagem.
- **Medido** (corte 259 do tfue, 54,5 s, 25 frases, NVENC, informado em `DUBLAGEM.md`): sem dublagem 5,8 s; 1ª vez
+29 a +41 s (~1,6 s/frase, 3 em paralelo; 6 não ajudam); cache pronto +0,3 s; prévia de 5 s com cache 1,2 s. Conversa
densa: o português fica bem mais longo (9 das 25 falas terminaram cortadas com fade). Teste: `test_dub.py` (TTS falso).
## Quem fala (`speakers.py`, `voiceprint.py`, `doc/clipador/FALANTES.md`, migração v15)
O áudio da live é um canal só: streamer, colegas no Discord e voz do jogo misturados. **As outras vozes NÃO estão na
câmera**; a webcam só ajuda a confirmar qual voz é o streamer.
- **Impressão de voz:** WeSpeaker ResNet34-LM (`models.lock.json` id `wespeaker_r34`, pesos **CC-BY-4.0**, atribuição
"WeSpeaker, wenet-e2e", 26,5 MB, sha256 no lock) no `onnxruntime` (sem PyTorch; fbank reimplementado em numpy). Nada de
pyannote/SpeechBrain/NeMo/Resemblyzer (pedem PyTorch). 3D-Speaker CAM++ ficou fora: licença dos pesos não conferida.
- Etapas: `speakers.index_block` (logo após o Whisper, 0,19 s de CPU por bloco de 30 s) → `face.MouthMeter` (YuNet, boca na
webcam, +0,5 s por bloco) → `speakers.build_model` sob demanda (0,05 s em 72 min; refeito na leitura, o rótulo melhora
sozinho com a live). Tabela `voice_chunks (session_id, idx, data_json, updated_at)` = **migração v15** (~0,6 MB/h).
- Regras: trechos ≤ 3 s, fecham em `. ? !`; voz = grupo com ≥ 15 s de fala (cosseno ≥ 0,5). Streamer = a voz que bate com a
boca (t de Welch ≥ 3) **e/ou** a mais forte (≥ 3 dB acima da 2ª). **Discordam ou nenhuma decide → ninguém vira
"outro"** (tudo do streamer, como antes). Trecho só vira `otherN` com folga (cosseno ≥ 0,30 e ≥ 0,10 acima do streamer).
- Dados: `scoring.Word.speaker` (`""`/`"streamer"` ou `"other1"…`); `segments.words_json` aceita o 4º elemento; o projeto do
editor ganha `sp` por palavra (projeto antigo sem `sp` sai igual); `translation_json` por linha tem `speaker` e frases
nunca misturam falantes (tradução antiga sem `speaker` é refeita). `GET /v1/sessions/{id}/speakers` mostra as vozes e
o porquê. Opção `speakers` (`intel.opts`, padrão ligada) desliga tudo.
- **Legenda em duas linhas:** streamer na posição normal; outra pessoa logo abaixo (`caption.otherColor` `#5CE1FF`,
`caption.otherSize` vazio = 85 % de `size`); no horizontal a linha do streamer sobe. Estilos `CaptionOther`/`KaraokeOther`
só entram no ASS quando há outra pessoa: corte só com o streamer sai byte a byte igual (teste dourado do vertical).
Editor: botão **Outra pessoa / É o streamer** corrige palavras selecionadas.
- **Juízes:** `judge._transcript` marca `[Tfue]`/`[other1]` e manda "Never attribute to Tfue what someone else said".
- **Medido** (sessão 15, tfue, 144 blocos, só leitura; em `FALANTES.md`): 3 vozes; volume do streamer +7,5 dB sobre os
colegas; boca sozinha **não** resolve (webcam de perfil, AUC 0,55–0,64), quem decide é o volume; estabilidade 84 % aos
5 min, 98 % aos 10, 99 % aos 40. Conferência visual às cegas fraca (rosto de 45 px). Sem gabarito de áudio.
- Limites: troca de falante sem pausa nem pontuação fica com um rótulo; primeiros minutos (< 15 s de fala por voz) sem
atribuição; vozes de NPC também viram "outra pessoa"; modelo indisponível = blocos sem impressão (não refeitos).
+205 -24
View File
@@ -12,7 +12,7 @@ renderiza cortes verticais (1080×1920, padrão) ou horizontais (1920×1080, You
| O quê | Onde |
|---|---|
| Banco do Clipador | `data/clipper/clipper.db` (`PRAGMA user_version` 10, `SCHEMA` em `clipper/app/db.py`: v1 tabelas, v2 `settings`, v3 jogo/varredura/emotes/configuração do corte — colunas novas em `sessions`, `channels.settings_json`, `chat.emotes`, `clips.learned`, tabelas `games` e `emotes`; v4 `edits` (`clip_id`, `project_json`, `rev`, `cover`, `exported_at`, `created_at`, `updated_at`); v5 `face_track`; v6 `games.notes_json`/`games.edited_at`; v7 `edits.origin` (`ai`/`user`) + `edits.ai_project_json`; v8 `clips.aspect` (`vertical`/`horizontal`, padrão `vertical`, gravado no render); v9 `sessions.capture_json` (o que a captura gravou de fato; sessões antigas `NULL`); v10 tabela `deleted_clips` (marca do corte apagado, `ON DELETE CASCADE` com a sessão)). Migra ao subir o serviço. **Nunca altere uma migração já aplicada** (o banco real estava em v4 quando a v7 nasceu): coluna nova = `ALTER` numa versão nova |
| Banco do Clipador | `data/clipper/clipper.db` (`PRAGMA user_version` 17, `SCHEMA` em `clipper/app/db.py`: v1 tabelas, v2 `settings`, v3 jogo/varredura/emotes/configuração do corte — colunas novas em `sessions`, `channels.settings_json`, `chat.emotes`, `clips.learned`, tabelas `games` e `emotes`; v4 `edits` (`clip_id`, `project_json`, `rev`, `cover`, `exported_at`, `created_at`, `updated_at`); v5 `face_track`; v6 `games.notes_json`/`games.edited_at`; v7 `edits.origin` (`ai`/`user`) + `edits.ai_project_json`; v8 `clips.aspect` (`vertical`/`horizontal`, padrão `vertical`, gravado no render); v9 `sessions.capture_json` (o que a captura gravou de fato; sessões antigas `NULL`); v10 tabela `deleted_clips` (marca do corte apagado, `ON DELETE CASCADE` com a sessão); v11 `channels.monitor_paused_at`/`monitor_paused_session`/`language` e `sessions.language`, padrão `''` = `CLIPPER_LANGUAGE`; v12 `games.profile_ai_json` (perfil em inglês), `translated_at`, `aliases_json`; v13 `clips.translation_json`, fala do corte em frases + português; v14 vídeo de revisão × final (`clips.review_dev_json`, `final_status/file/thumb/cover/error/at`); v15 `voice_chunks` (impressão de voz); v16 detecção do jogo (`sessions.game_status`, `game_detect_json`; vem de outra frente, o doc `DETECCAO-JOGO.md` ainda não está nesta branch); v17 `ai_calls`, `scene_notes`, `clips.owner_label/owner_note`). Detalhes de v14–v15 em [clipper-video.md](clipper-video.md), de v17 em [clipper-ai-team.md](clipper-ai-team.md). Migra ao subir o serviço. **Nunca altere uma migração já aplicada** (o banco real estava em v4 quando a v7 nasceu): coluna nova = `ALTER` numa versão nova |
| Blocos gravados (`.ts` de 30 s + `segments.csv`) e frames | `data/clipper/sessions/<id>/` (frames em `frames/`) |
| Pesos do rastreio de reação (YuNet, MediaPipe, OpenSeeFace) | `data/clipper/models/`, fixados (URL imutável + sha256) em `clipper/models.lock.json` |
| Cortes prontos | `output/clipper/<sessão>/clip-<id>.mp4` + `clip-<id>.jpg` |
@@ -29,13 +29,21 @@ renderiza cortes verticais (1080×1920, padrão) ou horizontais (1920×1080, You
| Busca de quadro dentro de bloco `.ts` (`seek_args`, `grab_frame`) e emenda de resolução/codec (`uniform_segments`) | `clipper/app/media.py`; `clipper/app/editor_render.py`; `face.grab_bgr` e tamanho do quadro por bloco (`_frame_size`) em `face.py` | gotchas, itens 107–108 |
| Retomada de live (`Engine.live_check`, `keep_live`, `RESUME_DELAYS_S`, `resume_interrupted`), render que falha (`recover_orphan_renders`, `ORPHAN_RENDER_S` 300, `MAX_RENDER_ATTEMPTS` 3), cortes duplicados (`SAME_PEAK_S` 10, `SAME_MOMENT_OVERLAP` 0,6, `KEPT_STATUSES`/`VETO_STATUSES`, `discard_pending_duplicates`) | `clipper/app/worker.py` | `clipper/tests/test_resume.py`, `clipper/tests/test_render_and_duplicates.py` |
| Apagar cortes (`delete_clip`, `delete_many`, `select_ids`, `MAX_BATCH` 500, recusas `BUSY`/`PUBLISHED`/`CHANGED`, marca `marks`/`mark_spans`, arquivos só dentro das pastas do Clipador) | `clipper/app/clip_delete.py`; rotas em `main.py` (`ClipsDeleteIn`); marca lida em `worker.py` (veto depois do juiz) e na varredura (`intel.py`) | `clipper/tests/test_clip_delete.py`; `METHODS` em `panel/src/lib/clipper.ts`; seção "Apagar cortes" abaixo |
| Parar à mão e pausa do monitor (`Engine.stop_session(id, pause_monitor=True)`, `StopIn.pauseMonitor`), idioma por fonte/sessão (`check_language`, visões de fonte/sessão/corte com `language` resolvido; Whisper e `judge.output_language_note`) | `clipper/app/worker.py`, `main.py`, `db.py` (v11), `judge.py`; painel `ACCOUNT_LANGUAGES` em `panel/src/lib/languages.ts` | `clipper/tests/test_monitor_pause_and_language.py` (9); seção "Parar é parar e idioma" abaixo |
| Fonte em outro idioma (inglês): prompts `*_EN`, schemas com bloco `pt`, `lang_key`, `translate_lines`, `translate_clip`, `voice_language`, `phrases`, legenda `Trans` | `clipper/app/judge.py`, `intel.py` (`Intel.lang`), `worker.py`, `subtitles.py`, `scoring.py`, `layout.py`, `editor_render.py`, `editor_api.py` (`translation_for`), `main.py`; painel `clipper-client.ts`, `clipper-clip-dialog.tsx`, `clipper-clip-parts.tsx`, `clipper-clip-table.tsx`, `clipper-session-detail.tsx`, `clipper-cut-settings.tsx` | `clipper/tests/test_english_source.py` (9); seção "Fonte em inglês" abaixo |
| Vídeo de revisão × final (`dev_flags`, `render_clip_edit(dev=…)`, `review_layers`, `render_final`, `drop_final`, rota `POST /v1/clips/{id}/final`, `publishFile`) | `clipper/app/layout.py`, `editor_api.py`, `worker.py`, `main.py`; painel `panel/src/lib/publishing-rules.ts` (`clipPublishFile`), `publishing.ts` (`sendDue`), `clipper-clip-dialog.tsx`, `clipper-clip-table.tsx` | `clipper/tests/test_final_render.py`, `publishing-rules.test.ts`, `publishing-db.test.ts`; seção em [clipper-video.md](clipper-video.md) |
| Dublagem em português (`dev.dub*`, TTS, cache, encaixe, `duck`) | `clipper/app/dub.py` + `editor_render.py` (mistura) + serviço de voz `POST /v1/synthesize` | `clipper/tests/test_dub.py`; [clipper-video.md](clipper-video.md) |
| Falantes (streamer × `otherN`): impressão de voz, boca, legenda em duas linhas, `GET /v1/sessions/{id}/speakers` | `clipper/app/speakers.py`, `voiceprint.py`, `face.py` (`MouthMeter`), `subtitles.py`, `judge.py` (`_transcript`); peso `wespeaker_r34` em `clipper/models.lock.json` | `clipper/tests/test_speakers.py`; [clipper-video.md](clipper-video.md) |
| Expressões, pose da cabeça e corpo do streamer; mapa de expressões | lógica `clipper/app/reaction.py` (`label`, `body_moments`, `expression_map`, `extra_weights`), E/S `face.py` (`pose_from_matrix`, reserva do YuNet); painel `clipper-face-map.tsx` | `clipper/tests/test_expressions.py`; seção "Expressões" em "Rastreio de reação" abaixo |
| Equipe de IA: papéis (`judge.roles`), juiz de contexto, linha do tempo JSON + mosaico (`timelineJson`), medição (`ai_calls`, `GET /v1/judge/report`), rótulo do dono | `clipper/app/roles.py`, `context_judge.py`, `timeline.py`, `report.py`, `judge.py`, `worker.py`, `intel.py`; painel `clipper-ai-team.tsx`, `clipper-judge.tsx`, `clipper-clip-parts.tsx` | `clipper/tests/test_roles.py`, `test_context_judge.py`; [clipper-ai-team.md](clipper-ai-team.md) |
| Chat (IRC anônimo da Twitch com `CAP REQ :twitch.tv/tags` → emotes nativos e `room-id`; Pusher da Kick, emotes `[emote:id:NOME]`) | `clipper/app/chat.py` | — |
| Heurística: pesos, base de 3 min, mínimo proporcional (`_required_messages`), reações (`min_reactions`), chat fraco (`sparse_rate` 0,5 msg/s), momentos do chat/áudio/rosto (`_chat_moments`/`_audio_moments`/`_face_moments`; `face_*` em `Params`), `pick_peaks`, `fit_window` (duração de todo corte automático) | `Params` e funções em `clipper/app/scoring.py`; alvo `min_target` em `layout.py` | `clipper/tests/test_scoring.py` (regressões de falso positivo, chat fraco e rosto), `test_duration_banner_fonts.py` |
| Rastreio de reação — E/S: backends (MediaPipe; plano B OpenSeeFace), download sob demanda com sha256, recorte FFmpeg 6 qps, laço `face` | `clipper/app/face.py` (`for_scoring`, `must_wait`, `view`, `reset`); laço `_face_loop` e uso de `must_wait` na decisão do corte em `worker.py`; bancada `clipper/tools/face_bench.py` | `clipper/tests/test_face.py`, `clipper/models.lock.json`, `doc/FACE_BAKEOFF.md` |
| Rastreio de reação — lógica pura: sinal por segundo contra o neutro do streamer, rótulos, `reaction_moments`, `summarize` (linha do analista), `locate_cam` (câmera pelo rosto) | `ReactionParams` e funções em `clipper/app/reaction.py` | `clipper/tests/test_reaction.py` |
| Emotes: catálogo 7TV/BTTV/FFZ (canal + global, TTL 1 h, fonte que falha é ignorada), emojis, peso aprendido (`LEARN_UP`/`LEARN_DOWN` 0,3/0,15) | `clipper/app/emotes.py`; ingestão e aprendizado em `clipper/app/intel.py` (`ingest_chat`, `learn_from_clip`) | `clipper/tests/test_intel.py` |
| Contexto do jogo (categoria a cada `GAME_CHECK_S` 600, `screen_game`, perfil pela web; `clean_profile`, `save_profile`, `refine`, `delete_note`), varredura (`SCAN_*`), webcam (`detect_cam`: YuNet local primeiro, IA só se não achar ou `use_ai`; `CAM_RETRY_S` 300), opções `OPTION_DEFAULTS` (inclui `faceTrack`) | `clipper/app/intel.py` | README do Clipador |
| Juízes (analista + editor), prompts, glossário `CHAT_GLOSSARY`, linha "Rosto do streamer: …" do analista, schemas, chamada da CLI, pesquisa e refino do jogo (`PROFILE_SYSTEM`/`research_game`, `REFINE_SYSTEM`/`refine_game`), câmera | `clipper/app/judge.py`; montagem dos 6 frames do analista (8 se o trecho passa de 80 s) em `worker.py` | README do Clipador |
| Detecção do jogo da live (`check_game` a cada `GAME_CHECK_S` 180, `detect_game`, `detect_game_now`, `note_screen`, `canon`, `gather_evidence`; regra pura `Evidence`/`fuse`/`count_mentions`/`is_generic`; `sessions.game_status`/`game_detect_json`) | `clipper/app/game_detect.py` (regra) + `intel.py` (pistas e aplicação); `judge.py` (`GAME_SYSTEM`/`GAME_SCHEMA`, `Judge.detect_game`); `main.py` (`session_view`: `gameStatus`, `gameDetect`; `PUT …/game`, `POST …/game/detect`); painel `clipper-games.tsx` (`SessionGame`), `clipper-client.ts` (`GameStatus`, `GameDetect`, `GAME_CLUE_LABEL`, `gameNeedsReview`) — seção "Detecção do jogo da live" abaixo | `clipper/tests/test_game_detect.py`; `doc/clipador/DETECCAO-JOGO.md`; `ALLOWED` em `panel/src/lib/clipper.ts` (gotchas, item 180) |
| Contexto do jogo (`screen_game` da varredura, perfil pela web; `clean_profile`, `save_profile`, `refine`, `delete_note`; perfis bilíngues, `add_game`, `delete_game`, `translate`, aliases, `import_seeds` de `clipper/app/seeds/games/*.json`; contrato em `doc/clipador/JOGOS.md`), varredura (`SCAN_*`), webcam (`detect_cam`: YuNet local primeiro, IA só se não achar ou `use_ai`; `CAM_RETRY_S` 300), opções `OPTION_DEFAULTS` (inclui `faceTrack`) | `clipper/app/intel.py` | README do Clipador |
| Juízes (analista + editor), prompts, glossário `CHAT_GLOSSARY`, linha "Rosto do streamer: …" do analista, schemas, chamada da CLI, pesquisa e refino do jogo (`PROFILE_SYSTEM`/`research_game`, `REFINE_SYSTEM`/`refine_game`), câmera, detecção do jogo pela tela (`SCAN_SCHEMA` exige `screen_game_confidence` high\|medium\|low e `screen_evidence`; `Judge.detect_game(images, live_title)` com 3 frames) | `clipper/app/judge.py`; montagem dos 6 frames do analista (8 se o trecho passa de 80 s) em `worker.py` | README do Clipador |
| Hashtags da legenda (`to_tag`, `fold`, `split_hashtags`, `compose`, `build_caption`; `MAX_TAGS` 8, `GAME_TAGS` 3, `MOMENT_TAGS` 4) | `clipper/app/hashtags.py`; uso em `judge_clip` de `worker.py`; campo `hashtags` em `judge.py` (`VERDICT_SCHEMA`, `PROFILE_SCHEMA`, `Verdict.hashtags`) e `PROFILE_LISTS`/`clean_profile`/`Intel.session_game` em `intel.py` — ver "Hashtags da legenda" abaixo | `clipper/tests/test_hashtags.py` |
| Configuração do corte: camadas padrão ← canal ← sessão ← projeto (`DEFAULTS`, `merge`, `validate`), `format.aspect` (`ASPECTS`, `FRAME_SIZES`, `CANVAS_SIZES`, `aspect()`), `MODES` (5 modos, inclui `cam_only`), `resolved_mode` (queda para `blur` sem câmera; `full` no horizontal), retângulos, legenda, crédito, `duration` (`min_target`), `hook` (`HOOK_STYLES`, `HOOK_ANIMS`, `HOOK_FONT`), `capture`; fontes empacotadas (`PACKAGED_FONTS`, `font_files`, `ass_filter` = `ass=` com `fontsdir` só se o ASS usar uma delas); cadeia de layout reutilizável `layout_chain(settings, src, dst, tail, suffix, mode)` (usada por `video_filter` e pelo editor) | `clipper/app/layout.py`; rotas de settings em `main.py` (devolvem `aspects`, `frames`, `fontFiles`, `hookStyles`, `hookAnims` e `captureQualities`) | `clipper/tests/test_format_and_captions.py` (o vertical precisa continuar batendo com `clipper/tests/data/vertical_golden_sha256.json`); modo novo também em `LayoutMode`/`MODE_LABEL` de `panel/src/components/clipper-client.ts` e `resolvedMode` de `clip-editor-model.ts`; grupo novo também em `CutSettings` (`Aspect`, `aspectOf`, `withFormat` para serviço antigo) |
| Projeto de edição: modelo, tempo sessão↔saída, `normalize_cuts`, `validate_project`, `auto_project` (projeto da IA), `pick_hook` (texto do gancho), `CAPTION_PRESETS`, `SUGGEST_SCHEMA`/`clean_suggestion` | `clipper/app/editor.py` | `clipper/tests/test_editor.py`, `clipper/tests/test_editor_layers.py`; tipos espelhados em `panel/src/components/clip-editor-model.ts` |
@@ -45,7 +53,7 @@ renderiza cortes verticais (1080×1920, padrão) ou horizontais (1920×1080, You
| Legenda (tempo saneado: `clean_words`, `group_words`, `caption_blocks`; `build_ass`) e crédito — usada pelo render do editor e pelo worker, nos dois formatos | `clipper/app/subtitles.py` (`MIN_WORD_S` 0,06, `MIN_STEP_S` 0,04). `media.render_vertical` ainda existe em `media.py`, mas **não** é mais usado pelo render de cortes | `clipper/tests/test_format_and_captions.py`; [gotchas.md](gotchas.md) itens 57–58, 70, 90 |
| Rotas HTTP | `clipper/app/main.py` (editor: `editor_api.py`) | `ALLOWED` em `panel/src/lib/clipper.ts` (o proxy recusa caminho fora da regex) e o timeout por rota no mesmo arquivo |
| Variáveis do `.env` | `clipper/app/config.py` + `clipper/.env.example` | tabela do README do Clipador |
| Página `/clipper` | `panel/src/app/clipper/page.tsx`, `panel/src/components/clipper-*.tsx` (`clipper-cut-settings.tsx` modal do corte em 5 abas, com Gancho e "Qualidade da gravação"; `clipper-games.tsx` aba Jogos e emotes (editar perfil, pedir à IA, pedidos guardados); `clipper-queue.tsx` cartão com a análise, reação do rosto (`FaceSignal`, `FACE_LABEL`), recuo do início `START_STEPS`, botão "Editar"/"Continuar edição", "Apagar" e seleção discreta (`SelectionPill`); `clipper-judge.tsx` interruptor "Rastrear a reação do streamer"; `clipper-sessions.tsx` cartão da sessão (`sessionHealth`, selo de quem achou a câmera, relógio `RecordingClock`, cadência `SummaryCadence`) e cabeçalho em `clipper-studio.tsx`), cliente `clipper-client.ts` | [panel.md](panel.md) |
| Páginas `/clipper/*` (grupo de rotas `panel/src/app/clipper/(studio)/`, layout com `ClipperProvider` + `ClipperShell`) | `clipper-provider.tsx` (dados + consulta periódica, `useClipper()`), `clipper-shell.tsx` (`CLIPPER_SECTIONS`, cabeçalho, bloco "Ao vivo agora · N"), páginas `clipper-clips-page.tsx` (+ `clipper-clip-table.tsx` `ClipTable`, `clipper-clip-dialog.tsx` `ClipDialog`, `clipper-clip-parts.tsx`), `clipper-sessions-page.tsx`, `clipper-session-detail.tsx`, `clipper-channels.tsx` (Fontes), `clipper-games-page.tsx` + `clipper-game-dialog.tsx` + `clipper-game-parts.tsx` + `clipper-games.tsx` (emotes), `clipper-settings-page.tsx`; peças compartilhadas em `clipper-sessions.tsx` (`PlatformIcon`, `CutNow`, `RecordForm`, relógio, `sessionHealth`) e utilitários da lista em `clipper-queue.tsx`; `clipper-cut-settings.tsx` modal do corte em 5 abas; `clipper-judge.tsx`; cliente `clipper-client.ts`. Mapa de rotas e papéis em [panel.md](panel.md#página-clipper-clipador) | [panel.md](panel.md) |
| Página do editor `/clipper/edit/[clipId]` | `panel/src/app/clipper/edit/[clipId]/page.tsx` + `panel/src/components/clip-editor*.ts(x)` (papel de cada arquivo em [panel.md](panel.md#editor-de-cortes)); tokens `--color-nle-*` e bloco `.nle` em `panel/src/app/globals.css` | [panel.md](panel.md#editor-de-cortes) |
| Ponte e proxy do painel | `panel/src/lib/clipper.ts` + `panel/src/app/api/clipper/[...path]/route.ts` | — |
| Fontes (canais de live) nos canais de publicação | `linkChannel`/`endChannel`/`accountsForChannel` em `panel/src/lib/accounts.ts`; rotas `panel/src/app/api/accounts/[id]/channels/`; card "Fontes de corte" em `account-manager.tsx`. Na UI "Canais" virou **"Fontes"**; código e rotas seguem `channels` | [panel.md](panel.md) |
@@ -64,20 +72,30 @@ renderiza cortes verticais (1080×1920, padrão) ou horizontais (1920×1080, You
- **Aprendizado dos emotes:** aprovar/rejeitar no painel = ±0,3/0,15 nos emotes de −10 s a +6 s do pico, uma vez por
corte (`clips.learned`); a decisão da IA conta com `factor=0.5`. Peso limitado a −1…3.
## Juízes (decisão do usuário: pela CLI, sem chave de API)
## Juízes (decisão do usuário: pela CLI; chave de API só pelo cofre do painel)
- Provedores `codex` (padrão `gpt-6-luna`; lista de `~/.codex/models_cache.json`), `claude` (`haiku`/`sonnet`/`opus`)
ou `off` (só a heurística).
- Provedores `codex` (padrão `gpt-6-luna`; lista de `~/.codex/models_cache.json`), `claude` (`haiku`/`sonnet`/`opus`),
`gemini` (`Judge._gemini`: `gemini -p <instrução curta> -o json --approval-mode plan --skip-trust -m <modelo>`, prompt
completo pelo stdin, schema no prompt e JSON extraído de `response`; frames copiados para pasta temporária **fora do
repo**, porque `@arquivo` respeita o `.gitignore`) ou `off` (só a heurística).
- **IA reserva por chamada** (18/11/2026): `clipper/app/ai_settings.py` lê `data/ai/settings.json` e o cofre
`data/ai/vault.bin` (DPAPI por `ctypes`; **só leitura**, quem escreve é o painel). Falha de indisponibilidade (cota,
429, login, chave, rede, CLI fora) pausa a IA e a mesma chamada segue na próxima pronta da `order`; erro de conteúdo
não troca. Contrato: `doc/ia.md`; visão geral e armadilhas: [ai.md](ai.md). Teste: `clipper/tests/test_ai_fallback.py`.
Só vale depois de reiniciar o Clipador (gotchas, item 144). Gemini com chave real e `@arquivo` de imagem: não testados.
- **ANALISTA** vê 6 frames (8 se o trecho passa de 80 s) + fala + chat + glossário e devolve `situation`, `what_happened`, `screen`, `speech`,
`chat_meaning`, `confidence` (0–1) e início/fim da ação. **EDITOR** vê só texto + a análise e escreve título,
legenda, nota e corte. Os dois podem recuar até `duration.backtrackS` (padrão 120 s) antes do candidato.
- `PUT /v1/judge`: provedor, `model` (editor), `analystModel` (vazio = o mesmo), `minScore`, `scanEnabled`,
`scanIntervalS`, `vision`, `camDetect`, `faceTrack`. Fica na tabela `settings`, sem reiniciar; o `.env` só dá o valor inicial.
`scanIntervalS`, `vision`, `camDetect`, `faceTrack`, `timelineJson`, `roles`. Fica na tabela `settings`, sem reiniciar; o `.env` só dá o valor inicial.
- **Equipe de IA (18/11/2026):** hoje são quatro papéis (varredura, analista, editor e o **juiz de contexto**), cada um com
provedor + modelo + raciocínio + instruções do administrador (`judge.roles`), e a IA lê a live como linha do tempo JSON
(`timelineJson`). Tudo em [clipper-ai-team.md](clipper-ai-team.md); o texto acima descreve o fluxo base analista → editor.
- Codex: cada imagem com seu `-i`, todas antes do `-` final; `--search` é opção **global** (antes de `exec`).
- Custo fixo: cada chamada é um processo novo (2 por candidato). `codex_lean_overrides(search, config_file=None)` em
`judge.py` enxuga o Codex; o Claude leva `--setting-sources project,local`. Números e limites em
[token-economy.md](token-economy.md); teste: `test_codex_lean_overrides`. Vale após reiniciar o Clipador (gotcha 136).
- Não adicione chave de API ao juiz sem pedido do usuário. Corte manual é renderizado mesmo com nota baixa.
- Chave de API do juiz vem só do cofre do painel (`authMode: "apiKey"`, variável só na chamada); não crie outro caminho de chave sem pedido do usuário. Corte manual é renderizado mesmo com nota baixa.
## Hashtags da legenda (`hashtags.py`)
@@ -138,8 +156,9 @@ montada por `build_caption(text, tags, credit)` (partes separadas por linha em b
- Webcam: `POST /v1/sessions/{id}/detect-cam` (YuNet local em 12 quadros, sem IA; a IA olha 3 frames só se o local
não achar rosto e `vision` estiver ligada, ou com `?ai=true`) ou automática nos 2 primeiros blocos, se `camDetect`.
`cam_json.source` = `yunet` | `ai` | `manual`. Prévia sem salvar (no formato efetivo): `POST …/preview`; quadro: `GET …/frame?t=`.
- Jogo da sessão: `PUT /v1/sessions/{id}/game` trava a troca automática. Emotes do canal:
`GET /v1/emotes?channel=twitch-<login>`.
- Jogo da sessão: `PUT /v1/sessions/{id}/game` confirma o jogo (`game_source = user`; a troca automática vira só
sugestão) e `POST …/game/detect` roda a detecção ("Detectar agora"); regras em "Detecção do jogo da live". Emotes do
canal: `GET /v1/emotes?channel=twitch-<login>`.
- Timeouts do proxy do painel: 8 min para `games/*/(research|refine)`, 5 min para
`clips/*/(proxy|preview-render|retranscribe|tts|suggest|waveform)`, 3 min para `detect-cam|preview|check`, 30 s para
`sessions/*/face(/reset)`, 2 min o resto.
@@ -225,6 +244,26 @@ medições em `doc/FACE_BAKEOFF.md`. Roda no PC, sem IA. Opção `faceTrack` (pa
(gotchas, item 92). Não baixe esse piso sem medir.
- **Sinal:** z robusto de cada canal contra o neutro dos últimos 180 s do próprio streamer; rótulos `risada`, `grito`,
`susto`, `choque`, `raiva`, `confuso`. Ajuste por `ReactionParams` (pisos por canal, pesos, limiares).
- **Expressões, cabeça e corpo** (18/11/2026; `doc/clipador/EXPRESSOES.md`, sem migração: os campos novos vão no
`data_json` de `face_track`, séries antigas continuam valendo):
- Rótulos novos só a partir de blendshapes que já vinham: `gargalhada` (risada + cabeça ≥ 20° para trás), `alegria` (só no
mapa), `medo`, `nojo`, `tristeza`, `espanto`, `tenso`, `bocejo`. Além dos antigos (`risada`, `grito`, `susto`, `choque`,
`raiva`, `confuso`). Pose (yaw/pitch/roll) vem da matriz de transformação facial do MediaPipe
(`output_facial_transformation_matrixes=True`, `face.pose_from_matrix`).
- **Reserva do YuNet:** quando o MediaPipe perde o rosto (streamer de perfil), o YuNet roda **só nesse quadro** (5,3 ms) e dá a
caixa da cabeça → corpo: `balançando`, `acenando`, `agitado`, `chegou perto`, `saiu do quadro` (`reaction.body_moments`;
"saiu" só com o campo `head`). Rastreio perdido nunca vira movimento.
- **Canais novos só dão nome, não criam picos:** `ReactionParams.extra_weights` = 0 (a intensidade alimenta nota e fonte
`face`; mexer sem conjunto aprovado/rejeitado maior seria chute). Ligar um canal = dar peso lá e medir de novo. Única mudança
nos picos: bocejo deixou de contar como grito.
- **Calibração (dados reais, 4 sessões):** bocejos eram os maiores "gritos" (jawOpen ≥ 0,6 por 3 s); `noseSneerLeft/Right`,
`cheekSquintLeft/Right`, `cheekPuff` são sempre ~0 no MediaPipe (nojo usa o lábio de cima); mão no rosto ainda engana a
boca (tristeza/espanto/medo/raiva no mapa); cadeira vazia pode gerar "rosto fantasma"; balançar a 6 qps é movimento, não
"não" literal. Série de 1,7 h: ~1,4 MB/h no banco; análise ~1 s.
- API: `GET /v1/sessions/{id}/face` ganha `expr`/`body` por segundo e `body: [{startS,endS,peakS,label,value}]`; a linha
"Rosto do streamer" do analista leva até 2 movimentos do corpo (com rosto de perfil: "sem expressão legível… saiu do quadro").
Painel: **Mapa de expressões** no modal do corte (`clipper-face-map.tsx`), chip `FaceSignal` com os rótulos novos.
- **Não verificado:** serviço real rodando o código novo; painel no navegador (só `tsc`); câmera escura/minúscula além da do tfue.
- **Cortes:** rosto **reforça, não manda.** `reasons.face` + bônus ≤ 0,6 em momentos do chat/áudio; fonte `face` só
com z ≥ 6 **e** apoio (áudio suavizado ≥ 1,5 ou ≥ 2 mensagens de reação). A decisão do corte espera o rosto do
trecho (no máximo 2 blocos atrás da transcrição). O analista recebe a linha "Rosto do streamer: …" — exceto
@@ -322,18 +361,131 @@ Teste local do editor sem tocar no serviço do usuário: instância na faixa 450
banco, com as regras do item 77 de [gotchas.md](gotchas.md). Teste de UI no painel do usuário sobre um corte real:
intercepte as escritas (item 86) e ache as camadas do canvas pelo cursor (item 85).
## Parar é parar e idioma (18/11/2026)
Texto completo no README do Clipador ("Parar é parar", "Idioma por fonte e por sessão").
- **Parar à mão pausa o monitor da fonte.** `POST /v1/sessions/{id}/stop` (corpo opcional `{"pauseMonitor": false}`;
padrão `true`) grava `channels.monitor_paused_at` + `monitor_paused_session`; o monitor pula a fonte pausada. Limpam a
pausa: `PATCH /v1/channels/{id}` com `{"monitor": true}`, `POST /v1/sessions` (gravar pelo link) e `resume` pelo painel.
Queda de live (captura cai sozinha) **não** passa pela pausa: continua `keep_live`, na mesma sessão. Na UI: a fonte
mostra "monitor pausado · você parou a sessão #N" com **Religar**; o diálogo de parar tem a opção de voltar a gravar
sozinho (marcada = não pausa).
- **Idioma.** `language` em `channels` e `sessions` (`pt-BR`, `en-US`, `es-419`; `''` = `CLIPPER_LANGUAGE`), aceito em
`POST/PATCH /v1/channels` e `POST /v1/sessions`; as visões de fonte, sessão e corte devolvem o idioma **já resolvido**.
O Whisper usa o idioma da sessão (pela fronteira `voice_language`, ver abaixo); espanhol mantém os prompts em português com a nota de idioma de saída; inglês tem juízes próprios (seção "Fonte em inglês").
No painel, `accounts.language` (migração v9 do painel, padrão `pt-BR`) e o aviso no diálogo Publicar quando o idioma do
canal difere do idioma do corte. Versão do corte em outro idioma para publicar: **ainda não existe**; a tradução em português guardada é só para a equipe ler.
- Sem reiniciar o Clipador as rotas novas não valem; o painel trata `language`/pausa como opcionais e não quebra
(gotchas, item 166).
## Fonte em inglês (18/11/2026)
Fonte do contrato: `doc/clipador/IDIOMAS.md`; README do Clipador, "Idioma por fonte e por sessão". Decisão do dono: o
**vídeo sai em inglês** (título, legenda, hashtags, gancho) e **a equipe vê tudo em português** no painel.
- **Regra:** `judge.lang_key(language)` = `"en"` para `en-*`, senão `"pt"`; `Intel.lang(session)` resolve. Em inglês, analista,
editor e varredura usam `ANALYST_SYSTEM_EN`/`JUDGE_SYSTEM_EN`/`SCAN_SYSTEM_EN`, `CLIP_GUIDE_EN`, `CHAT_GLOSSARY_EN` e
`LABELS` en nos montadores (parâmetro `lang` em `Judge.analyze/judge/scan`). Perfil do jogo no prompt = `profileAi`.
- **Tradução sem chamada extra:** os schemas `*_EN` exigem o bloco `pt` (analista: `what_happened`, `screen`, `speech`,
`chat_meaning`, `hook`; editor: `title`, `caption`, `reason`; varredura: `summary_pt` e `pt` por momento). Vai em
`judge_json.pt`, `memory[].summaryPt`, `reasons.proposalTitlePt/proposalReasonPt`. `analysis_block` tira o `pt` antes do editor.
Campo novo no schema inglês = pôr o `pt` correspondente e mostrar no painel.
- **Fala traduzida:** `Engine.translate_clip(clip_id, lo, hi, force)` (chamada quando o corte é mantido) grava
`clips.translation_json` `{language, startS, endS, model, lines: [{s, e, text, pt}]}`; frases de `subtitles.phrases`
(pausa > 0,7 s, fim de frase com 4+ palavras, 16 palavras ou 6 s) traduzidas por `Judge.translate_lines`.
`POST /v1/clips/{id}/translate` refaz (409 em fonte PT); `clip_view.translation`.
- **Legenda em português no vídeo (só para desenvolver):** `dev.translation` (padrão `false`; `caption.translation` é o legado, ainda lido) → estilo ASS `Trans`
(metade do tamanho, `&H00FFE79B`) sob a legenda, seguindo o desvio do gancho; só entra no ASS quando ligado **e** há
tradução (sem isso o ASS é idêntico ao de antes). `editor_api.translation_for` alimenta render e prévia. Entra só no
**vídeo de revisão**: o final, gerado ao aprovar, sai sem ela ([clipper-video.md](clipper-video.md); dublagem: mesma seção).
- **Heurística:** `scoring.py` (`REACTION_PATTERNS`, `SPOKEN_REACTION`) reconhece reação em inglês (lmao, lol, 💀, 😭, no
way, bruh, holy, clutch, goated, clip that…). `judge.output_language_note` agora é vazio também para inglês.
- **Voz:** `worker.VOICE_LANGUAGES`/`voice_language()` converte `en-US` → `en` e `es-419` → `es` antes do Whisper (gotchas, item 173).
- **Começar uma fonte gringa:** Fontes → idioma English (US); jogo com perfil em inglês e gírias do público gringo
(Jogos → "acrescente as gírias…", ou `POST /v1/games/{id}/translate` se o perfil só existe em português); ligar
"Tradução em português embaixo (teste)" (e, se quiser, "Dublagem em português (teste)") na configuração do corte do
canal enquanto estiver testando. Fontes em teste (18/11/2026): twitch-tfue (ROB RUN) e twitch-maxylobes (GTA V Chaos
Mod, en-US, `dev.translation` + `dev.dub` ligados).
- **Painel:** modal do corte com bloco "Em português" (título, legenda, "O que ele fala" frase a frase, botão "Traduzir a
fala"); lista com título traduzido (🇧🇷); resumo da sessão em português; switch em `clipper-cut-settings.tsx`; Fontes: a
coluna "Ao vivo" mostra "gravando #N" da sessão ativa e checagem do monitor com mais de 10 min vira "ao vivo há X"
apagado (gotchas, item 174).
- Medido (18/11/2026, sessão 15, twitch.tv/tfue, ROB RUN, 1080p60 h264, informado pelo coordenador): transcrição em
inglês ok; câmera pela YuNet em 12/12 quadros; corte manual 259 (30–100 s) com título, legenda e hashtags em inglês,
`judge.pt` em português, 27 frases traduzidas e vídeo 1080×1920 com inglês em cima e português embaixo. Não verificado
por mim: o render real (só a suíte foi reexecutada); qualidade da tradução fora desse corte; espanhol ponta a ponta.
## Detecção do jogo da live (18/11/2026)
Fonte do contrato: `doc/clipador/DETECCAO-JOGO.md`; seção "Contexto do jogo" de `clipper/README.md`. Decisão do dono:
ninguém precisa lembrar de dizer o jogo; o Clipador descobre sozinho e o usuário só confirma ou corrige.
- **Quando:** `Intel.check_game` a cada `GAME_CHECK_S` 180 s grava a categoria/título em `sessions.game_detect_json`
(`platform`) e chama `detect_game`. A varredura e "Detectar agora" gravam a tela com `note_screen` (vale
`SCREEN_FRESH_S` 900 s). Chat e fala: últimos `CHAT_WINDOW_S` 360 s e 12 blocos (`SPEECH_SEGMENTS`).
- **Pistas** (`game_detect.Evidence`; peso por fonte `SOURCE_WEIGHT`: categoria 0,55, tela 0,5, chat e fala 0,35,
título 0,25; tela multiplica pela confiança high 1 / medium 0,7 / low 0,4). Cada fonte conta uma vez por jogo.
`fuse` junta os pesos por ruído-ou e decide `status`:
`agreed` (≥ 2 fontes e nota ≥ 0,6), `probable` (nota ≥ 0,34), `conflict` (2º colocado ≥ 0,34, vantagem < 0,25 e com
fonte forte = categoria ou tela), `unknown`. Chat só conta com ≥ 2 mensagens citando o jogo.
- **Estados em `sessions.game_status`:** `user` (você confirmou) | `agreed` | `probable` | `conflict` | `unknown` (`''` =
sessão antiga, ainda não checada).
- **Regras de troca** (`detect_game`):
- Jogo confirmado por você (`game_source = user`) **nunca** muda sozinho; se as pistas concordam em outro jogo por 2
checagens seguidas vira `suggestion` e o painel pergunta.
- Sem confirmação, trocar de jogo exige a categoria apoiando **ou** a mesma resposta em 2 checagens seguidas
(`state.pending.n`); "Detectar agora" (`immediate`) pula a espera.
- Conflito categoria × tela mantém o jogo atual e o painel pergunta (um botão por candidato).
- Categoria genérica ("Just Chatting", "IRL", "Só Bate-papo"…, `GENERIC_CATEGORIES`) não é jogo: fica registrada, não conta.
- **Nomes:** `canon(name)` resolve categoria "Grand Theft Auto VI" e tela "GTA 6" para o mesmo id quando o jogo (ou um
alias) está cadastrado. `count_mentions` casa palavra inteira e confere duas leituras do texto: sem acento (`slug`) e
como `intel.game_id` gerou o id, que **não** tira acento (`Pokémon` → `pok-mon`).
- **"Detectar agora"** (`POST /v1/sessions/{id}/game/detect`, `detect_game_now`): a IA vê 3 frames (−120, −60 e −6 s) e
o título; sem IA ou sem visão (`vision`) responde erro de usuário. Leva de 10 s a 1 min. Resposta `{result, session}`.
- **API:** `session_view` ganhou `gameStatus` e `gameDetect` `{checkedAt, candidates, suggestion, platform, screen}`.
`PUT …/game` confirma à mão e roda a detecção (limpa a sugestão).
- **Painel:** `SessionGame` em `clipper-games.tsx`: selo do estado, botão "Detectar agora", aviso de conflito, aviso de
sugestão e "Como o jogo foi descoberto"; `gameNeedsReview` (`clipper-client.ts`) é o que `clipper-session-detail.tsx` e
`clipper-sessions-page.tsx` usam para chamar a atenção (serviço antigo sem `gameStatus`: cai no cálculo por `screenGame`).
- **Limites:** chat e fala só reconhecem jogos já cadastrados em Jogos (`_mention_forms` lê a tabela `games`); sem IA/visão
não há pista de tela. Só vale com o serviço reiniciado (migração v16; gotchas, item 180).
## Perfil do jogo (aba Jogos)
Toda rota abaixo devolve a lista inteira (mesma forma de `GET /v1/games`).
Fonte do contrato: `doc/clipador/JOGOS.md`; seção "Contexto do jogo" de `clipper/README.md`. Toda rota abaixo devolve a
lista inteira (mesma forma de `GET /v1/games`), exceto onde dito.
**Dois idiomas.** `profile` = português (o que o painel mostra); `profileAi` = inglês (vai nos prompts; `null` = não
traduzido, a IA usa `profile`); `aiLanguage` `en-US`; `translatedAt`; `aliases` (união dos dois perfis). Campos novos do
perfil: `aliases` (≤ 10), `missions` `[{name, chapter, summary, completion_triggers ≤ 8 de 200 caracteres}]` (até 120;
`[]` quando não há lista pública — a IA nunca inventa) e `end_triggers` (≤ 12, sinais gerais de fim de missão).
`game_context` (`judge.mission_lines`: `MISSIONS_IN_PROMPT` 25, `MISSIONS_PROMPT_CHARS` 1500) manda terminar o corte de
missão logo depois do gatilho de fim. Busca por nome casa `id` **ou** alias (categoria "Grand Theft Auto VI" e tela
"GTA 6" = mesmo jogo).
| Rota | Faz |
|---|---|
| `GET /v1/games` | perfis com `status`, `model`, `researchedAt`, `editedAt`, `notes` (`[{text, at, section?}]`) e `profile` |
| `POST /v1/games/{id}/research` | refaz o perfil do zero pela web (`RESEARCH_TIMEOUT_S` 420); os pedidos guardados entram no prompt |
| `PUT /v1/games/{id}` | grava o perfil editado à mão: `name`, `summary`, `genre`, `mechanics`, `clip_worthy`, `avoid`, `jargon`, `news`, `hashtags`, `sources` |
| `POST /v1/games/{id}/refine` | `{instruction, search, section, history}` → `{games, reply}`. `instruction` 3–1500 caracteres; `search` padrão `true` (`false` = sem web, `TIMEOUT_S` 240); `section` `""` \| `summary` \| `clip_worthy` \| `avoid` \| `mechanics` \| `news` \| `jargon` \| `hashtags` \| `sources` (`Literal` em `GameRefineIn` de `main.py`, inválido dá 422); `history` `[{role: "user"\|"ai", text ≤1500}]`, máx. 20. A IA devolve o perfil inteiro + `reply` (1–2 frases do que mudou); guarda o pedido (com `section`) e marca `edited_at` |
| `GET /v1/games` | perfis com `status`, `error`, `model`, `researchedAt`, `editedAt`, `translatedAt`, `notes` (`[{text, at, section?}]`), `aliases`, `profile`, `profileAi` |
| `POST /v1/games` `{name, notes?}` | cadastra (201, `{games, id}`, status `pending`) e pesquisa em segundo plano; 409 se o `id` ou um alias já existe |
| `DELETE /v1/games/{id}` | apaga o jogo (sessões não mudam; volta a ser pesquisado se o jogo reaparecer); 404 se não existe |
| `POST /v1/games/{id}/research` | refaz o perfil do zero pela web **em inglês** e traduz para português (`RESEARCH_TIMEOUT_S` 420); os pedidos guardados entram no prompt |
| `POST /v1/games/{id}/translate` | gera o inglês a partir do português (jogo de antes dos perfis bilíngues) |
| `PUT /v1/games/{id}?lang=pt\|en` | grava a edição à mão no idioma `lang` (padrão `pt`) e traduz para o outro; sem IA, grava e deixa o outro desatualizado. Campos: `name`, `summary`, `genre`, `mechanics`, `clip_worthy`, `avoid`, `jargon`, `news`, `hashtags`, `sources`, `aliases`, `missions`, `end_triggers` |
| `POST /v1/games/{id}/refine` | `{instruction, search, section, history}` → `{games, reply}`. Aplica no inglês e responde em português. `instruction` 3–1500 caracteres; `search` padrão `true` (`false` = sem web, `TIMEOUT_S` 240); `section` `""` \| `summary` \| `clip_worthy` \| `avoid` \| `mechanics` \| `news` \| `jargon` \| `hashtags` \| `sources` \| `missions` \| `end_triggers` \| `aliases` (`Literal` em `GameRefineIn` de `main.py`, inválido dá 422); `history` `[{role: "user"\|"ai", text ≤1500}]`, máx. 20. A IA devolve o perfil inteiro + `reply`; guarda o pedido (com `section`) e marca `edited_at` |
| `DELETE /v1/games/{id}/notes/{index}` | esquece um pedido guardado (o perfil atual fica como está) |
- Tradução que falha (ou IA desligada): a outra versão fica como estava (na pesquisa, as duas em inglês), `error`
explica e `translatedAt` não muda. Tradução nunca mexe em nome, hashtags, fontes e outros nomes, e é recusada se
perder missões.
- **Sementes:** `clipper/app/seeds/games/*.json` (`{name, aliases, researchedAt, sources, profileAi, profile}`) é
importado na subida **só se o jogo não existe**. Hoje: `gta-vi.json` (GTA VI lança 19/11/2026, sem lista oficial de
missões; a semente traz 4 do vídeo "An Extended Look" com nomes descritivos **não oficiais** — pesquisar de novo
depois do lançamento; gotchas, item 167).
- Proxy do painel (`panel/src/lib/clipper.ts`): `ALLOWED` aceita `games/<id>/(research|refine|translate|notes/n)`;
`METHODS` dá GET/POST a `games` e PUT/DELETE a `games/<id>`; timeouts: 8 min `research|refine`, 5 min `translate` e
`PUT`, 30 s `POST games`.
- `clean_profile` (`intel.py`) normaliza tudo que entra: apara, tira vazios e duplicados, no máximo 20 itens por lista.
São guardados os últimos 30 pedidos.
- **Pedido guardado sobrevive a "Pesquisar de novo"** (`research_game(name, title, notes)`; `PROFILE_SYSTEM` manda
@@ -344,13 +496,10 @@ Toda rota abaixo devolve a lista inteira (mesma forma de `GET /v1/games`).
`history`, 400 caracteres cada. `REFINE_SYSTEM` manda mexer só na seção em foco e transformar pedido genérico
em item concreto ("reação do streamer conta" → "Streamer grita, xinga ou ri alto logo depois de uma morte ou fuga").
`Intel.refine(...)` (`intel.py`) devolve `(profile, reply)`.
- Painel (`clipper-games.tsx`): o cabeçalho tem selo de iniciais e os botões "Conversar com a IA" (perfil inteiro),
"Editar" (uma linha por item) e "Pesquisar de novo". Cada seção é um cartão com "Pedir à IA", que abre o chat
daquela seção (`AiChat`: Enter envia, Shift+Enter quebra linha, chave "Confirmar na web" **desligada** por
padrão no painel, embora a API use `search=true` por padrão). Item recém-acrescentado aparece com selo "novo".
"Memória da IA" lista os pedidos guardados (com a seção) e tem X. A conversa só existe enquanto o chat está
aberto. O que fica salvo é o pedido. Tipo `Game` em `panel/src/components/clipper-client.ts`
(`editedAt?`, `notes?[].section?`). Detalhes visuais em [panel.md](panel.md).
- Painel: lista em `/clipper/games` e modal por `?game=ID` (`clipper-game-dialog.tsx`, `clipper-game-parts.tsx`); o chat
`AiChat` tem a chave "Confirmar na web" **desligada** por padrão, embora a API use `search=true`. A conversa só existe
enquanto o chat está aberto; o que fica salvo é o pedido (aba "Pedidos à IA", com X). Tipos `Game`, `GameProfile`,
`GameMission` em `panel/src/components/clipper-client.ts`. Detalhes visuais em [panel.md](panel.md).
## Regras
@@ -371,6 +520,38 @@ Toda rota abaixo devolve a lista inteira (mesma forma de `GET /v1/games`).
## Testes e evidência
Detecção do jogo da live (18/11/2026): suíte inteira do Clipador (`cd clipper; .venv\Scripts\python -m pytest`) →
exit 0, 440 testes (pontos contados na saída; o `pytest.ini` usa `-q` e não imprime a linha final; reexecutado nesta
manutenção); `tests/test_game_detect.py` tem 15 testes (o lote informou 14); `npx tsc --noEmit -p panel` → exit 0
(reexecutado). Não verificado: IA real em `Judge.detect_game` e nos prompts com os campos novos; o painel no navegador;
banco real em v16 (o serviço precisa reiniciar); o botão "Detectar agora" contra o serviço — o proxy do painel não tem
`game/detect` no `ALLOWED` (gotchas, item 186; já corrigido).
Bloco de 18/11/2026 (revisão × final, dublagem, falantes, expressões, Equipe de IA e proxy): **informado pelo coordenador**
(não reexecutado por mim): suíte inteira do Clipador passa; painel `tsc` + 119 testes. Testes novos: `test_final_render.py`,
`test_dub.py`, `test_speakers.py`, `test_expressions.py`, `test_roles.py`, `test_context_judge.py`. Medidas citadas (tempo da
dublagem, custo da voz, estabilidade dos falantes, tokens por hora) vêm dos docs de `doc/clipador/` e estão nas seções
próprias. Não verificado: serviços reais com o código novo (precisam reiniciar), UI no navegador, juiz/dublagem/voz com IA e
TTS reais além dos cortes citados, banco real em v17. `onnxruntime` 1.32.0 e `mediapipe` 1.2.3 reconferidos no `clipper/.venv`.
O proxy do painel liberou `POST clips/{id}/translate` e `GET sessions/{id}/speakers` (sem isso o botão "Traduzir a fala"
dava 404; regex `ALLOWED` + `METHODS` em `panel/src/lib/clipper.ts`).
Fonte em inglês (18/11/2026): `pnpm test:clipper` → **346 passed** (reexecutado nesta manutenção, 101 s); `test_english_source.py`
novo (9 testes) e ajustes em `test_monitor_pause_and_language.py`, `test_render_and_duplicates.py`, `test_intel.py`. Não
verificado: IA real com prompts em inglês (só o corte 259 informado), painel no navegador, `pnpm typecheck`, banco real em v13
(o serviço precisa reiniciar).
Perfis de jogo bilíngues, missões, cadastro e semente do GTA VI (18/11/2026): `pnpm test:clipper` → **335 passed**
(reexecutado nesta manutenção, 108 s; bate com o informado); 10 testes em `clipper/tests/test_game_profiles.py`. Não
verificado: IA real na pesquisa, tradução e refino bilíngues; modal e lista no navegador; serviço real em v12 (precisa
reiniciar); `pnpm typecheck` e testes do painel.
IA reserva e Gemini no juiz (18/11/2026): `pnpm test:clipper` → **335 passed** (reexecutado pela skill; `test_ai_fallback.py` novo).
Reformulação da interface e regras de pausa/idioma (18/11/2026): `pnpm test:clipper` → **287 passed** (reexecutado
nesta manutenção; 9 testes novos em `clipper/tests/test_monitor_pause_and_language.py`). Não verificado: as páginas no
navegador e o banco real em v11 (o serviço precisa reiniciar).
Os testes não chamam a CLI de IA: `FakeJudge.ask` (`clipper/tests/test_sources_and_api.py`) sempre falha, e o serviço
segue pelo caminho de "IA fora". Juiz falso novo precisa cobrir `ask` também.
@@ -485,7 +666,7 @@ Não verificado:
contra o serviço reiniciado;
- apagar: rota no serviço real do usuário; arquivo em uso no Windows (deve voltar em `left`); pedido do editor em
andamento gravando em `edit-<id>/` depois de apagar; relógio da sessão com movimento reduzido, aba escondida e
larguras de 1024/1280; a faixa do topo em `clipper-studio.tsx` ainda mostra o `durationS` real (sem o relógio);
larguras de 1024/1280; a faixa do topo (hoje `clipper-shell.tsx`) pode ainda mostrar o `durationS` real (sem o relógio);
- duração, gancho, reenquadramento, camadas e captura: live 2K real e HEVC real da Twitch pela captura; gravação longa
em 1080p ou 2K com o serviço real; juiz e varredura reais com as durações novas; render real de um projeto feito no
editor com reenquadramento e camadas comparado com a prévia (pendente, depois do reinício do serviço); camadas na
+123 -2
View File
@@ -3,7 +3,7 @@
Cada item: **sintoma → causa → correção → onde está tratado**. Observadas na implementação da
prova de conceito com Godot 4.7.2 / FFmpeg 7.1.1 / pnpm 11.22 (16/11/2026). Registro formal em
`doc/TEST_RESULT.md`: itens 1–5, 7, 13–15, 17 e 18; itens 30–33 estão em `voice/README.md`
("GPU e CPU"); itens 57–61 estão em `clipper/README.md` ("Armadilhas já resolvidas"); itens 74–76, 87–90 e 103–108 também estão lá e o 78 na seção "Limitações" do editor; itens 79, 81–84 e 92–95 estão em `doc/FACE_BAKEOFF.md` (o 93 também em "Variáveis" de `clipper/README.md`) (o 80, no comentário de `clipper/requirements.txt`); itens 118–128 (publicação) seguem `doc/publicacao/` e o código; itens 151–154 foram informados em 17/11/2026 (parte conferida no código); itens 129–132 foram informados em 17/11/2026 e conferidos no código (`doc_main.gd`, `doc/godot/cenas.md`) e no banco (`agent_runs` 5, 7 e 8); itens 62–67, 77, 85–86, 91, 99–102, 109–112 e as ampliações do 52, do 44, 77, 86 e 87 foram informados em 16–17/11/2026 (não estão em `doc/TEST_RESULT.md`); os demais vieram de erros de compilação ou instalação durante a implementação.
("GPU e CPU"); itens 57–61 estão em `clipper/README.md` ("Armadilhas já resolvidas"); itens 74–76, 87–90 e 103–108 também estão lá e o 78 na seção "Limitações" do editor; itens 79, 81–84 e 92–95 estão em `doc/FACE_BAKEOFF.md` (o 93 também em "Variáveis" de `clipper/README.md`) (o 80, no comentário de `clipper/requirements.txt`); itens 168–172 (IA) seguem `doc/ia.md`; itens 118–128 (publicação) seguem `doc/publicacao/` e o código; itens 151–154 foram informados em 17/11/2026 (parte conferida no código); o 180 (detecção do jogo) foi informado em 18/11/2026 e conferido no código; itens 129–132 foram informados em 17/11/2026 e conferidos no código (`doc_main.gd`, `doc/godot/cenas.md`) e no banco (`agent_runs` 5, 7 e 8); itens 62–67, 77, 85–86, 91, 99–102, 109–112 e as ampliações do 52, do 44, 77, 86 e 87 foram informados em 16–17/11/2026 (não estão em `doc/TEST_RESULT.md`); os demais vieram de erros de compilação ou instalação durante a implementação.
Ao descobrir uma nova, registre aqui via `cenaforge-skill-updater`. Os números são estáveis
(outros textos os citam): item novo entra na seção do assunto com o próximo número livre.
@@ -508,6 +508,35 @@ Observadas em 17/11/2026 (diagnóstico da sessão 3, cartão da sessão, apagar
**Só vale depois de reiniciar o Clipador (porta 4520)**: o código é lido na partida. Detalhes em
[token-economy.md](token-economy.md). Onde: `clipper/app/judge.py`.
Observadas em 18/11/2026 (revisão × final, falantes, dublagem, trabalho em worktree):
180. **Corte aprovado "não publica" e o job fica parado.** Causa: a publicação só usa o vídeo FINAL (`publishFile`); enquanto
`final_status` não é `ready` o job mostra "Esperando o vídeo final…" (final `pending`/`rendering`, ou `error`).
Correção: olhe `final` no corte (`GET /v1/clips`, campos `final` e `publishFile`); `error` → "Tentar de novo" = `POST /v1/clips/{id}/final`.
Nunca troque para `file` (é o de revisão, com camadas de teste). Corte antigo publicado com tradução e sem final: gere
com `POST /final` antes de mandar a outra rede. Onde: `clipPublishFile` (`panel/src/lib/publishing-rules.ts`),
`sendDue` (`publishing.ts`); doc `doc/clipador/REVISAO.md`.
181. **Botão "Traduzir a fala" (e a lista de vozes) dava 404.** Causa: a rota existia no Clipador, mas a regex `ALLOWED` do
proxy do painel não liberava `clips/{id}/translate` nem `sessions/{id}/speakers`. Correção: liberadas em `ALLOWED` +
`METHODS`. Rota nova do Clipador = regex, método e timeout em `panel/src/lib/clipper.ts` no mesmo commit.
182. **Fala do colega aparece como do streamer (ou tudo em uma linha só).** Causa esperada, não bug: sem atribuição nos
primeiros minutos (< 15 s de fala por voz); volume e boca **discordam** ou nenhum decide → ninguém vira "outro"; webcam
de perfil não separa pela boca; o código novo só roda depois de reiniciar o Clipador. Correção: confira
`GET /v1/sessions/{id}/speakers` (vozes e por quê); corrija à mão no editor (**Outra pessoa / É o streamer**).
Onde: `clipper/app/speakers.py`; `doc/clipador/FALANTES.md`.
183. **Dublagem soa corrida, emendada ou cortada no fim.** Causa: o português sai bem mais longo que o inglês; o encaixe
deixa a fala escorrer até 1,5 s sobre a próxima frase, acelera até 1,2× e por fim corta com fade (medido: 9 de 25 falas
cortadas no corte 259). Não é falha; **não** acelere além disso nem clone a voz do streamer. A 1ª renderização sintetiza
(~1,6 s por frase); depois o cache (`data/clipper/dub/`) deixa +0,3 s. Onde: `clipper/app/dub.py` (`fit`).
184. **Worktree de isolamento do harness falha no Windows.** Causa: diferença de caixa da letra do drive (`f:` × `F:`).
Correção: criar a worktree à mão em `F:/Projects/cf-wt/<nome>` (`git worktree add`). Para rodar testes nela: copiar
`clipper/tests/data/vertical_golden_sha256.json` (ignorado no git, o teste dourado do vertical precisa dele) e criar
um junction `panel/node_modules` apontando para o da pasta principal (sem isso `tsc` e os testes do painel não rodam).
185. **Serviço "não pegou" ou "caiu e não voltou".** Os serviços (painel, voz, Clipador, Publicador) são do usuário, subidos
por `pnpm dev`: agente **não** sobe nem encerra. O `scripts/dev.ts` pula um serviço se a porta já está ocupada e só
reinicia sozinho a voz (quando `voice/.env` muda); serviço que cai não volta. Peça ao usuário para reiniciar o `pnpm
dev` (com a suíte verde: item 87) e compare o início do processo com o arquivo (item 143).
## Publicação (Publicador + despachante do painel)
Regras de projeto informadas em 17/11/2026 (código em `panel/src/lib/publishing*.ts` e `publisher/app/`); nenhuma
@@ -756,6 +785,98 @@ observada num envio real ainda. Contexto em [publishing.md](publishing.md).
162. **Regex com `\b` escrita por heredoc/Python sem string raw vira um caractere de controle (backspace, 0x08)** (aconteceu 2x ao
editar `montage-cartoon.ts`): a regex deixa de casar, sem erro. Use `r"..."` ou o Edit (item 44) e confira com
`grep -nP "\x08" <arquivo>` que não sobrou nenhum.
163. **Cartoon: a boca (curva quadrática) só chega à METADE do ponto de controle.** Controles da boca ficam no dobro da
abertura desejada. Onde: `cartoon/src/CharacterFigure.tsx`.
164. **Script de teste em Python que grava JSON com `open(..., "w")` sem `encoding` estraga acento no Windows** (cp1252; o
render lê UTF-8). Sempre `open(..., "w", encoding="utf-8")` (e `ensure_ascii=False` se quiser acento legível). Mesma
família do item 153. Onde: ao gerar `character.json`/spec por script.
165. **Cartoon: sombra do corpo/barriga em elipse parece mancha.** Correção: elipse + curva de volume (contorno) e sombra
lateral recortada por `clipPath`. Onde: `cartoon/src/CharacterFigure.tsx`.
166. **Clipador: depois de parar a sessão à mão, a fonte não grava de novo (ou as rotas/campos novos "não pegam").**
Dois lados. (a) Parar à mão pausa o monitor da fonte de propósito (`monitor_paused_at`): live no ar e nada
reabrindo não é falha. Religar = "Religar" em `/clipper/sources`, `PATCH /v1/channels/{id}` `{"monitor": true}`,
gravar pelo link ou retomar a sessão; `{"pauseMonitor": false}` no stop evita a pausa. Queda de live sem ninguém
parar continua retomando na mesma sessão. (b) Serviço sem `--reload` (item 144): sem reiniciar, `stop` não pausa,
`language` não é aceito nem devolvido e a migração v11 não roda; o painel trata os campos como opcionais, então
nada quebra, só não pega. Reinicie (é do usuário) e confira `PRAGMA user_version` = 11. Onde:
`clipper/app/worker.py`, `main.py` (`StopIn`), `db.py` (v11); teste `clipper/tests/test_monitor_pause_and_language.py`.
167. **Clipador: perfil do jogo sem versão em inglês, GTA VI ausente ou "cadastrar jogo" que não funciona.** (a) Serviço
sem reiniciar (item 144): a migração v12 não roda, `POST /v1/games`, `translate`, `DELETE` e `?lang=` não existem e a
semente do GTA VI não é importada (só entra na subida, e só se o jogo não existe: nunca sobrescreve edição).
Reinicie (é do usuário) e confira `PRAGMA user_version` = 12. (b) Jogo antigo tem `profileAi: null`: a IA usa o
português até rodar `POST /v1/games/{id}/translate` ("Gerar versão em inglês" no modal). (c) Categoria ou tela com
outro nome ("Grand Theft Auto VI" × "GTA 6") só cai no mesmo perfil se o nome estiver em `aliases`; cadastro com nome
já existente (inclusive alias) dá 409. (d) Missões só entram quando a lista é pública; **a semente do GTA VI traz 4
missões do vídeo "An Extended Look" com nomes descritivos, não oficiais** (jogo lança 19/11/2026, sem lista oficial):
pesquisar de novo depois do lançamento, sem apagar o jogo. Edição à mão em um idioma é traduzida para o outro; tradução
que falha deixa a outra versão como estava e `error` explica. Onde: `clipper/app/intel.py` (`import_seeds`,
`add_game`, `translate`), `main.py`, `db.py` (v12), `seeds/games/`; teste `clipper/tests/test_game_profiles.py`.
173. **Clipador: fonte em inglês sem transcrição (422 `language_not_supported` em todo bloco).** Causa: a fonte/sessão
guarda `en-US` (idioma do público), mas o serviço de voz só aceita `pt-BR`, `en` e `es`; antes de 18/11/2026 o idioma
gringo nunca tinha sido testado ponta a ponta. Correção: `worker.voice_language()` (`VOICE_LANGUAGES`) traduz na
fronteira, antes de mandar `X-Language`; idioma novo = entrada ali **e** em `WHISPER_LANGUAGES` de `voice/app/stt.py`.
Sintoma parecido: corte em inglês sem o português no painel = serviço sem reiniciar (item 144; banco precisa estar em
v13) ou corte anterior à mudança (use "Traduzir a fala" / `POST /v1/clips/{id}/translate`). Onde:
`clipper/app/worker.py`; teste `clipper/tests/test_english_source.py`.
174. **Clipador: Fontes mostrava "ao vivo" por checagem velha e parecia que a gravação estava na fonte errada.** Causa: a
coluna usava a última checagem do monitor (de 2 h antes) como se fosse agora; o Skipnho aparecia "ao vivo" enquanto a
sessão gravando era a do Tfue. Correção: a coluna mostra "gravando #N" da sessão ativa e trata checagem com mais de
10 min como "ao vivo há X" apagado. Onde: `panel/src/components/clipper-channels.tsx`.
186. **Clipador: o jogo da sessão não é detectado, fica `unknown`, ou "Detectar agora" falha.** Conferido no código em
18/11/2026. Causas, por ordem: (a) serviço sem reiniciar (item 144): a migração v16 não roda, `game_status` e
`gameDetect` não existem e `POST …/game/detect` dá 404; reinicie (é do usuário) e confira `PRAGMA user_version` = 16.
(b) Chat e fala só reconhecem jogos **já cadastrados** em Jogos (nome, id ou alias): jogo novo só aparece por
categoria ou tela até ser cadastrado. (c) Sem IA ou sem visão ligada não há pista de tela e "Detectar agora" devolve
erro de usuário ("precisa da IA ligada e da visão ligada"). (d) Categoria genérica ("Just Chatting", "IRL") não conta
como jogo. (e) `intel.game_id()` não tira acento (`Pokémon` → `pok-mon`) e `game_detect.slug` tira: `count_mentions`
confere as duas leituras; ao mexer em um dos dois, mantenha as duas.
Onde:
`clipper/app/game_detect.py`, `intel.py`, `judge.py`, `main.py`, `db.py` (v16); teste `clipper/tests/test_game_detect.py`.
## IA: provedores, login e reserva
Itens 168–172 e 175–179 informados em 18/11/2026 e conferidos contra `doc/ia.md` e o código. Contexto em [ai.md](ai.md).
168. **Gemini CLI com login Google: `IneligibleTierError: UNSUPPORTED_CLIENT`** (gemini-cli 0.68.0). Causa: o OAuth gratuito
"Code Assist for individuals" foi encerrado; o Google manda migrar para o Antigravity. OAuth só com plano elegível
(Code Assist Standard/Enterprise, Workspace). Correção: conta pessoal usa **chave do AI Studio** (`authMode: "apiKey"`).
O erro conta como indisponibilidade (`IneligibleTier`) e aciona a reserva. Onde: `panel/src/lib/ai.ts`, `doc/ia.md`.
169. **`CODEX_API_KEY` só vale no `codex exec`** (confirmado no binário 0.169.0). Para chave sem mexer na conta do usuário,
ponha a variável só na chamada (`providerEnv`); **não** use `codex login --with-api-key`, que troca o login global.
Mesma regra para `ANTHROPIC_API_KEY` e `GEMINI_API_KEY`. Onde: `providerEnv` em `panel/src/lib/ai.ts`.
170. **Terminal de login no Windows: aspas do `cmd` e caminho com espaço ("Program Files").** Forma que funcionou:
`cmd /d /c start "<título>" cmd.exe /k "<linha>"` com `windowsVerbatimArguments: true` (testado com caminho em
"Program Files"); sem o modo verbatim o Node reescreve as aspas (causa não isolada). Onde: `openLoginTerminal` em
`panel/src/lib/ai.ts`.
171. **Status das IAs lento (~0,3 s por chamada ao cofre).** Causa: a DPAPI no Node passa por PowerShell. Correção: cofre
em cache por `mtime` de `data/ai/vault.bin`; o Clipador lê com `ctypes` (`clipper/app/ai_settings.py`). Não leia o
cofre por requisição sem o cache.
172. **CLI instalada "não aparece" no painel.** Causa: o PATH do painel é o de quando ele abriu (instalação nova não entra),
e o instalador nativo do Claude usa `~/.local/bin` e o npm `%APPDATA%\npm`. Correção: `resolveCommand` procura nesses
dois lugares além do PATH; mesmo assim, instalar e não ver = "Verificar" de novo na tela. Gemini no Windows: o
`gemini.cmd` exige shell, então roda `node …/@google/gemini-cli/bundle/gemini.js` (mesma família do item 28).
175. **Gemini CLI: nem conta pessoal AI Pro/Ultra entra.** OAuth de conta pessoal encerrado em 18/06/2026; Code Assist
Standard/Enterprise sem assinatura nova desde 09/10/2026. Correção: chave do AI Studio ou o provedor `antigravity`
(conta Google; atenção aos termos, ver [ai.md](ai.md)). Complementa o 168. Onde: `doc/ia.md`.
176. **`/usage` no Git Bash vira caminho e a CLI cobra uma resposta normal.** Causa: o MSYS converte `/usage` em
`C:/Program Files/Git/usage`. Correção no terminal: `MSYS_NO_PATHCONV=1 claude -p "/usage"`. O painel chama sem shell
e não é afetado. `claude -p "/usage"` bem formado custa US$ 0 (`<synthetic>`). Onde: `panel/src/lib/ai-usage.ts`.
177. **`agy`: shell recusado em silêncio.** Só vale correspondência exata `command(<linha>)` em `--settings`; prefixo,
`command(node)`, `command(node:*)` e `command(node -e *)` não liberam. O que não está liberado vira passo `ERROR`
+ mensagem `jetski:` no stderr com **código de saída 0**: não confie no código, leia os eventos. Não use
`--dangerously-skip-permissions`. Onde: `antigravityArgs`/`normalizeAntigravity` em `panel/src/lib/agents.ts`.
178. **`codex app-server`: leitura de limites falha sem o handshake.** Ordem: `initialize` → notificação `initialized` →
pedido. `account/read` sem `params` dá "missing field `params`". Onde: `panel/src/lib/ai-usage.ts`.
179. **IA aparecia "pronta" sem estar.** Causa: último teste falhado por login/cota não tirava a IA da cadeia, e o Gemini
em modo conta contava como pronto sem teste. Correção: teste falho por indisponibilidade tira de `readyChain`;
Gemini em conta só depois de um teste que passou; "Testar" segue habilitado. Onde: `panel/src/lib/ai.ts`;
teste `ai.test.ts`.
Relacionadas, já registradas acima:
- Patch por script em arquivos CRLF do painel (`lib/metrics.ts`, `components/metrics-view.tsx`, `dashboard-controls.tsx`,
@@ -763,4 +884,4 @@ Relacionadas, já registradas acima:
- `codex.cmd` sem shell: item 28.
- Script de patch com regex (`\b`) passado por heredoc: item 44.
- Publicador roda sem `--reload`: mudança em `publisher/app/` só vale depois de reiniciar o `pnpm dev` (itens 137, 139, 140, 142, 143, 145 e 147; o Clipador também: 144).
- Migração do painel (v3 … v8) é aplicada na 1ª requisição depois da recarga do `db.ts`; reiniciar o `pnpm panel`/`pnpm dev` só se isso não bastar: itens 51 e 138 (reiniciar mata agente em execução: item 131).
- Migração do painel (v3 … v10) é aplicada na 1ª requisição depois da recarga do `db.ts`; reiniciar o `pnpm panel`/`pnpm dev` só se isso não bastar: itens 51 e 138 (reiniciar mata agente em execução: item 131).
+45 -12
View File
@@ -19,13 +19,15 @@ Fonte: código em `panel/src/lib/` e `panel/README.md`. O painel é do usuário:
(ex.: `CutSettingsDialog` de `clipper-cut-settings.tsx`). Não monte um segundo host.
- `Button` (`components/ui.tsx`) tipa as props como `ComponentProps<"button">` e aceita `ref` (React 19).
## Banco (`data/cenaforge.db`, esquema v7)
## Banco (`data/cenaforge.db`, esquema v10)
- Migração em `panel/src/lib/db.ts` (lista `MIGRATIONS`). Banco com dados → cópia em `data/backups/`
antes de migrar (`cenaforge-v<atual>-<data>.db`). `foreign_keys = OFF` fora da transação e `PRAGMA
foreign_key_check` antes do `COMMIT` de cada versão.
- v3: `account_channels` (conta ↔ canal de live do Clipador; `status` `active`/`ended`). O canal
vive em `data/clipper/clipper.db`, então não há chave estrangeira para ele.
- v9: `accounts.language` (idioma e público do canal de publicação; padrão `pt-BR`; opções em `ACCOUNT_LANGUAGES` de
`panel/src/lib/languages.ts`). A v8 (última leitura dos números das redes) não está descrita aqui: ver publishing.md.
- v4: reconstrói `stories` (SQLite não altera CHECK) para `kind` aceitar `'documentary'`; mesmas
colunas e ids.
- v5: publicação real — `publish_jobs`, `app_settings`, `clip_auto_approvals`; `account_networks` e `publications`
@@ -35,6 +37,7 @@ Fonte: código em `panel/src/lib/` e `panel/README.md`. O painel é do usuário:
- v6: reconstrói `publish_jobs` (ids preservados) com `schedule_source` (`auto`/`manual`/`now`) e `cancel_reason`
`unlinked`. Banco real em v6 (`PRAGMA user_version`, conferido em 17/11/2026, antes da v7).
- v7: `publish_jobs.origin` (`link`/`manual`, padrão `link`): job criado pelo botão "Publicar" do corte. Ver publishing.md.
- v10: `agent_runs.fallback_of` (execução que continuou outra que caiu por indisponibilidade; IA reserva — [ai.md](ai.md)).
- API: toda rota `/api/**` passa por `panel/src/proxy.ts` (Host local; escrita exige `Origin` do painel) e corpo por
`readJson` (415 sem `Content-Type: application/json`) — gotchas, item 125.
- A conexão fica em `globalThis.__cenaforgeDb`; a marca de módulo `checkedThisModule` faz a 1ª chamada de `db()` depois
@@ -248,7 +251,13 @@ Cada trecho vira um MP4 de desenho 2D montado por peças a partir do texto; pers
informando o formato (o subagente é uma casca que lê `doc/roteiro/`; sem WebSearch, fato sem fonte fica
"a confirmar"); no **Codex** manda ler os guias e escrever sozinho, sem usar `.claude/agents/` (mesma
regra no `AGENTS.md`).
- Lista de modelos = `models()` (não há mais constante fixa):
- **Quatro provedores** (`claude`, `codex`, `gemini`, `antigravity` — este começa desligado), configurados em **Configurações → IA** (`/settings/ai`: ligar/desligar,
conta ou chave de API, ordem da reserva, instalar, entrar, testar, uso do limite). **IA reserva:** agente que termina com erro de
indisponibilidade é pausado e a mesma tarefa recomeça na próxima IA pronta (`agent_runs.fallback_of`; o console segue
o `followUpRunId` também nesse caso; vertentes religadas à nova execução). Tarefa nova pula a IA acima do limite de uso (`overLimit`; não vale em retomada). Contrato, API e armadilhas em
[ai.md](ai.md). Configurações são subpáginas `/settings/{ai,publishing,apps,browser,modes}` (`/settings` → IA;
`SETTINGS_SECTIONS` em `settings-shell.tsx`, também no menu lateral); link antigo `/settings?tab=apps` não existe mais.
- Lista de modelos = `models()` (não há mais constante fixa; o Gemini usa `geminiModels()` de `lib/ai.ts`):
- Codex: lê `models_cache.json` de `$CODEX_HOME` (padrão `~/.codex`), que a CLI do Codex atualiza
sozinha; filtra `visibility === "list"`, ordena por `priority`. Primeira opção "Padrão da CLI (…)"
= `model = "..."` do `config.toml`. O id vai em `codex exec -m <slug>`. Em 17/11/2026: 8 modelos
@@ -266,8 +275,9 @@ Cada trecho vira um MP4 de desenho 2D montado por peças a partir do texto; pers
em `createStoryFromTextAction`, `app/actions.ts`). Por script: `POST /api/stories {text, title?, kind?, provider?,
model?}` (`app/api/stories/route.ts`; `kind` padrão `documentary`, texto 20–20.000 caracteres) cria a história + ep01
e dispara o agente `story` → `{storyId, episodeId, runId}` (cabeçalho `Origin`: gotchas, item 125).
- O agente roda dentro do processo do painel: reiniciar o `pnpm panel` o mata (gotchas, item 131). Limite de uso do
Claude/Codex para a tarefa no meio: continue no outro provedor com o contexto (item 132).
- O agente roda dentro do processo do painel: reiniciar o `pnpm panel` o mata (gotchas, item 131). Limite de uso no
meio da tarefa: com a reserva ligada o painel recomeça sozinho na próxima IA (item 132 vale só com a reserva
desligada ou sem outra IA pronta: continue à mão no outro provedor com o contexto).
- Prompt do Codex manda ler texto no PowerShell com `Get-Content -Raw -Encoding UTF8` (gotchas, item 98).
### Mensagem com o agente rodando
@@ -336,6 +346,29 @@ Limitação: o overlay da Godot só tem `choiceA`/`choiceB` (`scene_config.gd`);
## Página `/clipper` (Clipador)
Reformulada em 18/11/2026 (`doc/clipador/REDESIGN.md`): deixou de ser uma página com 5 abas e virou **subpáginas** no
grupo de rotas `panel/src/app/clipper/(studio)/`. O `layout.tsx` monta `ClipperProvider` (`clipper-provider.tsx`: dados +
consulta periódica; `useClipper()`) e `ClipperShell` (`clipper-shell.tsx`: cabeçalho compacto com estado do serviço,
bloco "Ao vivo agora · N" com uma linha por live, sub-navegação com contadores). Sub-navegação = `CLIPPER_SECTIONS`; a
sidebar (`sidebar-nav.tsx`) mostra os mesmos subitens quando o Clipador está ativo. Seção nova = entrada em
`CLIPPER_SECTIONS` + pasta em `(studio)/`.
| Rota | Conteúdo | Arquivos |
|---|---|---|
| `/clipper` Cortes | lista `ClipTable` (uma linha por corte; ações rápidas Aprovar/Rejeitar/Publicar), filtros na URL (`?stage ?source ?session ?lang`), modal `ClipDialog` por `?clip=ID` com anterior/próximo; em fonte inglesa, bloco "Em português" e título traduzido na lista ([clipper.md](clipper.md#fonte-em-inglês-18112026)); etiquetas e player **Final / Revisão** do vídeo final, **Mapa de expressões**, "O que falam" por falante, botão **Sem contexto** e veredito do juiz de contexto ([clipper-video.md](clipper-video.md), [clipper-ai-team.md](clipper-ai-team.md)) | `clipper-clips-page.tsx`, `clipper-clip-table.tsx`, `clipper-clip-dialog.tsx`, `clipper-clip-parts.tsx`; ordenar/apagar/selecionar em utilitários de `clipper-queue.tsx` |
| `/clipper/sessions` | lista de sessões; "Gravar pelo link" em diálogo (`RecordForm`) | `clipper-sessions-page.tsx` |
| `/clipper/sessions/[id]` | saúde, resumo da IA, tiles, gráfico do chat, emotes, configuração do corte | `clipper-session-detail.tsx` |
| `/clipper/sources` | fontes em tabela, "Adicionar fonte" em diálogo, monitor ligado/**pausado** + Religar, idioma da live, canais de publicação; coluna "Ao vivo" = "gravando #N" (sessão ativa) ou "ao vivo há X" apagado se a checagem tem > 10 min (gotchas, item 174) | `clipper-channels.tsx` |
| `/clipper/games` | jogos em tabela (nome, gênero, estado, missões, última pesquisa/edição), "Adicionar jogo" em diálogo, `?game=ID` abre o modal do jogo e emotes do canal | `clipper-games-page.tsx`, `clipper-game-dialog.tsx` (modal), `clipper-game-parts.tsx` (seções, `AiChat`, editor à mão), `clipper-games.tsx` |
| `/clipper/settings` | abas Juiz (IA) / Serviço / Idiomas e públicos; em Juiz, a **Equipe de IA** (um cartão por papel: provedor, modelo, raciocínio, instruções do administrador, mosaico/`timelineJson`) e a **Medição** ([clipper-ai-team.md](clipper-ai-team.md)) | `clipper-settings-page.tsx`, `clipper-judge.tsx`, `clipper-ai-team.tsx` |
| `/clipper/edit/[clipId]` | editor em tela cheia, **fora** do grupo `(studio)` | ver "Editor de cortes" |
`clipper-studio.tsx` foi **apagado**; `clipper-queue.tsx` virou só utilitários da lista (a lista é `ClipTable`);
`clipper-sessions.tsx` virou peças compartilhadas (`PlatformIcon`, `CutNow`, `RecordForm`, relógio, `sessionHealth`).
Canal de publicação: campo "Idioma e público" em `account-manager.tsx`; aviso de idioma em `clip-publish.tsx`.
Os parágrafos abaixo descrevem o comportamento de cada peça; onde falam em "aba", "cartão" ou "fila", leia "página",
"linha" e "lista de cortes" (a reescrita deles não foi verificada no navegador).
- `clipper-cut-settings.tsx`: modal "Configuração do corte" em cinco abas — Formato e duração (com a seção
"Qualidade da gravação" e o disco por hora de cada opção, de `captureQualities`) · Câmera e layout · Legenda (com
seletor de fonte) · Gancho (estilo, cores, fonte, animação de entrada, "Ver a entrada") · Crédito — com a prévia ao
@@ -345,7 +378,7 @@ Limitação: o overlay da Godot só tem `choiceA`/`choiceB` (`scene_config.gd`);
- `clipper-client.ts`: tipo `Aspect`, `format` em `CutSettings`, `aspect?` em `Clip`, `aspectOf()` (ausente =
vertical) e `withFormat()` (completa a resposta de um serviço antigo sem `format`). Na fila (`clipper-queue.tsx`)
o corte horizontal aparece em 16:9.
- Aba Sessões (`clipper-sessions.tsx`; cabeçalho em `clipper-studio.tsx`): cartão com cabeçalho (tempo gravado,
- Sessão (`clipper-sessions.tsx`, `clipper-session-detail.tsx`): cartão com cabeçalho (tempo gravado,
"gravando em L×A · fps" de `capture` e ações), frase de saúde (`sessionHealth()`), painel "o que está acontecendo" (resumo da IA + jogo), quatro blocos
(Chat, Transcrição, IA assistiu, Cortes) e barra de ferramentas. **Altura fixa por desenho**: nada pode pular na
atualização automática. "Retomar gravação" aparece em toda live que não está gravando (botão principal só em
@@ -358,12 +391,12 @@ Limitação: o overlay da Godot só tem `choiceA`/`choiceB` (`scene_config.gd`);
atrasou, "gerando o próximo resumo…". O intervalo vem de `/status` → `judge.options.scanIntervalS`
(`useScanInterval`; reserva 180 = `OPTION_DEFAULTS` de `intel.py`). Existe porque o dono achou que o resumo
travava (gotchas, item 115).
- `clipper-games.tsx`: aba Jogos e emotes. O card do jogo tem selo de iniciais (primeira + última palavra, cor
por `hueOf`) e os botões "Conversar com a IA", "Editar" e "Pesquisar de novo". Cada seção é um cartão com
barra colorida, contador e "Pedir à IA", que abre o chat inline `AiChat` (balões, atalhos de pedido por seção,
indicador de digitação, "+N itens novos / −N removidos"). Item novo fica verde com selo "novo". Gírias viram
chips, e Fontes e "Memória da IA" ficam recolhidas. A aba também mostra os emotes do canal com usos e peso.
Rotas e regras em [clipper.md](clipper.md#perfil-do-jogo-aba-jogos).
- Jogos (`clipper-games-page.tsx` + `clipper-game-dialog.tsx` + `clipper-game-parts.tsx`; `clipper-games.tsx` guarda
os emotes do canal): lista em tabela; o modal tem alternância **Português (você lê) / English (vai para a IA)** e abas
Visão geral · Rende corte · Missões · Gatilhos de fim · Termos e hashtags · Fontes · Pedidos à IA, com Pesquisar de
novo, Editar, Pedir à IA (`AiChat`: atalhos por seção, "+N itens novos / −N removidos") e Apagar. Editar grava no
idioma da alternância e o serviço traduz o outro. Rotas e regras em [clipper.md](clipper.md#perfil-do-jogo-aba-jogos).
- Sidebar: os subitens do Clipador usam os mesmos ícones das abas do topo (`sidebar-nav.tsx`, `SubItem.icon`).
- `clipper-queue.tsx`: cartão do corte mostra a análise do juiz e recua/avança o início (`START_STEPS`
−30/−10/−5/−2/+2 s). `clipper-judge.tsx`: modelos do editor e do analista, varredura, visão, câmera.
- **Ordenar a fila** (`clipper-queue.tsx`, seletor "Ordenar" ao lado do filtro de sessão; `QUEUE_SORTS`, `useQueueSort`):
@@ -523,4 +556,4 @@ Apagar na fila, relógio da sessão e prévia igual ao render (17/11/2026): `npx
(reconferido pela skill). Informado pelo coordenador: porte da legenda em 22 conferências contra o Python; corte 61
montado no editor e renderizado pelo serviço com enquadramento, inserção e legenda iguais à prévia em
2/3,5/5/6,5/8 s. Não verificado: apagar pela UI contra o serviço real; relógio com movimento reduzido, aba escondida
e larguras de 1024/1280; a faixa do topo de `clipper-studio.tsx` ainda usa o `durationS` real.
e larguras de 1024/1280; a faixa do topo (hoje `clipper-shell.tsx`) pode ainda usar o `durationS` real.
@@ -74,6 +74,9 @@ No texto visível do Clipador "Canais" virou **"Fontes"**; código, tabelas e ro
- Encerrar fonte/história cancela os jobs não enviados (`unlinked`); religar zera `linked_at` (a automática não pega
cortes do intervalo desligado). Cancelar no meio de um ciclo vale (UPDATEs condicionais; se o Publicador já criou o
envio, o painel cancela lá). Aprovação automática é registrada em `clip_auto_approvals` antes do PATCH no Clipador.
- **Só o vídeo FINAL sai** (18/11/2026): corte de fonte com camadas de teste (tradução, dublagem) tem um vídeo de revisão e, ao
aprovar, um final sem elas. `clipPublishFile` (`publishing-rules.ts`) devolve `publishFile` ou o motivo de esperar; `sendDue`
relê o corte e deixa o job em "Esperando o vídeo final…" até estar pronto; nunca use `file`. Detalhes: [clipper-video.md](clipper-video.md), gotchas 180.
- **Botão "Publicar" do corte** (`POST /api/publishing/clips/<id>`, corpo `{accountId, platforms[], timing?: "now"|"best_slot"}`,
resposta `{jobs, skipped[{platform, reason}], placed}`; `publishClip`; `timing` também aceita `"at"`, ver abaixo): serve para corte aprovado cuja fonte **não** está
ligada a canal (`account_channels`) ou para outra rede. O clique é a aprovação humana. `timing` omitido = o do canal.
+7 -4
View File
@@ -21,9 +21,9 @@ prévia e registre aqui (via `cenaforge-skill-updater`).
| Next.js / React / Tailwind | 16.4.6 / 19.3.0 / 4.3.3 | painel (`panel/`) | dependências do workspace | 16/11/2026 |
| @xyflow/react | 13.0.1 | árvore de vertentes na aba Fluxo (`panel/src/components/story-flow.tsx`) | dependência do painel | 16/11/2026 |
| SQLite | `node:sqlite` (Node 24) | banco do painel, sem dependência nativa | embutido | 16/11/2026 |
| Codex CLI | 0.169.0 (`@openai/codex`) | agente no painel (`codex exec --json -m <slug>`, sandbox `workspace-write`); modelos lidos de `~/.codex/models_cache.json` (panel.md, "Agentes e modelos") | `CODEX_BIN` → `.exe` no PATH → `codex.js` ao lado do `codex.cmd` do npm | 17/11/2026 |
| Codex CLI | 0.169.0 (`@openai/codex`) | agente no painel (`codex exec --json -m <slug>`, sandbox `workspace-write`); modelos lidos de `~/.codex/models_cache.json` (panel.md, "Agentes e modelos") | `CODEX_BIN` → `.exe` no PATH → `codex.js` ao lado do `codex.cmd` do npm | 17/11/2026 (`--version` reconferido em 18/11/2026) |
| API do Wikimedia Commons (`commons.wikimedia.org/w/api.php`) | sem versão (HTTP público, sem chave; User-Agent genérico) | fotos reais por trecho na montagem documental (`panel/src/lib/image-search.ts`), com autor, licença e página de origem nos créditos | chamada direta do painel | 17/11/2026 (`ep01.montage.json`: 5 fotos do Commons com licença CC registrada; MP4 de 88,3 s; licença não conferida na página de cada foto) |
| Claude Code CLI | 2.1.314 | agente chamado pelo painel (`-p`, `stream-json`, `--resume`, `--model claude-*-5-5`/`claude-fable-5-2`) | `CLAUDE_BIN` → `PATH` (`claude.exe`) | 17/11/2026 |
| Claude Code CLI | 2.1.314 | agente chamado pelo painel (`-p`, `stream-json`, `--resume`, `--model claude-*-5-5`/`claude-fable-5-2`) | `CLAUDE_BIN` → `PATH` (`claude.exe`) → `~/.local/bin` | 17/11/2026 (`--version` reconferido em 18/11/2026) |
Estilo Cartoon (`cartoon/`, 17/11/2026; contrato e uso em [cartoon.md](cartoon.md)):
@@ -35,8 +35,8 @@ Estilo Cartoon (`cartoon/`, 17/11/2026; contrato e uso em [cartoon.md](cartoon.m
| Fontes Anton e Bebas Neue | `assets/fonts/` (`publicDir` = `assets`) | texto das etiquetas e legenda | ver licenças em "Clipador" |
Licença da Remotion: grátis para pessoa física e empresa pequena; empresa maior paga. **Conferir os termos antes de uso
comercial** (não verificado aqui). Testes: `npx tsx --test tests/*.test.ts` em `cartoon/` (5 testes de `spec.test.ts`);
painel: `montage-cartoon.test.ts` (9). Cartoon 5/5 reexecutado em 17/11/2026; painel 77/77 informado pelo dono.
comercial** (não verificado aqui). Testes: `npx tsx --test tests/*.test.ts` em `cartoon/` (5 de `spec.test.ts` + 11 de `motion.test.ts`);
painel: `montage-cartoon.test.ts` (10). Cartoon 16/16 reexecutado em 17/11/2026; painel 78/78 informado pelo dono.
Hardware do teste de referência: i9-13900K, 64 GB, RTX 2060 SUPER. Tempos: prévia 540×960
42–44 s; final 1080×1920 ~160 s. A etapa de render da Godot ocupa 94–96% do total, dominada
@@ -142,6 +142,7 @@ no `clipper/.venv` em 16/11/2026 (`importlib.metadata`). Evidência (`doc/FACE_B
| mediapipe (Face Landmarker `face_landmarker.task` float16/1) | 1.2.3 | Apache-2.0 | 478 pontos + 52 blendshapes; 5–7 ms/quadro na bancada; bloco de 30 s em 1,71 s ao vivo (com gravação + transcrição juntas) |
| opencv-contrib-python (`cv2.FaceDetectorYN`) + YuNet `face_detection_yunet_2026may.onnx` | 5.0.0.93 (`cv2` 5.0.0) | Apache-2.0 / MIT (peso) | acha a câmera pelo rosto no quadro inteiro (piso de confiança 0,7: gotchas, item 92). Sem `opencv-python-headless` junto (gotchas, item 80) |
| numpy | 2.5.5 | BSD | séries e recorte |
| onnxruntime + WeSpeaker ResNet34-LM `wespeaker_voxceleb_resnet34_LM.onnx` (`wespeaker_r34` no lock, commit `f0c48c2…`) | 1.32.0 (onnxruntime reconferido em 18/11/2026) | CC-BY-4.0 (pesos; atribuição "WeSpeaker, wenet-e2e") | impressão de voz: quem fala cada palavra (streamer × `otherN`); 0,19 s de CPU por bloco de 30 s. Medido em `doc/clipador/FALANTES.md` (sessão 15, informado; **não reexecutado** aqui). Quadro: [clipper-video.md](clipper-video.md) |
| onnxruntime + OpenSeeFace `osf_lm_model3_opt.onnx` / `osf_mnv3_detection_opt.onnx` | 1.32.0 | MIT / BSD-2-Clause (pesos) | plano B (só posição, sem expressões; sem linha de rosto ao analista). Pesos reais no `face.py` em 17/11/2026: rosto 96,7–100 %, 12,3–13,9 ms/quadro (MediaPipe no mesmo trecho: 94,4–100 %, 9,8–13,2) |
Pesos fixados em `clipper/models.lock.json` (commit/caminho versionado + sha256), baixados em `data/clipper/models/`.
@@ -168,6 +169,8 @@ segurança).
| Ferramenta | Para quê | Situação |
|---|---|---|
| Gemini CLI (`@google/gemini-cli`) | terceiro provedor de IA (agentes do painel e juiz do Clipador; [ai.md](ai.md)) | **código pronto, nunca executado de verdade**: não instalado nesta máquina (18/11/2026, `gemini: command not found`); a versão 0.68.0 do contrato (`doc/ia.md`) vem de teste do dono e não foi reverificada aqui. Coberto só por testes sem CLI (`ai.test.ts`, `test_ai_fallback.py`). OAuth gratuito de conta pessoal encerrado (gotchas, item 168); uso real exige chave do AI Studio, ainda não testada. Passa a "Em uso" depois de uma tarefa real concluída por ele |
| Antigravity CLI (`agy`) | 4º provedor de IA, só agentes do painel (conta Google; substituto do Gemini CLI; [ai.md](ai.md)) | **candidata, desligada por padrão**: `agy` 1.5.10 em `~/.gemini/bin` (verificado em 18/11/2026). Testes informados: "Testar" respondeu "ok" em 15 s; leitura de uso 12%/5%; o painel chamou `-p` sem terminal. Nenhuma tarefa real de vídeo/história concluída por ele. Termos do Google: embrulhar o `agy` em app de terceiro "não é suportado" em planos pessoais (decisão do usuário). Juiz do Clipador não usa. Gotchas 177 |
| Meshy | gerar modelos GLB (personagens, objetos) e rig | citada na especificação; não testada |
| Mixamo | animações para personagens com rig | citada como não obrigatória; não testada |
| `.glb` carregado por `GLTFDocument` em tempo de execução (Godot) | modelos prontos dentro de cenas da biblioteca (`library/<id>/assets/`) | **só documentado** em `doc/godot/cenas.md`; nenhum `.glb` no repositório nem render com ele (17/11/2026). Personagens e barcos atuais são procedurais (`godot/kits/`) |
+3
View File
@@ -45,3 +45,6 @@ voice/vendor/
# Publicador: venv local
publisher/.venv/
# Worktrees temporárias dos subagentes do Claude Code
.claude/worktrees/
@@ -0,0 +1,109 @@
# Tarefa: subir o personagem cartoon (corpo e MÃOS) ao nível de uma ilustração de referência
Você vai trabalhar num **workspace isolado** (pasta `workspace/` deste pacote), sem acesso ao projeto
original. Responda e comente em **português do Brasil**; nomes de código (variáveis, funções, tipos,
arquivos) em **inglês**.
## Contexto
Temos um gerador de vídeos curtos verticais (9:16) em estilo "cartoon explicativo". Cada personagem é um
**componente React que desenha SVG puro** (`workspace/src/CharacterFigure.tsx`). Ele não é uma imagem pronta:
é montado por peças a partir de uma ficha de aparência (`CharacterLook`, em `src/character.ts`) e animado por
um **rig** de parâmetros contínuos (`src/rig.ts`: rosto `FaceParams` e corpo `BodyParams`, braços e pernas em
dois segmentos). As poses e ações (`src/motion.ts`) mexem nesses parâmetros quadro a quadro, e a boca segue a
fala (`src/lipsync.ts`). O vídeo final é renderizado quadro a quadro pela Remotion (Chrome headless), então
**tudo precisa ser função pura dos parâmetros** (nada de aleatório sem semente, nada de relógio).
O mesmo personagem aparece em close (só rosto e tronco), meio corpo e corpo inteiro, de frente para a câmera.
## Referência (o NÍVEL de acabamento que queremos)
Pasta `referencia/`: quadros de um vídeo de outra série (1080×1920) e recortes ampliados em
`referencia/recortes/` (mãos segurando, joinha, mão com prancheta, apontando, close de mãos, braços cruzados,
rosto). `00-video-inteiro-…png` mostra o vídeo todo.
**Copie a qualidade, não o conteúdo.** Não reproduza aqueles personagens, nomes, roupas, logotipos ou cenas.
O que importa nelas:
- **Proporção:** cabeça grande (≈ 1/3 da altura no corpo inteiro), pescoço visível e proporcional, ombros
largos e arredondados, tronco em "pera".
- **Sombreado cel em 2 tons**, luz de um lado só, sombra levemente fria, **sem contorno preto** (a borda é o
tom mais escuro da própria cor).
- **Rosto:** orelha com dobra interna; nariz como curva simples; rugas da testa como arcos suaves no tom da
pele; sobrancelha como forma cheia; pálpebra pesada; olhos com esclera branca; óculos de aro grosso com
reflexo.
- **Roupa com construção:** gola, zíper ou botões, costuras, 2–3 dobras (manga, cotovelo, barriga), barra;
pano pendurado (toalha) com dobras e sombra própria.
- **MÃOS (o problema principal):** formas macias e orgânicas, dedos de comprimentos diferentes que afinam na
ponta, nós em arco, polegar nascendo da base da palma, unhas visíveis quando a vista mostra, mão grande
(≈ do nariz ao queixo). Segurando objeto: o polegar por cima e os dedos por trás (objeto entre as camadas da
mão). Objeto largo (livro, camisa dobrada) com as duas mãos pelas bordas. Joinha com o punho de lado e os
dedos dobrados em fileira. A **mão sai de dentro da manga**: a manga termina numa borda com espessura e
abertura escura, o pulso afina e entra nela, e a manga faz sombra no pulso.
## Onde estamos (pasta `nosso/`)
- `01-folha-antes.png` → `02-folha-atual.png`: em cima a referência, embaixo o nosso, nos mesmos 6
enquadramentos. Melhoramos muito, mas um olhar rápido ainda separa os dois.
- `03-maos-ref-antes-depois.png`, `04-formas-de-mao-3-rotacoes.png`: estado atual das mãos (biblioteca
`src/hands.tsx` com formas `relaxed`, `open`, `point`, `thumbs_up`, `grip`, `pinch_edge`, `pinch_low`,
`fist`, `on_face`, giradas pelo pulso).
- `05-poses-camadas.png`: a ordem das camadas do braço (`src/limbs.ts`, `armLayer`) para a mão nunca sumir
atrás do corpo.
- `08-folha-de-poses-do-workspace.png`: saída do script deste workspace (12 poses).
O que o dono do projeto ainda reprova:
1. **Mãos** ainda parecem recortadas/coladas: formas duras, sombra em cunha, dedos "salsicha". Exemplos na
folha 08:
- braços cruzados viram um losango de dedos;
- no apontar, a mão some;
- o martelo e o ramo atravessam a túnica, e o cabo não fica claramente dentro do punho;
- no pensar e no tapar a boca, a mão parece um bloco.
2. A **emenda pulso → manga** às vezes mostra corte ou degrau quando o braço gira.
3. O **corpo inteiro** ainda parece "boneco de recorte" perto da referência:
- pouco volume na roupa;
- pernas e braços muito retos;
- sapato simples;
- sobrancelhas claras viram mancha (veja o idoso de barba branca).
4. Falta **textura de ilustração**: a referência tem degradê suave dentro das áreas e um leve granulado. A
sombra cel deve continuar, mas com transição menos "vetor de ícone".
## O que fazer
1. Estude a referência (abra as imagens) e liste, por item acima, o que muda no desenho.
2. Reescreva o que precisar em `src/CharacterFigure.tsx`, `src/hands.tsx` e `src/limbs.ts` (e, se
necessário, presets de pose em `src/rig.ts`) para chegar ao nível da referência. Pode criar arquivos novos
em `src/`.
3. Use `npx tsx render-sheet.tsx` (corpo inteiro) e `npx tsx render-sheet.tsx close` (close) para gerar
`out/sheet-*.svg`/`.png` e **olhe as imagens a cada rodada**. Acrescente poses ao `CELLS` do script se
precisar (ex.: apontar para o outro lado, acenar com a outra mão, mãos na cintura, segurando celular).
4. Pare quando, lado a lado com os recortes da referência, a mão e o corpo não se separarem pela qualidade do
desenho.
### Regras que NÃO podem quebrar (o projeto real depende delas)
- **Mesma interface pública:**
- `CharacterFigure({ look, expression?, pose?, item?, t?, state?, shadeSide?, gesture? })`;
- viewBox `0 0 200 440` com os pés em (100, 440);
- `HandsInsert({ look, item?, t?, shadeSide? })` desenha o close de mãos num viewBox 1080×1080.
- **Tipos e campos:** `CharacterLook`, `FaceParams`, `BodyParams` e os nomes de poses e expressões continuam
existindo. Campo novo só **opcional**, porque personagens já salvos precisam continuar abrindo.
- **Rig:** o desenho continua dirigido pelo rig. Expressões, poses, fala (boca) e movimento (andar, acenar,
martelar, pular, sentar) precisam funcionar; a sombra acompanha a cabeça virando (`headTurn`) e as dobras
acompanham o braço.
- **Sem dependências novas no desenho:** só React e SVG, sem imagens rasterizadas e sem bibliotecas novas.
- **Sem custo alto de render:** nada de `feGaussianBlur` ou filtros SVG pesados repetidos por quadro (o vídeo
renderiza 30 quadros por segundo; hoje um trecho de 4 s leva ~4 s). Degradê linear ou radial e textura
barata são aceitos.
- **Função pura e camadas:**
- nada de `Math.random()` nem relógio; mesmos parâmetros = mesmo desenho;
- braço, mão e objeto na mão nunca somem atrás do tronco, da barba ou de acessório quando o personagem está
de frente; mantenha a lógica de `armLayer` (ou melhore-a).
## Entrega
- A pasta `workspace/src/` com os arquivos alterados ou novos (vou copiá-los de volta para o projeto).
- `out/sheet-full.png` e `out/sheet-close.png` finais, e uma folha **referência × seu resultado** (os recortes
da referência ao lado das mesmas situações no seu desenho).
- Um resumo curto: o que mudou em cada arquivo, campos novos (se houver) e o que ainda não ficou igual.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 621 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 709 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 497 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 843 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 867 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 689 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 930 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 899 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 333 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 180 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 241 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 342 KiB

@@ -0,0 +1,16 @@
# Workspace isolado do personagem cartoon
Cópia mínima do desenho do personagem do CenaForge (`src/`), sem Remotion e sem o resto do projeto.
`src/spec.ts` aqui é uma versão reduzida, só com os tipos que o desenho usa.
```sh
npm install
npx tsx render-sheet.tsx # out/sheet-full.svg + out/sheet-full.png (12 poses, corpo inteiro)
npx tsx render-sheet.tsx close # out/sheet-close.svg + .png (rosto e tronco ampliados)
npx tsc --noEmit # tipos
```
O PNG sai pelo `@resvg/resvg-js`. Se ele não instalar, abra o `.svg` no navegador ou converta com um Chrome
headless: `chrome --headless --screenshot=out.png --window-size=2160,1520 file:///.../out/sheet-full.svg`.
A tarefa está em `../PROMPT.md`.
Binary file not shown.

After

Width:  |  Height:  |  Size: 967 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 788 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 465 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 873 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 465 KiB

@@ -0,0 +1,847 @@
{
"name": "cenaforge-personagem-sandbox",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cenaforge-personagem-sandbox",
"dependencies": {
"react": "19.3.0",
"react-dom": "19.3.0"
},
"devDependencies": {
"@resvg/resvg-js": "2.6.2",
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"tsx": "4.23.15",
"typescript": "5.9.3"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
"integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
"integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
"integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
"integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
"integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
"integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
"integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
"integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
"integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
"integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
"integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
"integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
"integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
"integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
"integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
"integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
"integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
"integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
"integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
"integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
"integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
"integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
"integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
"integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
"integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
"integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@resvg/resvg-js": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js/-/resvg-js-2.6.2.tgz",
"integrity": "sha512-xBaJish5OeGmniDj9cW5PRa/PtmuVU3ziqrbr5xJj901ZDN4TosrVaNZpEiLZAxdfnhAe7uQ7QFWfjPe9d9K2Q==",
"dev": true,
"license": "MPL-2.0",
"engines": {
"node": ">= 10"
},
"optionalDependencies": {
"@resvg/resvg-js-android-arm-eabi": "2.6.2",
"@resvg/resvg-js-android-arm64": "2.6.2",
"@resvg/resvg-js-darwin-arm64": "2.6.2",
"@resvg/resvg-js-darwin-x64": "2.6.2",
"@resvg/resvg-js-linux-arm-gnueabihf": "2.6.2",
"@resvg/resvg-js-linux-arm64-gnu": "2.6.2",
"@resvg/resvg-js-linux-arm64-musl": "2.6.2",
"@resvg/resvg-js-linux-x64-gnu": "2.6.2",
"@resvg/resvg-js-linux-x64-musl": "2.6.2",
"@resvg/resvg-js-win32-arm64-msvc": "2.6.2",
"@resvg/resvg-js-win32-ia32-msvc": "2.6.2",
"@resvg/resvg-js-win32-x64-msvc": "2.6.2"
}
},
"node_modules/@resvg/resvg-js-android-arm-eabi": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-android-arm-eabi/-/resvg-js-android-arm-eabi-2.6.2.tgz",
"integrity": "sha512-FrJibrAk6v29eabIPgcTUMPXiEz8ssrAk7TXxsiZzww9UTQ1Z5KAbFJs+Z0Ez+VZTYgnE5IQJqBcoSiMebtPHA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MPL-2.0",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-android-arm64": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-android-arm64/-/resvg-js-android-arm64-2.6.2.tgz",
"integrity": "sha512-VcOKezEhm2VqzXpcIJoITuvUS/fcjIw5NA/w3tjzWyzmvoCdd+QXIqy3FBGulWdClvp4g+IfUemigrkLThSjAQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MPL-2.0",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-darwin-arm64": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-darwin-arm64/-/resvg-js-darwin-arm64-2.6.2.tgz",
"integrity": "sha512-nmok2LnAd6nLUKI16aEB9ydMC6Lidiiq2m1nEBDR1LaaP7FGs4AJ90qDraxX+CWlVuRlvNjyYJTNv8qFjtL9+A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MPL-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-darwin-x64": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-darwin-x64/-/resvg-js-darwin-x64-2.6.2.tgz",
"integrity": "sha512-GInyZLjgWDfsVT6+SHxQVRwNzV0AuA1uqGsOAW+0th56J7Nh6bHHKXHBWzUrihxMetcFDmQMAX1tZ1fZDYSRsw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MPL-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-linux-arm-gnueabihf": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-linux-arm-gnueabihf/-/resvg-js-linux-arm-gnueabihf-2.6.2.tgz",
"integrity": "sha512-YIV3u/R9zJbpqTTNwTZM5/ocWetDKGsro0SWp70eGEM9eV2MerWyBRZnQIgzU3YBnSBQ1RcxRZvY/UxwESfZIw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-linux-arm64-gnu": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-linux-arm64-gnu/-/resvg-js-linux-arm64-gnu-2.6.2.tgz",
"integrity": "sha512-zc2BlJSim7YR4FZDQ8OUoJg5holYzdiYMeobb9pJuGDidGL9KZUv7SbiD4E8oZogtYY42UZEap7dqkkYuA91pg==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-linux-arm64-musl": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-linux-arm64-musl/-/resvg-js-linux-arm64-musl-2.6.2.tgz",
"integrity": "sha512-3h3dLPWNgSsD4lQBJPb4f+kvdOSJHa5PjTYVsWHxLUzH4IFTJUAnmuWpw4KqyQ3NA5QCyhw4TWgxk3jRkQxEKg==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-linux-x64-gnu": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-linux-x64-gnu/-/resvg-js-linux-x64-gnu-2.6.2.tgz",
"integrity": "sha512-IVUe+ckIerA7xMZ50duAZzwf1U7khQe2E0QpUxu5MBJNao5RqC0zwV/Zm965vw6D3gGFUl7j4m+oJjubBVoftw==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-linux-x64-musl": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-linux-x64-musl/-/resvg-js-linux-x64-musl-2.6.2.tgz",
"integrity": "sha512-UOf83vqTzoYQO9SZ0fPl2ZIFtNIz/Rr/y+7X8XRX1ZnBYsQ/tTb+cj9TE+KHOdmlTFBxhYzVkP2lRByCzqi4jQ==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-win32-arm64-msvc": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-win32-arm64-msvc/-/resvg-js-win32-arm64-msvc-2.6.2.tgz",
"integrity": "sha512-7C/RSgCa+7vqZ7qAbItfiaAWhyRSoD4l4BQAbVDqRRsRgY+S+hgS3in0Rxr7IorKUpGE69X48q6/nOAuTJQxeQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MPL-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-win32-ia32-msvc": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-win32-ia32-msvc/-/resvg-js-win32-ia32-msvc-2.6.2.tgz",
"integrity": "sha512-har4aPAlvjnLcil40AC77YDIk6loMawuJwFINEM7n0pZviwMkMvjb2W5ZirsNOZY4aDbo5tLx0wNMREp5Brk+w==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MPL-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@resvg/resvg-js-win32-x64-msvc": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js-win32-x64-msvc/-/resvg-js-win32-x64-msvc-2.6.2.tgz",
"integrity": "sha512-ZXtYhtUr5SSaBrUDq7DiyjOFJqBVL/dOBN7N/qmi/pO0IgiWW/f/ue3nbvu9joWE5aAKDoIzy/CxsY0suwGosQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MPL-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@types/react": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
"integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
"dev": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
}
},
"node_modules/@types/react-dom": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
"integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^19.3.0"
}
},
"node_modules/csstype": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz",
"integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==",
"dev": true,
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
"integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.2",
"@esbuild/android-arm": "0.28.2",
"@esbuild/android-arm64": "0.28.2",
"@esbuild/android-x64": "0.28.2",
"@esbuild/darwin-arm64": "0.28.2",
"@esbuild/darwin-x64": "0.28.2",
"@esbuild/freebsd-arm64": "0.28.2",
"@esbuild/freebsd-x64": "0.28.2",
"@esbuild/linux-arm": "0.28.2",
"@esbuild/linux-arm64": "0.28.2",
"@esbuild/linux-ia32": "0.28.2",
"@esbuild/linux-loong64": "0.28.2",
"@esbuild/linux-mips64el": "0.28.2",
"@esbuild/linux-ppc64": "0.28.2",
"@esbuild/linux-riscv64": "0.28.2",
"@esbuild/linux-s390x": "0.28.2",
"@esbuild/linux-x64": "0.28.2",
"@esbuild/netbsd-arm64": "0.28.2",
"@esbuild/netbsd-x64": "0.28.2",
"@esbuild/openbsd-arm64": "0.28.2",
"@esbuild/openbsd-x64": "0.28.2",
"@esbuild/openharmony-arm64": "0.28.2",
"@esbuild/sunos-x64": "0.28.2",
"@esbuild/win32-arm64": "0.28.2",
"@esbuild/win32-ia32": "0.28.2",
"@esbuild/win32-x64": "0.28.2"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/react": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz",
"integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-dom": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz",
"integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==",
"license": "MIT",
"dependencies": {
"scheduler": "^0.28.0"
},
"peerDependencies": {
"react": "^19.3.0"
}
},
"node_modules/scheduler": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
"integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",
"license": "MIT"
},
"node_modules/tsx": {
"version": "4.23.15",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz",
"integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.28.0"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
}
@@ -0,0 +1,21 @@
{
"name": "cenaforge-personagem-sandbox",
"private": true,
"type": "module",
"scripts": {
"sheet": "tsx render-sheet.tsx",
"sheet:close": "tsx render-sheet.tsx close",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"react": "19.3.0",
"react-dom": "19.3.0"
},
"devDependencies": {
"@resvg/resvg-js": "2.6.2",
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"tsx": "4.23.15",
"typescript": "5.9.3"
}
}
@@ -0,0 +1,242 @@
// Folha de conferência do personagem, SEM Remotion: renderiza o mesmo componente do projeto (CharacterFigure / HandsInsert)
// em várias poses/expressões/objetos e grava out/sheet-full.png, out/sheet-close.png e out/referencia-vs-resultado.png.
//
// npm install
// npx tsx render-sheet.tsx → out/sheet-full.svg + .png (e out/referencia-vs-resultado.png)
// npx tsx render-sheet.tsx close → só o close (rosto + tronco + mãos), como no vídeo
// npx tsx render-sheet.tsx compare → folha referência × resultado lado a lado
import fs from "node:fs";
import path from "node:path";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { CharacterFigure, HandsInsert } from "./src/CharacterFigure";
import type { CharacterLook } from "./src/character";
import type { IconId } from "./src/spec";
// Personagens de teste (genéricos; não são da série de referência).
const OLD: CharacterLook = {
build: "average", height: 0.95, skin: "#e0a77a", hair: { style: "bald", color: "#9a9aa2" }, beard: { style: "mustache", color: "#8e8e96" },
glasses: "square", brows: "thick", top: { style: "jacket", color: "#4f7a4a", accent: "#e9ecef" }, bottom: { style: "pants", color: "#2c3346" },
shoes: "#2a2a30", head: "wide", nose: "curve", lids: 0.45, wrinkles: 0.6, accessories: ["towel"],
};
const COACH: CharacterLook = {
build: "heavy", height: 0.98, skin: "#d9a27a", hair: { style: "short", color: "#5a4a3a" }, beard: { style: "mustache", color: "#4a3a2a" },
glasses: "none", brows: "thick", top: { style: "jacket", color: "#22335e", accent: "#e8b13a" }, bottom: { style: "pants", color: "#22335e" },
shoes: "#f2f2f2", head: "round", nose: "round", lids: 0.15, wrinkles: 0.3, belly: true, accessories: ["whistle"],
};
const NOAH: CharacterLook = {
build: "slim", height: 0.96, skin: "#c98a5e", hair: { style: "long", color: "#e2e2e8" }, beard: { style: "long", color: "#eeeef2" },
glasses: "none", brows: "thick", top: { style: "robe", color: "#a8865a", accent: "#6b4a2a" }, bottom: { style: "pants", color: "#5a4a3a" },
shoes: "#6b4a2a", footwear: "sandals", head: "oval", nose: "long", lids: 0.5, wrinkles: 0.85,
};
const WORKER: CharacterLook = {
build: "average", height: 0.98, skin: "#dfa678", hair: { style: "short", color: "#4e3829" }, beard: { style: "full", color: "#78604c" },
glasses: "none", brows: "thick", top: { style: "shirt", color: "#6e6545" }, bottom: { style: "pants", color: "#34465e" },
shoes: "#423127", head: "round", nose: "curve", lids: 0.35, wrinkles: 0.25,
};
const MECHANIC: CharacterLook = {
build: "average", height: 0.97, skin: "#e2a878", hair: { style: "short", color: "#4a3525" }, beard: { style: "mustache", color: "#4a3525" },
glasses: "none", brows: "thick", top: { style: "shirt", color: "#687a52" }, bottom: { style: "pants", color: "#3b4c5e" },
shoes: "#4a372b", head: "round", nose: "round", lids: 0.2, wrinkles: 0.2,
};
type Cell = { look: CharacterLook; label: string; expression?: string; pose?: string; item?: IconId; gesture?: "thumbs_up" };
const CELLS: Cell[] = [
{ look: OLD, label: "stand / relaxed", pose: "stand", expression: "smile" },
{ look: OLD, label: "hold book (2 mãos)", pose: "hold", item: "book", expression: "smile" },
{ look: COACH, label: "thumbs up", pose: "thumbs_up", gesture: "thumbs_up", expression: "happy" },
{ look: COACH, label: "hold ruler (1 mão)", pose: "hold", item: "ruler", expression: "laugh" },
{ look: OLD, label: "point", pose: "point", expression: "surprised" },
{ look: OLD, label: "wave", pose: "wave", expression: "happy" },
{ look: COACH, label: "cross_arms", pose: "cross_arms", expression: "suspicious" },
{ look: OLD, label: "think", pose: "think", expression: "confused" },
{ look: OLD, label: "cover_mouth", pose: "cover_mouth", expression: "shocked" },
{ look: NOAH, label: "hold hammer", pose: "hold", item: "hammer", expression: "determined" },
{ look: NOAH, label: "hold olive", pose: "hold", item: "olive", expression: "smile" },
{ look: NOAH, label: "celebrate", pose: "celebrate", expression: "laugh" },
{ look: MECHANIC, label: "point (manga curta)", pose: "point", expression: "happy" },
{ look: WORKER, label: "cross_arms (manga curta)", pose: "cross_arms", expression: "sad" },
{ look: MECHANIC, label: "hands_on_hips", pose: "hands_on_hips", expression: "proud" },
{ look: WORKER, label: "hold phone", pose: "hold", item: "phone", expression: "neutral" },
{ look: OLD, label: "shrug", pose: "shrug", expression: "confused" },
{ look: WORKER, label: "facepalm", pose: "facepalm", expression: "sad" },
];
const Fig = CharacterFigure as unknown as React.FC<Record<string, unknown>>;
const Insert = HandsInsert as unknown as React.FC<Record<string, unknown>>;
function renderPoseSheet(mode: "full" | "close") {
const cw = 360, ch = mode === "close" ? 580 : 760, cols = 6;
const rows = Math.ceil(CELLS.length / cols);
const W = cw * cols, H = ch * rows;
const sheet = (
<svg xmlns="http://www.w3.org/2000/svg" viewBox={`0 0 ${W} ${H}`} width={W} height={H}>
<rect width={W} height={H} fill="#8f9bb3" />
{CELLS.map((c, i) => {
const x = (i % cols) * cw, y = Math.floor(i / cols) * ch;
const fw = mode === "close" ? 400 : 330, fh = fw * 2.2;
const fx = x + (cw - fw) / 2, fy = mode === "close" ? y - 42 : y + ch - fh - 10;
const cid = `cell${mode}${i}`;
return (
<g key={i}>
<defs>
<clipPath id={cid}>
<rect x={x + 4} y={y + 4} width={cw - 8} height={ch - 8} rx={14} />
</clipPath>
</defs>
<rect x={x + 4} y={y + 4} width={cw - 8} height={ch - 8} rx={14} fill={i % 2 ? "#a3adc2" : "#97a3ba"} />
<g clipPath={`url(#${cid})`}>
<svg x={fx} y={fy} width={fw} height={fh} viewBox="0 0 200 440" overflow="hidden">
<Fig look={c.look} expression={c.expression} pose={c.pose} item={c.item} gesture={c.gesture} t={0.6} />
</svg>
</g>
<text x={x + 16} y={y + 34} fontSize={22} fontFamily="Arial" fontWeight={700} fill="#1b1d26">{c.label}</text>
</g>
);
})}
</svg>
);
return { svg: renderToStaticMarkup(sheet), W };
}
function renderCompareSheet() {
const refDir = path.resolve("..", "referencia", "recortes");
const loadRef = (name: string) => {
const p = path.join(refDir, name);
if (!fs.existsSync(p)) return "";
return `data:image/png;base64,${fs.readFileSync(p).toString("base64")}`;
};
// Enquadra nosso SVG (viewBox 0 0 200 440) na mesma janela de recorte usando um `<g transform="translate(...) scale(...)">`.
const cropFig = (boxW: number, boxH: number, cx: number, cy: number, span: number, node: React.ReactNode) => {
const k = boxW / span;
const tx = boxW / 2 - cx * k;
const ty = boxH / 2 - cy * k;
return (
<g transform={`translate(${tx} ${ty}) scale(${k})`}>
<svg width={200} height={440} viewBox="0 0 200 440" overflow="visible">{node}</svg>
</g>
);
};
const items: {
title: string;
refFile: string;
bg: string;
renderOur: (w: number, h: number) => React.ReactNode;
}[] = [
{
title: "1. Rosto (close)",
refFile: "rosto-close.png",
bg: "#1e2742",
renderOur: (w, h) => cropFig(w, h, 100, 148, 138, <Fig look={OLD} expression="smile" pose="stand" t={0.6} />),
},
{
title: "2. Segurando (2 mãos)",
refFile: "maos-segurando.png",
bg: "#232d4b",
renderOur: (w, h) => cropFig(w, h, 100, 250, 128, <Fig look={OLD} expression="smile" pose="hold" item="book" t={0.6} />),
},
{
title: "3. Joinha (thumbs_up)",
refFile: "joinha.png",
bg: "#68623e",
renderOur: (w, h) => cropFig(w, h, 122, 212, 130, <Fig look={COACH} expression="happy" pose="thumbs_up" gesture="thumbs_up" t={0.6} />),
},
{
title: "4. Segurando (1 mão)",
refFile: "mao-prancheta.png",
bg: "#3e4844",
renderOur: (w, h) => cropFig(w, h, 118, 224, 132, <Fig look={COACH} expression="happy" pose="hold" item="ruler" t={0.6} />),
},
{
title: "5. Apontando (point)",
refFile: "apontando.png",
bg: "#6e4e3a",
renderOur: (w, h) => cropFig(w, h, 130, 178, 125, <Fig look={MECHANIC} expression="happy" pose="point" t={0.6} />),
},
{
title: "6. Braços cruzados",
refFile: "bracos-cruzados.png",
bg: "#8c8275",
renderOur: (w, h) => cropFig(w, h, 100, 266, 142, <Fig look={WORKER} expression="sad" pose="cross_arms" t={0.6} />),
},
{
title: "7. Insert de mãos",
refFile: "insert-maos.png",
bg: "#4a3322",
renderOur: (w, h) => (
<g transform={`translate(${-w * 0.12} ${-h * 0.14}) scale(${(w * 1.24) / 1080})`}>
<svg width={1080} height={1080} viewBox="0 0 1080 1080" overflow="visible">
<Insert look={OLD} item="book" t={0.6} />
</svg>
</g>
),
},
];
const cw = 320, ch = 320, pad = 16, topBanner = 52, labelH = 34;
const W = items.length * cw, H = topBanner + (ch + labelH) * 2 + 20;
const sheet = (
<svg xmlns="http://www.w3.org/2000/svg" viewBox={`0 0 ${W} ${H}`} width={W} height={H}>
<rect width={W} height={H} fill="#181c26" />
<text x={20} y={36} fontSize={24} fontFamily="Arial" fontWeight={700} fill="#f2c230">
REFERÊNCIA (recortes originais) × NOSSO RESULTADO (SVG puro / rig contínuo sem juntas)
</text>
{items.map((it, i) => {
const x = i * cw;
const yRef = topBanner + labelH;
const yOur = yRef + ch + labelH;
const boxW = cw - pad, boxH = ch - pad;
const refData = loadRef(it.refFile);
return (
<g key={i}>
<text x={x + 12} y={yRef - 10} fontSize={18} fontFamily="Arial" fontWeight={700} fill="#d5dce8">{it.title} — Ref</text>
<defs>
<clipPath id={`cref${i}`}><rect x={x + 8} y={yRef} width={boxW} height={boxH} rx={12} /></clipPath>
<clipPath id={`cour${i}`}><rect x={x + 8} y={yOur} width={boxW} height={boxH} rx={12} /></clipPath>
</defs>
<g clipPath={`url(#cref${i})`}>
<rect x={x + 8} y={yRef} width={boxW} height={boxH} fill="#2a3040" />
{refData && <image href={refData} x={x + 8} y={yRef} width={boxW} height={boxH} preserveAspectRatio="xMidYMid slice" />}
</g>
<text x={x + 12} y={yOur - 10} fontSize={18} fontFamily="Arial" fontWeight={700} fill="#7be08a">{it.title} — Nosso</text>
<g clipPath={`url(#cour${i})`}>
<g transform={`translate(${x + 8} ${yOur})`}>
<rect width={boxW} height={boxH} fill={it.bg} />
{it.renderOur(boxW, boxH)}
</g>
</g>
</g>
);
})}
</svg>
);
return { svg: renderToStaticMarkup(sheet), W };
}
fs.mkdirSync("out", { recursive: true });
const arg = process.argv[2] ?? "full";
const { Resvg } = await import("@resvg/resvg-js").catch(() => ({ Resvg: null as unknown as typeof import("@resvg/resvg-js").Resvg }));
if (arg === "compare") {
const { svg, W } = renderCompareSheet();
fs.writeFileSync("out/referencia-vs-resultado.svg", svg);
if (Resvg) {
fs.writeFileSync("out/referencia-vs-resultado.png", new Resvg(svg, { fitTo: { mode: "width", value: W } }).render().asPng());
console.log("out/referencia-vs-resultado.png");
}
} else {
const mode = arg === "close" ? "close" : "full";
const { svg, W } = renderPoseSheet(mode);
fs.writeFileSync(`out/sheet-${mode}.svg`, svg);
console.log(`out/sheet-${mode}.svg`);
if (Resvg) {
fs.writeFileSync(`out/sheet-${mode}.png`, new Resvg(svg, { fitTo: { mode: "width", value: W } }).render().asPng());
console.log(`out/sheet-${mode}.png`);
}
const cmp = renderCompareSheet();
fs.writeFileSync("out/referencia-vs-resultado.svg", cmp.svg);
if (Resvg) {
fs.writeFileSync("out/referencia-vs-resultado.png", new Resvg(cmp.svg, { fitTo: { mode: "width", value: cmp.W } }).render().asPng());
console.log("out/referencia-vs-resultado.png");
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,111 @@
// Personagem do estilo Cartoon montado por PEÇAS (não é desenho pronto): o mesmo personagem sai igual em
// qualquer cena e história, mudando só expressão, pose e o que tem na mão. Guardado na biblioteca de
// personagens (assets/characters/<id>/character.json) e copiado no spec de cada trecho.
export const BUILDS = ["slim", "average", "heavy"] as const;
export const HAIR_STYLES = ["short", "side", "bun", "long", "curly", "spiky", "bald", "cap"] as const;
export const BEARD_STYLES = ["none", "stubble", "mustache", "full", "goatee", "long"] as const;
export const GLASSES = ["none", "round", "square", "sun"] as const;
export const BROWS = ["thin", "thick"] as const;
/** "robe" = túnica longa até a canela (com faixa na cintura), de roupa antiga. */
export const TOP_STYLES = ["shirt", "jacket", "hoodie", "dress", "uniform", "robe"] as const;
export const BOTTOM_STYLES = ["pants", "shorts", "skirt"] as const;
export const HEAD_SHAPES = ["round", "oval", "square", "wide"] as const;
export const NOSES = ["button", "curve", "round", "long", "wide"] as const;
/** Calçado: sapato fechado (cor em `shoes`), sandália de tiras ou pé descalço. */
export const FOOTWEAR = ["shoes", "sandals", "bare"] as const;
/** Acessórios desenhados por cima da roupa (combináveis). */
export const ACCESSORIES = ["towel", "whistle", "tie", "vest", "helmet", "watch", "badge", "apron", "scarf", "headset", "chain"] as const;
export type Accessory = (typeof ACCESSORIES)[number];
// Expressões e poses são ATALHOS do rig (rig.ts): parâmetros contínuos que dá para ajustar e misturar.
import { EXPRESSION_NAMES, POSE_NAMES, type ExpressionName, type PoseName } from "./rig";
export const EXPRESSIONS = EXPRESSION_NAMES;
export const POSES = POSE_NAMES;
export type Expression = ExpressionName;
export type Pose = PoseName;
export type CharacterLook = {
build: (typeof BUILDS)[number];
/** Altura relativa (0,85 a 1,15). Criança ≈ 0,8 é aceito também. */
height: number;
skin: string;
hair: { style: (typeof HAIR_STYLES)[number]; color: string };
beard: { style: (typeof BEARD_STYLES)[number]; color: string };
glasses: (typeof GLASSES)[number];
brows: (typeof BROWS)[number];
top: { style: (typeof TOP_STYLES)[number]; color: string; accent?: string };
bottom: { style: (typeof BOTTOM_STYLES)[number]; color: string };
shoes: string;
/** Tipo de calçado (padrão "shoes"); a cor continua em `shoes`. */
footwear?: (typeof FOOTWEAR)[number];
/** Detalhe de ilustração (opcionais; sem eles o personagem sai no traço simples). */
head?: (typeof HEAD_SHAPES)[number];
nose?: (typeof NOSES)[number];
/** Pálpebra de cima de base (0 olho aberto … 0,6 meio caído, olhar cansado/esperto). */
lids?: number;
/** Rugas (0 nenhuma … 1 muitas: testa e canto dos olhos). */
wrinkles?: number;
/** Barriga saliente (o "forte" de barriga). */
belly?: boolean;
accessories?: Accessory[];
/** Cor dos acessórios principais (toalha, gravata, colete, capacete…). */
accessoryColor?: string;
};
/** Ficha do personagem na biblioteca. `kind: "3d"` aponta para a pessoa articulada da Godot (godot/kits). */
export type Character = {
schemaVersion: 1;
id: string;
name: string;
/** Texto curto que aparece na etiqueta (ex.: "Engenheiro de minas · 58 anos"). */
caption?: string;
description?: string;
kind: "cartoon" | "3d";
look: CharacterLook;
/** Só kind "3d": parâmetros da pessoa articulada da Godot. */
godot?: Record<string, unknown>;
createdAt?: string;
updatedAt?: string;
};
export const DEFAULT_LOOK: CharacterLook = {
build: "average", height: 1, skin: "#c98a5e",
hair: { style: "short", color: "#3a2a1e" }, beard: { style: "none", color: "#3a2a1e" },
glasses: "none", brows: "thin",
top: { style: "shirt", color: "#4f7a4a", accent: "#e8b13a" }, bottom: { style: "pants", color: "#2b3350" }, shoes: "#1b1b22",
};
const HEX = /^#[0-9a-f]{6}$/i;
const one = <T extends readonly string[]>(list: T, v: unknown): v is T[number] => typeof v === "string" && list.includes(v);
/** Confere a aparência e devolve os problemas (vazio = ok). */
export function validateLook(look: unknown): string[] {
const l = look as Partial<CharacterLook> | null;
if (!l || typeof l !== "object") return ["look precisa ser um objeto"];
const errors: string[] = [];
if (!one(BUILDS, l.build)) errors.push(`build: ${BUILDS.join("|")}`);
if (typeof l.height !== "number" || !(l.height >= 0.6 && l.height <= 1.2)) errors.push("height entre 0,6 e 1,2");
for (const [k, v] of [["skin", l.skin], ["hair.color", l.hair?.color], ["beard.color", l.beard?.color], ["top.color", l.top?.color],
["bottom.color", l.bottom?.color], ["shoes", l.shoes]] as const) {
if (typeof v !== "string" || !HEX.test(v)) errors.push(`${k}: cor #rrggbb`);
}
if (l.top?.accent !== undefined && !HEX.test(l.top.accent)) errors.push("top.accent: cor #rrggbb");
if (!one(HAIR_STYLES, l.hair?.style)) errors.push(`hair.style: ${HAIR_STYLES.join("|")}`);
if (!one(BEARD_STYLES, l.beard?.style)) errors.push(`beard.style: ${BEARD_STYLES.join("|")}`);
if (!one(GLASSES, l.glasses)) errors.push(`glasses: ${GLASSES.join("|")}`);
if (!one(BROWS, l.brows)) errors.push(`brows: ${BROWS.join("|")}`);
if (!one(TOP_STYLES, l.top?.style)) errors.push(`top.style: ${TOP_STYLES.join("|")}`);
if (!one(BOTTOM_STYLES, l.bottom?.style)) errors.push(`bottom.style: ${BOTTOM_STYLES.join("|")}`);
if (l.head !== undefined && !one(HEAD_SHAPES, l.head)) errors.push(`head: ${HEAD_SHAPES.join("|")}`);
if (l.nose !== undefined && !one(NOSES, l.nose)) errors.push(`nose: ${NOSES.join("|")}`);
if (l.lids !== undefined && !(typeof l.lids === "number" && l.lids >= 0 && l.lids <= 0.8)) errors.push("lids entre 0 e 0,8");
if (l.wrinkles !== undefined && !(typeof l.wrinkles === "number" && l.wrinkles >= 0 && l.wrinkles <= 1)) errors.push("wrinkles entre 0 e 1");
if (l.accessories !== undefined && (!Array.isArray(l.accessories) || l.accessories.some((a) => !one(ACCESSORIES, a)))) errors.push(`accessories: ${ACCESSORIES.join("|")}`);
if (l.footwear !== undefined && !one(FOOTWEAR, l.footwear)) errors.push(`footwear: ${FOOTWEAR.join("|")}`);
if (l.accessoryColor !== undefined && !HEX.test(l.accessoryColor)) errors.push("accessoryColor: cor #rrggbb");
return errors;
}
export const isExpression = (v: unknown): v is Expression => typeof v === "string" && (EXPRESSIONS as string[]).includes(v);
export const isPose = (v: unknown): v is Pose => typeof v === "string" && (POSES as string[]).includes(v);
@@ -0,0 +1,32 @@
// Cores e nomes de fonte do estilo Cartoon (vetor chapado). Sem Remotion: o painel também usa.
import type { TimeOfDay, Tone } from "./spec";
export const SKY: Record<TimeOfDay, [string, string]> = {
night: ["#0b0e22", "#1c2147"],
dawn: ["#2a2c5c", "#8a6a9c"],
day: ["#5aa9e6", "#bfe3f5"],
};
export const COLORS = {
ground: "#14172e",
road: "#1a1d38",
roadLine: "#3a3f6b",
house: ["#3b3f74", "#34386a", "#2f3362", "#41467e"],
houseFar: "#2a2d57",
roof: "#272a52",
window: "#1b1d3a",
light: "#ffc94a",
glow: "rgba(255, 190, 70, 0.35)",
text: "#ffffff",
key: "#ffcf3f",
danger: "#ff4d4d",
ok: "#3ddc84",
ink: "#0c0d1a",
blueprint: "#10245a",
grid: "rgba(120, 160, 255, 0.12)",
};
export const TONE_BG: Record<Tone, string> = { info: "#ffcf3f", danger: "#ff4d4d", ok: "#3ddc84" };
export const TONE_FG: Record<Tone, string> = { info: "#141414", danger: "#ffffff", ok: "#0c2a18" };
export const FONT_CAPTION = "CartoonAnton";
export const FONT_LABEL = "CartoonBebas";
@@ -0,0 +1,392 @@
// Biblioteca de MÃOS desenhadas no estilo de ilustração cartoon de referência (quadro canônico 120×120):
// - Proporções cheias, compactas e arredondadas (como em referencia/recortes/joinha.png, maos-segurando.png,
// mao-prancheta.png e apontando.png): sem dedos compridos em salsicha;
// - Base do pulso cilíndrica arredondada centrada em `wrist` (emenda perfeita com o antebraço ou punho da manga);
// - Sulcos quentes e curtos entre os dedos dobrados, e sombreado cel limpo em 2 tons acompanhando o volume;
// - Camadas `back` (atrás do objeto) e `front` (dedos/polegar na frente do objeto) para que qualquer objeto seguro
// fique claramente DENTRO da mão.
import React from "react";
import type { IconId } from "./spec";
export const HAND_SHAPES = [
"relaxed",
"open",
"point",
"thumbs_up",
"grip",
"pinch_edge",
"pinch_low",
"fist",
"on_face",
"think",
"crossed",
] as const;
export type HandShape = (typeof HAND_SHAPES)[number];
type ShapeDef = {
/** Silhueta principal (camada de trás quando `bodyBehind` é true). */
body: string;
/** Sombra cel em crescente macio (recortada pela silhueta `body`). */
shadow: string;
/** Linhas internas quentes: separação dos dedos, nós e dobras da palma. */
lines: string;
/** Peça por cima (polegar ou dedos que abraçam o objeto pela frente), com sombra e linhas próprias. */
over?: { body: string; shadow?: string; lines?: string };
/** Unhas discretas (só quando a vista pede): [cx, cy, rx, ry, giro]. */
nails?: [number, number, number, number, number][];
overNails?: [number, number, number, number, number][];
/** Pulso no quadro (centro da junta redonda onde termina o antebraço). */
wrist: [number, number];
/** Ângulo do antebraço para o qual a forma foi desenhada (0 = descendo; formas alinhadas = 0). */
wristDeg: number;
upright: boolean;
/** Com objeto: `body` fica ATRÁS do objeto e `over` fica NA FRENTE dele (objeto dentro da mão). */
bodyBehind?: boolean;
/** Ponto onde passa o cabo (`grip`) ou encosta a borda (`pinch_edge`/`pinch_low`). */
hold?: [number, number];
};
// Base redonda no pulso (centro (60, 0), raio ~13.5): garante emenda contínua em qualquer rotação.
const WRIST_CAP = "M46.5 0 A13.5 11 0 0 1 73.5 0";
const SHAPES: Record<HandShape, ShapeDef> = {
// Caída ao lado do corpo: formas arredondadas e carnudas, polegar voltado para dentro, dedos juntos curvando suavemente.
relaxed: {
body: `${WRIST_CAP}`
+ " C76 8 82.5 18 84 31 C85.2 43 84.4 55 82 65 C80.8 70.5 77.8 73.5 74.5 73 C72.2 72.6 70.8 70.5 70.4 67.5"
+ " C69.8 74 68 79 64.2 79.6 C60.8 80.2 58.6 77.5 58.2 73"
+ " C57.4 78.5 55.2 82 51.2 82 C47.5 82 45.4 78.5 45.2 73.5"
+ " C44.2 76.5 42 78 39.2 77.4 C35.8 76.6 34.2 72.5 34.8 66 C35.5 57 37.2 48 39 41"
+ " C37 46.5 35 51.5 32.2 54 C29 56.8 25 55.5 24.2 51 C23.2 45.8 25.5 37.5 29.5 29.5"
+ " C34 21 41 13.5 45 5.5 C46 3.5 46.5 1.8 46.5 0 Z",
shadow: "M66 -10 C69 5 75.5 16 78 30 C79.8 43 78.8 56 76 67 C72.5 75 62 80 44 78 L44 90 L92 90 L92 -10 Z",
lines: "M39 41 C40.8 35 41.5 28.5 40.5 22.5 M45.2 73.5 C45.8 65.5 46.8 58 48.2 52 M58.2 73 C58.8 65 59.5 57.5 60.2 51.5 M70.4 67.5 C71 61 71.6 55 72 50",
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Mão aberta (acenando / comemorando): palma carnuda, dedos abrindo em leque macio que afinam na ponta, polegar na base.
open: {
body: `${WRIST_CAP}`
+ " C75.5 7 81.5 16 83.8 28 C85 35 86 43 88 51.5 C89.2 56.8 88 61.2 84.8 62.2 C81.5 63.2 78.6 60.4 76.6 55"
+ " C74.8 50.2 73.2 45.2 71.8 41.2 C73 50 74.2 60.5 74.6 68.8 C74.9 74.6 72.2 78.2 68.4 78.2 C64.8 78.2 62.6 74.8 62.2 69"
+ " C61.8 60.5 61.2 51.5 60.8 44 C60.5 54 60.2 65.5 59.6 74.2 C59.2 80.4 56.2 83.6 52.2 83.4 C48.4 83.2 46.2 79.6 46.2 73.5"
+ " C46.2 64.5 46.8 54 47.5 44.5 C46 52.5 44.5 61.5 43.5 68.5 C42.6 74 39.6 76.8 36 76.2 C32.4 75.5 30.8 72 31.5 66.2"
+ " C32.8 56 35.2 44.5 37.5 35 C33.5 38.8 29.2 42.8 25 45.5 C20.8 48.2 16.4 47 15.2 43 C14 39 16.5 34 21.2 30.2"
+ " C27.2 25.4 34.8 20.8 40.2 14.5 C43.8 10.2 46 5 46.5 0 Z",
shadow: "M67 -10 C70 5 77 16 80 30 C82 40 83.5 50 86 60 L96 60 L96 -10 Z"
+ " M46 28 C53 33.5 63 35.5 72 32 C68 38.5 57 40.5 47 35.5 Z",
lines: "M43 37 C53 34 64.5 34.5 73.5 38.5 M38.5 34 C42.8 28 46 21 47 14",
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Apontando (como em referencia/recortes/apontando.png):
// Polegar redondo na lateral interna (esquerda), indicador comprido subindo firme ao lado dele,
// e os 3 outros dedos (médio, anelar, mínimo) dobrados em escada arredondada macia na direita.
point: {
body: `${WRIST_CAP}`
+ " C76 8 82.5 18 84.5 30 C86 39 86.5 48 84 55.5 C82 61 77.2 63.5 72.5 61.5"
+ " C71 66.8 66.2 69.8 60.8 68.6 C58 68 55.8 66 54.6 63.5"
+ " C53 67.5 51 69.5 48.8 69.5 C48.8 79.5 48.8 90.5 48.4 98.5"
+ " C48 105.5 44.2 109.2 39.4 109 C34.6 108.8 31.4 104.6 31.8 97.5"
+ " C32.4 85 33.8 69.5 35 55.5 C29 51.5 25 44.5 25.8 36.2 C26.6 28 32.2 21 38.8 15.2"
+ " C43.2 11 45.8 5.2 46.5 0 Z",
shadow: "M65 -10 C68.5 5 76 15 79 29 C81 39 80.5 49 78 56 C73 60.5 63 64.5 50 65.5 L50 75 L93 75 L93 -10 Z"
+ " M42.8 58 C44.2 72 44.2 88 43.2 109 L49.5 109 L49.5 58 Z",
lines: "M50.5 68.5 C50.8 60.5 51.6 53 53.5 47.5 M61.8 68 C62.4 60 63.2 53 64.8 47.5 M72.5 61.5 C73.2 55 74 49 75.2 44.5"
+ " M49 48.5 C57.5 46 67.5 44.5 78 43",
over: {
body: "M25.8 36.2 C26.6 27.5 33.8 21 41.2 24.2 C47 26.8 52.2 34.5 55.5 42.2 C58.5 49 57.5 56.5 52.2 58.8 C47 61.2 39.2 57.8 33.2 51.5 C27.8 45.8 25.2 41.2 25.8 36.2 Z",
shadow: "M28.5 43.5 C33.8 50.8 42.2 56.5 50.5 58 L47.5 62 L26.5 48.5 Z",
lines: "M35 27.5 C41.2 32.5 48 39.5 52.5 46.5",
},
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Joinha (proporção compacta e redonda idêntica a referencia/recortes/joinha.png):
// Punho cheio e arredondado (largura ~52, altura ~56 na palma), 4 dedos gordinhos empilhados com sulcos curtos,
// e polegar forte subindo na vertical do topo da palma.
thumbs_up: {
body: "M74 88 A13.5 13.5 0 0 0 90 66"
+ " C87 57 82 49 75 43"
+ " C75.5 32 75 19 73 10.5 C71.2 3.5 66.5 0 60.5 0.5 C54.8 1 51.2 6 51 14.5"
+ " C50.8 23.5 51.2 32.5 50 39 C41 38.5 33 40 29.5 45.5 C26.2 50.6 27.8 57 33 58.8"
+ " C27.2 61.2 26.8 68.8 32.2 71.6 C28.2 74.4 28.8 81.8 34 84"
+ " C31.8 87.5 34.2 93.8 41 95 C51 96.8 63 96 70.5 91.5 C72.5 90.2 73.5 89 74 88 Z",
shadow: "M67 2 C70.8 10 72 25 72 41 C78.5 46 84 55 87 65 L92 74 L74 92 L34 97 L30 89"
+ " C44 93.5 59 93 68.5 88.5 C75.5 85 78.5 76 77 65 C75.5 54 72 46.5 66 42.5 L66 2 Z"
+ " M31.5 57.2 C40.5 59.8 50.5 60 59 58.5 L59 61.2 C49.5 62.6 40.5 62.2 31 59.8 Z"
+ " M31 70 C40 72.6 50.5 72.8 59 71.2 L59 74 C49.5 75.4 40 75 30.5 72.6 Z"
+ " M33 82.4 C41.5 84.8 50 85 57.5 83.8 L57.5 86.5 C49 87.6 41.5 87.2 32.5 85 Z",
lines: "M33 58.8 C41 60.8 50 61 58 59.5 M32.2 71.6 C40.5 73.6 50 73.8 58 72.2 M34 84 C41.8 85.8 49.5 86 56.5 84.8"
+ " M51 36.5 C56.5 39.8 64.5 40.2 71.5 37.5",
wrist: [82, 76], wristDeg: 135, upright: true,
},
// Punho segurando um cabo ou prancheta (proporção compacta e redonda idêntica a referencia/recortes/mao-prancheta.png):
// - `body` (atrás do cabo): base da palma;
// - `over` (na frente do cabo): mão redonda e carnuda com 4 dedos roliços empilhados e 3 sulcos curtos.
grip: {
body: "M88 77 A13.5 13.5 0 0 0 88 50"
+ " C81 44 71 40 59 40 C47 40 37 43 33.5 51 C30 59 31 73 36 83"
+ " C41 91 54 93 67 90 C77 87.5 84 83 88 77 Z",
shadow: "M76 44 C83 52 86 64 83 75 C80 84 72 90 60 92 L92 92 L92 44 Z",
lines: "",
over: {
body: "M86 48 C79 38 66 33.5 53 34 C41 34.5 33 38 30.5 44.5 C28.5 49.5 30.2 53.5 34.5 55.2"
+ " C28 57 26 63 29.5 68 C31 70 33 71 35.5 71.6"
+ " C29.5 73.8 29 80.5 34 83.5 C32 86.8 34.2 92.5 41 93.8"
+ " C51.5 95.8 65 95 75 90.5 C83 87 88 81 89.5 74 C91 66 90 55 86 48 Z",
shadow: "M76 41 C84 49 87.5 61 85 73 C82 83 73.5 90 61.5 92.5 C49.5 95 39 94 32 90.5 L32 97 L92 97 L92 41 Z"
+ " M33.5 53.8 C42 56.2 52.5 56.2 61 54.5 L61 57.2 C52 59 41.5 58.8 32.5 56.2 Z"
+ " M33.8 70.2 C42 72.5 52 72.8 60 71.2 L60 74 C51 75.5 41 75 32.8 72.8 Z"
+ " M33.5 82.2 C41.5 84.5 51 84.8 58.5 83.5 L58.5 86.2 C50 87.5 40.5 87.2 32.5 84.8 Z",
lines: "M34.5 55.2 C43 57.2 53 57 60.5 55.2 M35.5 71.6 C43.5 73.6 52.5 73.8 59.5 72.2 M34 83.5 C42 85.5 50.5 85.8 57.5 84.5",
},
wrist: [86, 64], wristDeg: 45, upright: true, bodyBehind: true, hold: [44, 65],
},
// Segurando a borda lateral de um objeto largo (proporção redonda e compacta idêntica a referencia/recortes/maos-segurando.png):
// - `body` (atrás): palma arredondada que apoia por trás do objeto;
// - `over` (na frente da borda): mão redonda e gordinha (`largura ~50, altura ~58`) com 4 dedos roliços e 3 sulcos curtos!
pinch_edge: {
body: "M88 73 A13.5 13.5 0 0 0 88 46"
+ " C81 39 70 35 59 36 C47 37 40 44 40 58 C40 72 45 83 54 88"
+ " C63 93 75 91 83 83 C86 79.5 87.5 76 88 73 Z",
shadow: "M76 40 C83 48 86 60 83.5 72 C81 82 73 88 61 90 L92 92 L92 40 Z",
lines: "",
over: {
body: "M85 44 C77 34 63 30 49 31.5 C37.5 32.8 30.5 38.5 32.5 45.8"
+ " C26.8 48 25 55.2 30 59.5 C25 62.2 24.8 70 30.5 73.5"
+ " C27.2 77.2 29.2 84.5 36 87 C46 90.5 60 91 72 87"
+ " C80.5 84 86.5 78 88.2 70.5 C90 62 89 51 85 44 Z",
shadow: "M75 38 C83 47 86.5 59.5 84 71.5 C81.5 81.5 73 87.5 60.5 89 C47.5 90.5 37 88 31.5 83.5 L31.5 93 L92 93 L92 38 Z"
+ " M32 44.5 C40.5 47.2 50.5 47.5 58.5 46 L58.5 48.8 C49.5 50.2 39.5 50 31 47.2 Z"
+ " M29.5 58.2 C38 61 48 61.2 56 59.8 L56 62.5 C47 64 37 63.8 28.5 61 Z"
+ " M30 72.2 C38.5 74.8 48 75 55.5 73.6 L55.5 76.4 C46.5 77.8 37.5 77.5 29 75 Z",
lines: "M32.5 45.8 C41 48 50.5 48.2 58 46.8 M30 59.5 C38.5 61.8 48 62 55.5 60.5 M30.5 73.5 C38.8 75.8 47.8 76 54.8 74.6",
},
wrist: [85, 60], wristDeg: 62, upright: true, bodyBehind: true, hold: [44, 60],
},
// Pegada de borda com o antebraço vindo de baixo (HandsInsert): dedos atrás da página e polegar comprido + palma na frente.
pinch_low: {
body: "M84 106 A14 14 0 0 0 104 86"
+ " C99 76 95 64 92 52 C89 39 81 28 69 26 C59 24.5 52 30 51 40"
+ " C49.5 55 50 72 54 84 C58 93 69 98 84 106 Z",
shadow: "M78 28 C88 39 92 55 95 70 C97 80 100 86 105 92 L112 104 L76 108 L54 90 C66 93 78 90 83 80 C88 68 85 45 78 28 Z",
lines: "M52 44 C59 44.5 66.5 46.5 72.5 50 M51.5 58 C58.5 58.8 65.5 60.8 71.5 64 M52.5 72 C58.5 72.8 64.5 74.8 69.5 78",
over: {
body: "M84 106 A14 14 0 0 0 104 86"
+ " C98 76 91 64 82 54 C72 44 56 34 45 30.5 C36.5 27.8 30.5 32.5 33 40"
+ " C35.5 47.5 45 54.5 55 61 C61 65 65 73 68 84 C71 94 77 101 84 106 Z",
shadow: "M34 41 C42 49 52 56 60 62 C65 68 68 78 72 90 L98 106 L82 110 L62 92 L32 46 Z",
lines: "M56 61 C62 64 67 69 70 76",
},
wrist: [94, 96], wristDeg: 135, upright: true, bodyBehind: true, hold: [56, 52],
},
// Punho fechado: 4 dedos dobrados em arco macio, polegar travando por cima do indicador e do médio.
fist: {
body: `${WRIST_CAP}`
+ " C75.5 8 81 18 82.8 30 C84.2 40 84.2 50 81.5 56.5 C79.2 61.5 75.2 63.2 71.5 61.8"
+ " C69.8 66.2 65.5 68.5 60.8 67.6 C58.2 67 56.2 65.2 55 62.8"
+ " C53.2 66.8 48.8 68.8 44.2 67.6 C39.5 66.4 36.2 62.2 35 55.5"
+ " C33.2 46 33.5 35 36.5 25.5 C39.5 16.5 44 9 46.2 2.5 C46.4 1.5 46.5 0.8 46.5 0 Z",
shadow: "M65 -10 C68 5 75 15 78 29 C80 40 79 50 75 57 C68 63 54 66 38 62 L38 74 L92 74 L92 -10 Z",
lines: "M46 67 C46.2 59.5 47 52.5 48.8 47 M60.8 67.6 C61.2 60 61.8 53 63.4 47.5 M71.5 61.8 C72 55.5 72.6 49.5 73.8 45"
+ " M42 48.5 C53 45.8 65 44.5 76.5 43.2",
over: {
body: "M35.5 28 C41 34 49 41 55.5 46.5 C60.2 50.5 61 56.8 56.5 59.8 C52 62.8 44.8 60 39.5 54.2 C34.5 48.8 32.5 39.5 35.5 28 Z",
shadow: "M35 44 C39.5 51 46.5 56.5 54 58.5 L50 62.5 L33 50 Z",
},
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Mão no rosto (tapar a boca / facepalm): palma arredondada e macia, dedos unidos em concha com sulcos curtos nas pontas.
on_face: {
body: `${WRIST_CAP}`
+ " C75 8 80 18 81.5 30 C82.8 41 82.4 55 80.5 67 C79.5 73 76.8 76 73.5 75.5 C71.5 75.2 70.2 73.5 69.8 71"
+ " C69.2 76.5 67.2 81.5 63.2 82 C59.8 82.4 58 80 57.6 76.5"
+ " C57 81.5 54.6 85 50.6 85 C46.8 85 44.8 81.5 44.6 76.5"
+ " C43.8 79.8 41.4 81.8 38.2 81.2 C34.8 80.5 33 76.5 33.6 69.5 C34.5 58 36.2 46.5 38 38"
+ " C35.5 42.5 33 46.5 30 48.5 C26.8 50.5 23.2 49 22.6 45 C22 40 24.8 32.5 29.5 25.5"
+ " C34.5 18 41.8 11 45.2 4 C46 2.5 46.5 1.2 46.5 0 Z",
shadow: "M65 -10 C68 5 74.5 16 77 30 C78.5 43 78 58 75.5 71 C72.5 79 61 84 44 83 L44 92 L90 92 L90 -10 Z",
lines: "M38 38 C39.8 32.5 40.6 27 40 21 M44.6 76.5 C45 69.5 45.8 63 46.8 57.5 M57.6 76.5 C58 69.5 58.4 63 59 57.5 M69.8 71 C70.2 65 70.6 59.5 71 55",
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Mão pensando (apoiada no queixo): punho macio sob o queixo com o indicador estendido na bochecha/queixo
// e os outros 3 dedos dobrados em gomos arredondados (sem aspecto de garfo ou bloco).
think: {
body: `${WRIST_CAP}`
+ " C75.5 8 81.5 18 83.2 30 C84.5 40 84 50 81 57 C78.5 62.5 73.8 64.5 69.5 62.5"
+ " C67.8 67.2 63 69.5 58 68.2 C55.2 67.5 53.2 65.5 52.2 63"
+ " C50.5 66.5 47.8 68.2 44.8 67.5 C44.5 75 44 83.5 43 90"
+ " C42 96.2 38.2 99.5 33.8 98.8 C29.4 98 26.8 93.8 27.6 87"
+ " C29 75.5 31.2 61 33.5 48 C29.5 50.5 25 51.5 21.5 49.5 C17.8 47.5 16.5 42.5 18.8 37.5"
+ " C21.5 31.5 28 25.5 34.5 19.5 C40.5 14 44.8 7 46.5 0 Z",
shadow: "M65 -10 C68 5 75.5 16 78 30 C80 41 79 50 75 57 C69 63.5 57 66.5 43 65 L43 74 L91 74 L91 -10 Z"
+ " M38 56 C39.5 68 39.5 82 38.5 99 L44.5 99 L45 56 Z",
lines: "M33.5 48 C37.5 43 41 37 42.5 31 M45 66.5 C45.8 59 47 52 48.8 46.5 M58 68.2 C58.8 60.5 59.8 53.5 61.5 47.5 M69.5 62.5 C70.2 56 71 50 72.2 45",
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Mão de braços cruzados apoiada no bíceps oposto (como em referencia/recortes/bracos-cruzados.png):
// 3 dedos roliços e macios pousados diagonalmente sobre o braço.
crossed: {
body: `${WRIST_CAP}`
+ " C74.5 8 79 18 80 29 C81 40 79.5 52 75.8 61.5 C73.2 68 68.5 71 63.8 69.5"
+ " C61.4 75.8 56.2 79.2 50.5 77.6 C47 76.6 44.6 73.6 43.8 69.5"
+ " C41.2 74 36.2 76 31.2 73.8 C26.4 71.6 24.4 66 26.8 59.2"
+ " C30 50 34.8 38.5 39 27.5 C42.2 19 45.4 9.5 46.5 0 Z",
shadow: "M64 -10 C67 5 72.5 16 74 30 C75 42 73.5 53 70 62 C65.5 70 52 75 33 72 L33 82 L88 82 L88 -10 Z",
lines: "M43.8 69.5 C46.5 59.5 49.8 50 53.2 42 M63.8 69.5 C65.8 60 67.8 51 70.2 43.5",
wrist: [60, 0], wristDeg: 0, upright: false,
},
};
/** Objetos seguros com as DUAS mãos (pelas bordas, na frente do peito). O resto vai numa mão só (`grip`). */
export const TWO_HANDED: IconId[] = ["book", "tablet"];
/**
* Como cada objeto entra no punho (`grip`): ponto do cabo no quadro 100×100 do ícone e o giro que deixa o cabo em pé
* (cabeça do martelo, ponta do ramo e da régua para cima) com sobra visível do cabo abaixo da mão.
*/
export const GRIP: Partial<Record<IconId, { x: number; y: number; rot: number }>> = {
hammer: { x: 50, y: 68, rot: 20 },
olive: { x: 36, y: 68, rot: -42 },
ruler: { x: 32, y: 50, rot: -78 },
phone: { x: 50, y: 62, rot: -6 },
fuel: { x: 50, y: 30, rot: 0 },
bulb: { x: 50, y: 74, rot: 0 },
};
/**
* Posição da forma: espelho (`mirror`), giro em graus e escala, a partir do pulso na tela, do ângulo do antebraço e do
* lado do braço. Formas alinhadas giram com o antebraço; as "em pé" acompanham o ângulo para o qual foram desenhadas.
*/
export function handPlacement(shape: HandShape, x: number, y: number, foreDeg: number, s: number, k: number) {
const def = SHAPES[shape];
let mirror: number;
let rot: number;
if (def.upright) {
mirror = s >= 0 ? 1 : -1;
rot = foreDeg - def.wristDeg * mirror;
} else {
const up = Math.cos((foreDeg * Math.PI) / 180) >= 0;
mirror = up ? s : -s;
rot = foreDeg;
}
const [wx, wy] = def.wrist;
const transform = `translate(${x} ${y}) rotate(${rot}) scale(${k * mirror} ${k}) translate(${-wx} ${-wy})`;
const r = (rot * Math.PI) / 180;
/** Ponto do quadro 120×120 → tela. */
const map = (px: number, py: number) => {
const lx = (px - wx) * k * mirror;
const ly = (py - wy) * k;
return { x: x + lx * Math.cos(r) - ly * Math.sin(r), y: y + lx * Math.sin(r) + ly * Math.cos(r) };
};
return { def, mirror, rot, transform, map, hold: def.hold ? map(def.hold[0], def.hold[1]) : null };
}
/** Pulso que põe o ponto `hold` da forma em (hx, hy) — para pôr as mãos nas bordas do objeto. */
export function wristForHold(shape: HandShape, hx: number, hy: number, foreDeg: number, s: number, k: number) {
const p = handPlacement(shape, 0, 0, foreDeg, s, k);
return { x: hx - (p.hold?.x ?? 0), y: hy - (p.hold?.y ?? 0) };
}
function shadeHex(hex: string, k: number): string {
const n = parseInt(hex.slice(1), 16);
const c = (v: number) => Math.max(0, Math.min(255, Math.round(v * k))).toString(16).padStart(2, "0");
return `#${c((n >> 16) & 255)}${c((n >> 8) & 255)}${c(n & 255)}`;
}
/** Mistura duas cores hex (0 = a, 1 = b). */
function mixHex(a: string, b: string, t: number): string {
const pa = parseInt(a.slice(1), 16), pb = parseInt(b.slice(1), 16);
const ch = (sh: number) => Math.round(((pa >> sh) & 255) * (1 - t) + ((pb >> sh) & 255) * t).toString(16).padStart(2, "0");
return `#${ch(16)}${ch(8)}${ch(0)}`;
}
function coolHex(hex: string, k: number): string {
const n = parseInt(hex.slice(1), 16);
const r = ((n >> 16) & 255) * k * 0.96, g = ((n >> 8) & 255) * k * 0.96, b = (n & 255) * k + 6;
const c = (v: number) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, "0");
return `#${c(r)}${c(g)}${c(b)}`;
}
/**
* Desenha a forma de mão no lugar. `layer`: "back" = o que fica atrás do objeto, "front" = o que fica na frente,
* "all" = tudo. `light` = lado da sombra na tela (1 = direita).
*/
export function HandArt({ shape, x, y, foreDeg, s, k, skin, light = 1, layer = "all", uid }: {
shape: HandShape; x: number; y: number; foreDeg: number; s: number; k: number; skin: string; light?: number;
layer?: "all" | "back" | "front"; uid: string;
}) {
const p = handPlacement(shape, x, y, foreDeg, s, k);
const def = p.def;
const rightOnScreen = p.mirror * Math.cos((p.rot * Math.PI) / 180);
const flipShadow = Math.sign(rightOnScreen || 1) !== Math.sign(light || 1);
const shadowT = flipShadow && !def.upright ? "translate(120 0) scale(-1 1)" : undefined;
const creaseColor = shadeHex(skin, 0.76);
const shadowFill = coolHex(skin, 0.86);
const skinLite = mixHex(skin, "#fff6ea", 0.06);
const gradId = `hg${uid}${layer}`;
const lineProps = {
stroke: creaseColor,
strokeWidth: 3.1,
strokeLinecap: "round" as const,
strokeLinejoin: "round" as const,
fill: "none",
opacity: 0.9,
};
const nail = ([cx, cy, rx, ry, a]: [number, number, number, number, number], i: number) => (
<ellipse
key={i}
cx={cx}
cy={cy}
rx={rx}
ry={ry}
transform={`rotate(${a} ${cx} ${cy})`}
fill={mixHex(skin, "#fae5de", 0.38)}
opacity={0.8}
/>
);
const bodyLayer = def.bodyBehind ? "back" : def.hold ? "front" : "all";
const showBody = layer === "all" || layer === bodyLayer || (bodyLayer === "all" && layer === "front");
const showOver = layer !== "back";
return (
<g transform={p.transform}>
<defs>
<linearGradient id={gradId} x1="15%" y1="10%" x2="85%" y2="90%">
<stop offset="0%" stopColor={skinLite} />
<stop offset="100%" stopColor={skin} />
</linearGradient>
<clipPath id={`hb${uid}${layer}`}><path d={def.body} /></clipPath>
{def.over && <clipPath id={`ho${uid}${layer}`}><path d={def.over.body} /></clipPath>}
</defs>
{showBody && (
<>
<path d={def.body} fill={`url(#${gradId})`} />
<g clipPath={`url(#hb${uid}${layer})`}>
<path d={def.shadow} fill={shadowFill} transform={shadowT} opacity={0.88} />
</g>
{def.lines && <path d={def.lines} {...lineProps} />}
{(def.nails ?? []).map(nail)}
</>
)}
{showOver && def.over && (
<>
<path d={def.over.body} fill={`url(#${gradId})`} />
<g clipPath={`url(#ho${uid}${layer})`}>
{def.over.shadow && <path d={def.over.shadow} fill={shadowFill} opacity={0.88} />}
</g>
{def.over.lines && <path d={def.over.lines} {...lineProps} />}
{(def.overNails ?? []).map(nail)}
</>
)}
</g>
);
}
@@ -0,0 +1,127 @@
// Ícones chapados (viewBox 100×100). Formas simples, sem contorno, na paleta do estilo.
import React from "react";
import { COLORS } from "./colors";
import type { IconId } from "./spec";
const INK = COLORS.ink;
const DRAW: Record<IconId, React.ReactNode> = {
house: (<>
<polygon points="8,46 50,12 92,46" fill={COLORS.roof} />
<rect x={16} y={44} width={68} height={48} fill={COLORS.house[3]} />
<rect x={24} y={54} width={14} height={14} rx={2} fill={COLORS.light} />
<rect x={62} y={54} width={14} height={14} rx={2} fill={COLORS.light} />
<rect x={44} y={66} width={12} height={26} fill={COLORS.window} />
</>),
generator: (<>
<rect x={8} y={30} width={84} height={56} rx={8} fill="#2a2d3c" />
<rect x={14} y={22} width={58} height={16} rx={6} fill="#e8463d" />
<rect x={16} y={44} width={34} height={34} rx={4} fill="#4a4e63" />
{[0, 1, 2, 3, 4].map((i) => <rect key={i} x={19} y={48 + i * 6} width={28} height={3} fill="#2a2d3c" />)}
<circle cx={64} cy={52} r={4} fill="#11121a" /><circle cx={76} cy={52} r={4} fill="#11121a" />
<circle cx={70} cy={68} r={3} fill={COLORS.ok} />
<rect x={10} y={86} width={14} height={6} fill="#11121a" /><rect x={76} y={86} width={14} height={6} fill="#11121a" />
</>),
fuel: (<>
<rect x={20} y={22} width={60} height={72} rx={8} fill="#c8352f" />
<rect x={26} y={50} width={48} height={38} rx={4} fill="#e6b347" />
<path d="M30 22 L30 12 L60 12 L60 22" stroke="#c8352f" strokeWidth={6} fill="none" />
<rect x={66} y={8} width={12} height={14} fill="#c8352f" />
<path d="M30 56 L70 84 M70 56 L30 84" stroke="#c8352f" strokeWidth={3} />
</>),
battery: (<>
<rect x={28} y={14} width={44} height={80} rx={8} fill="#1d2b2a" stroke={COLORS.ok} strokeWidth={4} />
<rect x={40} y={6} width={20} height={10} rx={3} fill={COLORS.ok} />
<polygon points="54,30 38,58 50,58 46,80 62,50 50,50" fill={COLORS.ok} />
</>),
phone: (<>
<rect x={30} y={8} width={40} height={84} rx={8} fill="#15161f" />
<rect x={35} y={16} width={30} height={64} rx={3} fill="#2c3150" />
<rect x={42} y={40} width={16} height={8} rx={2} fill={COLORS.danger} />
</>),
door: (<>
<rect x={24} y={6} width={52} height={90} rx={3} fill="#4a2f22" />
<rect x={30} y={14} width={40} height={34} rx={2} fill="#3c251b" />
<rect x={30} y={54} width={40} height={34} rx={2} fill="#3c251b" />
<circle cx={66} cy={56} r={3.5} fill="#e6c27a" />
</>),
eye: (<>
<path d="M6 50 Q50 10 94 50 Q50 90 6 50 Z" fill="#f4f6ff" />
<circle cx={50} cy={50} r={20} fill="#2c3466" /><circle cx={50} cy={50} r={9} fill={INK} /><circle cx={56} cy={44} r={4} fill="#fff" />
</>),
bulb: (<>
<circle cx={50} cy={40} r={28} fill={COLORS.light} />
<rect x={38} y={64} width={24} height={16} rx={3} fill="#9aa0b8" /><rect x={42} y={80} width={16} height={8} rx={3} fill="#6c7190" />
</>),
solar: (<>
<polygon points="10,70 30,30 92,30 72,70" fill="#2b4fb8" />
<path d="M30 50 L82 50 M27 40 L87 40 M24 60 L77 60 M45 30 L35 70 M61 30 L51 70 M77 30 L67 70" stroke="#8fb0ff" strokeWidth={2} />
<rect x={46} y={70} width={6} height={22} fill="#6c7190" />
</>),
warning: (<>
<polygon points="50,8 94,88 6,88" fill={COLORS.key} />
<rect x={46} y={34} width={8} height={30} rx={3} fill={INK} /><circle cx={50} cy={74} r={5} fill={INK} />
</>),
money: (<>
<rect x={8} y={26} width={84} height={48} rx={6} fill="#3a9e5f" />
<circle cx={50} cy={50} r={14} fill="#2b7a49" /><text x={50} y={57} textAnchor="middle" fontSize={20} fontWeight={700} fill="#d9f5e3">$</text>
</>),
clock: (<>
<circle cx={50} cy={50} r={40} fill="#f4f6ff" /><circle cx={50} cy={50} r={34} fill="#232850" />
<rect x={48} y={24} width={4} height={28} rx={2} fill="#fff" /><rect x={48} y={48} width={22} height={4} rx={2} fill={COLORS.key} />
</>),
// Itens de mão e objetos de história antiga (também servem como objeto solto na cena).
olive: (<>
<path d="M14 94 Q44 62 86 14" stroke="#3d2814" strokeWidth={8.5} fill="none" strokeLinecap="round" />
<path d="M14 94 Q44 62 86 14" stroke="#7d5632" strokeWidth={5.5} fill="none" strokeLinecap="round" />
{[[38, 62, -38], [48, 52, 28], [58, 42, -38], [68, 32, 28], [78, 22, -38], [84, 15, -12]].map(([x, y, r], i) => (
<g key={i} transform={`rotate(${r} ${x} ${y})`}>
<ellipse cx={x} cy={y} rx={13.5} ry={6} fill={i % 2 ? "#557d32" : "#446827"} />
<ellipse cx={x} cy={y - 1} rx={12} ry={4.2} fill={i % 2 ? "#84ab4c" : "#6c943c"} />
<path d={`M${x - 9} ${y} L${x + 9} ${y}`} stroke="#9ec462" strokeWidth={1.2} strokeLinecap="round" opacity={0.7} />
</g>
))}
<circle cx={54} cy={54} r={4.5} fill="#2e2b4a" /><circle cx={52.5} cy={52.5} r={1.5} fill="#76729e" />
<circle cx={72} cy={35} r={4.5} fill="#2e2b4a" /><circle cx={70.5} cy={33.5} r={1.5} fill="#76729e" />
</>),
hammer: (<>
<g transform="rotate(-20 50 64)">
<rect x={42.5} y={28} width={15} height={68} rx={6} fill="#5c381c" />
<rect x={44} y={29} width={12} height={66} rx={5} fill="#9c6638" />
<rect x={45.5} y={30} width={4.5} height={64} rx={2} fill="#b87e4a" opacity={0.75} />
<rect x={42} y={32} width={16} height={6} rx={2} fill="#4a2e16" />
</g>
<g transform="rotate(-20 47 25)">
<rect x={18} y={11} width={58} height={25} rx={5} fill="#4d525e" />
<rect x={19} y={12} width={56} height={22} rx={4} fill="#8f96a3" />
<rect x={21} y={14} width={52} height={8} rx={3} fill="#b4bac6" opacity={0.7} />
<rect x={18} y={11} width={14} height={25} rx={4} fill="#686e7a" />
</g>
</>),
tablet: (<>
<path d="M18 10 Q50 4 82 10 L86 88 Q50 96 14 88 Z" fill="#8f6c4a" />
<path d="M20 12 Q50 6 80 12 L84 86 Q50 93 16 86 Z" fill="#b8916a" />
{Array.from({ length: 7 }, (_, i) => <path key={i} d={`M24 ${22 + i * 10} L76 ${22 + i * 10}`} stroke="#785638" strokeWidth={2.5} strokeDasharray="5 3 2 3" />)}
<path d="M70 70 L86 60 L86 88 L64 92 Z" fill="#000" opacity={0.18} />
</>),
book: (<>
<path d="M6 26 Q28 18 50 28 Q72 18 94 26 L94 86 Q72 78 50 88 Q28 78 6 86 Z" fill="#6b3022" />
<path d="M8 22 Q30 14 50 24 Q70 14 92 22 L92 80 Q70 72 50 82 Q30 72 8 80 Z" fill="#dfd2b5" />
<path d="M9 20 Q30 12 50 22 Q70 12 91 20 L91 77 Q70 69 50 79 Q30 69 9 77 Z" fill="#f5ecd6" />
<path d="M44 20 Q47 21 50 22 Q53 21 56 20 L56 78 Q53 78.5 50 79 Q47 78.5 44 78 Z" fill="#e2d5b8" />
<path d="M50 22 L50 79" stroke="#b9a882" strokeWidth={2.5} />
{[0, 1, 2, 3].map((i) => <g key={i}><path d={`M16 ${32 + i * 10.5} Q29 ${29 + i * 10.5} 43 ${34 + i * 10.5}`} stroke="#9a8a6a" strokeWidth={2.4} fill="none" strokeLinecap="round" /><path d={`M57 ${34 + i * 10.5} Q71 ${29 + i * 10.5} 84 ${32 + i * 10.5}`} stroke="#9a8a6a" strokeWidth={2.4} fill="none" strokeLinecap="round" /></g>)}
</>),
ruler: (<>
<g transform="rotate(-12 50 50)">
<rect x={4} y={36} width={92} height={26} rx={4} fill="#8c6230" />
<rect x={6} y={37} width={88} height={23} rx={3} fill="#e8c374" />
<rect x={8} y={53} width={84} height={6} rx={2} fill="#cfa656" />
{Array.from({ length: 11 }, (_, i) => <rect key={i} x={11 + i * 7.6} y={37} width={2.2} height={i % 2 ? 7 : 12} rx={0.8} fill="#5c3d1b" />)}
</g>
</>),
};
export function Icon({ id }: { id: IconId }) {
return <svg viewBox="0 0 100 100" width="100%" height="100%" overflow="visible">{DRAW[id]}</svg>;
}
@@ -0,0 +1,66 @@
// Profundidade dos braços do personagem de frente para a câmera (função pura do estado do rig, sem React).
//
// O desenho (CharacterFigure.tsx) empilha as camadas assim:
// tronco → braços "side" → acessórios do peito (toalha, cachecol, crachá, apito) → braços "front" →
// parte da toalha apoiada no ombro → cabeça → braços "face".
// Regra: com o personagem de frente, braço e mão NUNCA somem atrás do tronco, da roupa, de acessório ou da barba.
// - "face": a mão sobe até a altura do pescoço/rosto, dentro da largura da cabeça (pensar, tapar a boca, mão na
// testa) — desenhado por cima da cabeça e da barba;
// - "front": a mão ou o antebraço entram na frente do peito (segurar objeto diante do corpo, cruzar os braços,
// apontar para o outro lado, mão na cintura) — por cima do tronco e dos acessórios do peito;
// - "side": o braço fica ao lado do corpo (caído, acenando para fora, apontando para o lado) — por cima do tronco,
// mas por baixo do pano apoiado no ombro/peito (o braço sai por baixo da toalha).
// Não há caso "atrás do tronco": nenhuma pose do rig leva a mão às costas.
import type { BodyParams } from "./rig";
export type ArmLayer = "side" | "front" | "face";
export type Point = { x: number; y: number };
/** Ponta de um segmento: ângulo de tela em graus (0 = para baixo). Igual ao `tip` do desenho. */
export const tipOf = (x: number, y: number, deg: number, len: number): Point => {
const r = (deg * Math.PI) / 180;
return { x: x - Math.sin(r) * len, y: y + Math.cos(r) * len };
};
/** Medidas do desenho (viewBox 200×440) que a regra usa — as mesmas de CharacterFigure.tsx. */
export const ARM = { shoulderX: 54, upper: 56, wrist: 43, hand: 28, torsoHalf: 56 } as const;
/** Ombro, cotovelo, pulso e centro da mão do braço `s` (1 = direita da tela, -1 = esquerda). `w` = largura do corpo. */
export function armGeometry(b: BodyParams, s: 1 | -1, w = 1) {
const hipY = 306 + b.crouch * 56;
const shY = hipY - 100;
const torsoTop = hipY - 114;
const l = s > 0 ? b.armR : b.armL;
const shoulder = { x: 100 + s * ARM.shoulderX * w, y: shY };
const upperDeg = -s * l.raise;
const elbow = tipOf(shoulder.x, shoulder.y, upperDeg, ARM.upper);
const foreDeg = upperDeg + s * l.bend;
const wrist = tipOf(elbow.x, elbow.y, foreDeg, ARM.wrist);
const hand = tipOf(elbow.x, elbow.y, foreDeg, ARM.wrist + ARM.hand);
return { shoulder, elbow, wrist, hand, upperDeg, foreDeg, torsoTop, hipY };
}
/**
* Camada do braço `s` no quadro. `holds` = segura objeto (sempre na frente do corpo, salvo na altura do rosto).
* O "peito" é o tronco sem as faixas laterais onde o braço caído naturalmente encosta.
*/
export function armLayer(b: BodyParams, s: 1 | -1, opts: { holds?: boolean; w?: number } = {}): ArmLayer {
const w = opts.w ?? 1;
const g = armGeometry(b, s, w);
const l = s > 0 ? b.armR : b.armL;
const half = ARM.torsoHalf * w;
// Altura do pescoço/rosto: acima do topo do tronco (+ folga da gola), dentro da largura da cabeça, ou braço dobrado ao queixo/boca.
const atFace = (p: Point) => p.y < g.torsoTop + 20 && Math.abs(p.x - 100) < 60;
if (atFace(g.hand) || atFace(g.wrist) || (l.raise < 20 && l.bend > 138)) return "face";
if (opts.holds) return "front";
// Cotovelo bem dobrado para dentro com o braço baixo (segurar, joinha, mão na cintura, braços cruzados): antebraço na frente.
if (l.raise < 90 && l.bend > 85) return "front";
const chest = { x0: 100 - half + 14, x1: 100 + half - 14, y0: g.torsoTop + 4, y1: g.hipY + 12 };
const inChest = (p: Point) => p.x > chest.x0 && p.x < chest.x1 && p.y > chest.y0 && p.y < chest.y1;
// Amostra o antebraço (cotovelo → mão): basta um trecho na frente do peito.
for (let i = 0; i <= 8; i++) {
const k = i / 8;
if (inChest({ x: g.elbow.x + (g.hand.x - g.elbow.x) * k, y: g.elbow.y + (g.hand.y - g.elbow.y) * k })) return "front";
}
return "side";
}
@@ -0,0 +1,87 @@
// Boca acompanhando a fala SEM perder a expressão. O formato vem das letras da palavra que está sendo dita
// (tempos de cada palavra da transcrição): "a" abre, "e/i" esticam, "o/u" arredondam, "m/b/p" fecham, "f/v"
// mostram os dentes; vogal dura mais que consoante e as letras vizinhas se misturam (coarticulação). Se houver
// o volume do áudio quadro a quadro (`env`), ele fecha a boca nas pausas e abre mais nas sílabas fortes.
// A expressão continua por cima: os cantos (sorriso/tristeza), as sobrancelhas e os olhos são dela.
import type { FaceParams } from "./rig";
export type Viseme = { open: number; wide: number; round: number; teeth: boolean };
export type SpokenWord = { text: string; startS: number; endS: number };
const CLOSED: Viseme = { open: 0, wide: 0, round: 0, teeth: false };
const V: Record<string, Viseme> = {
a: { open: 0.85, wide: 0.3, round: 0, teeth: false },
e: { open: 0.55, wide: 0.65, round: 0, teeth: true },
i: { open: 0.3, wide: 0.95, round: 0, teeth: true },
o: { open: 0.65, wide: 0, round: 0.75, teeth: false },
u: { open: 0.35, wide: 0, round: 1, teeth: false },
mbp: { open: 0, wide: 0.1, round: 0, teeth: false },
fv: { open: 0.12, wide: 0.2, round: 0, teeth: true },
cons: { open: 0.3, wide: 0.3, round: 0, teeth: true },
};
function visemeOf(ch: string): Viseme {
if ("aáàâã".includes(ch)) return V.a;
if ("eéê".includes(ch)) return V.e;
if ("iíy".includes(ch)) return V.i;
if ("oóôõ".includes(ch)) return V.o;
if ("uúü".includes(ch)) return V.u;
if ("mbp".includes(ch)) return V.mbp;
if ("fv".includes(ch)) return V.fv;
return V.cons;
}
const isVowel = (ch: string) => /[aáàâãeéêiíyoóôõuúü]/.test(ch);
function mix(a: Viseme, b: Viseme, k: number): Viseme {
return { open: a.open + (b.open - a.open) * k, wide: a.wide + (b.wide - a.wide) * k, round: a.round + (b.round - a.round) * k, teeth: k < 0.5 ? a.teeth : b.teeth };
}
/** Formato da boca no instante `t` (segundos do trecho) para as palavras dadas; fechada fora das palavras. */
export function visemeAt(words: SpokenWord[], t: number, env?: { values: number[]; fps: number }): Viseme {
const w = words.find((x) => t >= x.startS && t < x.endS);
if (!w) {
// Fim de palavra: fecha em ~60 ms em vez de bater a boca.
const prev = [...words].reverse().find((x) => x.endS <= t);
return prev && t - prev.endS < 0.06 ? mix(V.cons, CLOSED, (t - prev.endS) / 0.06) : CLOSED;
}
const letters = [...w.text.toLowerCase().replace(/(ch|lh|nh|qu)/g, "c").replace(/[^a-záàâãéêíóôõúüçy]/g, "")];
if (!letters.length) return CLOSED;
// Vogal pesa o dobro da consoante no tempo da palavra.
const weights = letters.map((ch) => (isVowel(ch) ? 1.7 : 0.8));
const total = weights.reduce((a, b) => a + b, 0);
let pos = ((t - w.startS) / Math.max(0.04, w.endS - w.startS)) * total;
let i = 0;
while (i < letters.length - 1 && pos > weights[i]) { pos -= weights[i]; i++; }
const frac = Math.min(1, pos / weights[i]);
const cur = visemeOf(letters[i]);
const next = i + 1 < letters.length ? visemeOf(letters[i + 1]) : CLOSED;
// Coarticulação: a 2ª metade da letra já caminha para a próxima.
let v = frac > 0.5 ? mix(cur, next, (frac - 0.5) * 0.9) : cur;
if (env?.values.length) {
const a = env.values[Math.min(env.values.length - 1, Math.max(0, Math.floor(t * env.fps)))] ?? 0;
const k = Math.max(0, Math.min(1.15, (a - 0.03) / 0.3));
v = { ...v, open: v.open * (0.25 + 0.75 * Math.min(1, k)) * (k < 0.05 ? 0.2 : 1) };
}
return v;
}
/** Ênfase (0–1) no instante: o volume perto do pico levanta um pouco as sobrancelhas. */
export function emphasisAt(t: number, env?: { values: number[]; fps: number }): number {
if (!env?.values.length) return 0;
const a = env.values[Math.min(env.values.length - 1, Math.max(0, Math.floor(t * env.fps)))] ?? 0;
return Math.max(0, Math.min(1, (a - 0.45) / 0.4));
}
/** Põe a fala na boca mantendo a expressão (cantos, sobrancelhas, olhos). `k` = quanto da fala entra (0–1). */
export function speak(face: FaceParams, v: Viseme, k = 1, emphasis = 0): FaceParams {
const open = Math.max(face.mouthOpen * 0.35, v.open * 0.9);
return {
...face,
mouthOpen: face.mouthOpen + (open - face.mouthOpen) * k,
mouthWidth: face.mouthWidth * (1 + (v.wide * 0.22 - v.round * 0.45) * k),
mouthRound: face.mouthRound + (v.round - face.mouthRound) * k,
teeth: k > 0.5 ? v.teeth && v.open > 0.1 : face.teeth,
browL: { ...face.browL, y: face.browL.y - emphasis * 3 * k },
browR: { ...face.browR, y: face.browR.y - emphasis * 3 * k },
};
}
@@ -0,0 +1,222 @@
// Movimento do personagem: uma LINHA DO TEMPO de ações que se combinam (não animações prontas). Cada ação tem
// início (segundos `at`, fração do trecho `atP` ou a palavra da narração `cue`) e duração; o estado em cada
// quadro sai de aplicar as ações em ordem sobre a expressão/pose de base, mais a "vida" (piscar, respirar).
// Ações permanentes mudam o estado dali em diante (express, pose, walk, sit, fall, turn, look); as momentâneas
// voltam ao fim (nod, shake_head, tremble, bounce, wave, jump, talk, emote).
import { emphasisAt, speak, visemeAt, type SpokenWord } from "./lipsync";
import { blendBody, blendFace, bodyOf, faceOf, withBody, withFace, type BodyParams, type BodyPatch, type FaceParams, type FacePatch } from "./rig";
export const ACTIONS = ["express", "pose", "walk", "run", "enter", "exit", "jump", "nod", "shake_head", "tremble", "bounce", "fall",
"sit", "stand_up", "turn", "talk", "look", "emote", "wave", "hammer"] as const;
export type ActionKind = (typeof ACTIONS)[number];
export type Action = {
do: ActionKind;
/** Início: segundos, fração do trecho (0–1) ou a 1ª palavra da narração que começa com `cue`. */
at?: number; atP?: number; cue?: string;
dur?: number;
/** talk: termina no fim desta palavra da narração (a fala vai de `cue` até `cueEnd`). */
cueEnd?: string;
expression?: string; face?: FacePatch;
pose?: string; body?: BodyPatch;
/** walk/run/enter: x de destino (fração). */
to?: number;
/** look: para onde; fall: para que lado. */
dir?: "left" | "right" | "up" | "down";
/** nod/shake_head/bounce/wave: repetições. jump: altura (fração da altura do quadro). */
times?: number; height?: number;
/** emote: símbolo sobre a cabeça ("!", "?", "…", "♥", "zzz", "💢"). talk: o texto falado (sem tempos de palavra, é
* repartido pela duração). */
text?: string;
};
export type ActorInput = {
x: number; expression?: string; pose?: string; face?: FacePatch; body?: BodyPatch; flip?: boolean; timeline?: Action[];
};
export type ActorState = {
face: FaceParams; body: BodyParams;
x: number; dy: number; dx: number; rot: number; sx: number; sy: number; flip: boolean;
emote: { text: string; k: number } | null;
};
const DEFAULT_DUR: Record<ActionKind, number> = {
express: 0.25, pose: 0.35, walk: 1.6, run: 0.9, enter: 1.2, exit: 1.2, jump: 0.8, nod: 0.7, shake_head: 0.8, tremble: 1, bounce: 0.8,
fall: 0.6, sit: 0.5, stand_up: 0.5, turn: 0.3, talk: 1.5, look: 0.3, emote: 1.2, wave: 1.2, hammer: 2.4,
};
const clamp01 = (v: number) => Math.max(0, Math.min(1, v));
const ease = (p: number) => (p < 0.5 ? 2 * p * p : 1 - (-2 * p + 2) ** 2 / 2);
/** Passa um pouco do alvo e volta (dá vida às poses). */
const easeBack = (p: number) => { const c = 1.4; return 1 + (c + 1) * (p - 1) ** 3 + c * (p - 1) ** 2; };
const norm = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]/g, "");
/** Início da ação em segundos (cue = palavra falada; sem a palavra, cai para atP/at/0). */
export function startOf(a: Action, durationS: number, words: { text: string; startS: number }[] = []): number {
if (a.cue) {
const c = norm(a.cue);
const w = words.find((x) => norm(x.text).startsWith(c));
if (w) return w.startS;
}
if (a.atP !== undefined) return a.atP * durationS;
return a.at ?? 0;
}
/** Piscar em intervalos variados (2,4–4,6 s), determinístico pela semente. */
function blinkAt(t: number, seed: number): number {
let s = 0.6 + (seed % 7) * 0.13;
let k = 1;
while (s < t + 0.2) {
const d = t - s;
if (d >= 0 && d < 0.13) k = Math.min(k, Math.abs(d - 0.065) / 0.065);
s += 2.4 + ((Math.sin(s * 12.9898 + seed) + 1) / 2) * 2.2;
}
return k;
}
/** Fala do trecho: palavras com tempo (narração) e, se houver, o volume do áudio quadro a quadro. */
export type Speech = { words: SpokenWord[]; env?: { values: number[]; fps: number } };
/** Fim da fala: o fim da palavra `cueEnd` (depois do início), senão início + dur. */
function endOf(a: Action, s: number, words: SpokenWord[]): number | null {
if (!a.cueEnd) return null;
const c = norm(a.cueEnd);
const w = words.find((x) => x.startS >= s - 0.01 && norm(x.text).startsWith(c));
return w ? w.endS : null;
}
export function evaluate(actor: ActorInput, t: number, durationS: number, seed = 1, speech: Speech = { words: [] }): ActorState {
const words = speech.words;
const st: ActorState = {
face: faceOf(actor.expression, actor.face), body: bodyOf(actor.pose, actor.body),
x: actor.x, dy: 0, dx: 0, rot: 0, sx: 1, sy: 1, flip: !!actor.flip, emote: null,
};
const timeline = (actor.timeline ?? []).map((a) => ({ a, s: startOf(a, durationS, words) })).sort((p, q) => p.s - q.s);
for (const { a, s } of timeline) {
if (t < s) break;
const end = a.do === "talk" ? endOf(a, s, words) : null;
const d = Math.max(0.05, end !== null ? end - s : a.dur ?? DEFAULT_DUR[a.do]);
const p = clamp01((t - s) / d);
const active = t - s < d;
const env = active ? Math.min(1, (t - s) / 0.15, (s + d - t) / 0.15) : 0; // entra e sai suave (momentâneas)
switch (a.do) {
case "express": {
const target = a.expression ? faceOf(a.expression, a.face) : withFace(st.face, a.face);
st.face = blendFace(st.face, target, ease(p));
break;
}
case "pose": {
const target = a.pose ? bodyOf(a.pose, a.body) : withBody(st.body, a.body);
st.body = blendBody(st.body, target, clamp01(easeBack(p)));
break;
}
case "walk": case "run": case "enter": case "exit": {
const from = a.do === "enter" ? (a.to ?? st.x) < 0.5 ? -0.25 : 1.25 : st.x;
const to = a.do === "exit" ? (st.x < 0.5 ? -0.3 : 1.3) : a.to ?? st.x;
const run = a.do === "run";
st.x = from + (to - from) * (run ? p : ease(p));
if (to !== from) st.flip = to < from;
if (active) {
const phase = (t - s) * Math.PI * 2 * (run ? 3.2 : 2.1);
const amp = run ? 1.6 : 1;
const sw = Math.sin(phase);
st.body = withBody(st.body, {
armL: { raise: 8 + sw * 20 * amp, bend: run ? 85 : 15 }, armR: { raise: 8 - sw * 20 * amp, bend: run ? 85 : 15 },
legL: { raise: 3 + Math.max(0, sw) * 6, bend: Math.max(0, sw) * 38 * amp }, legR: { raise: 3 + Math.max(0, -sw) * 6, bend: Math.max(0, -sw) * 38 * amp },
lean: (to < from ? -1 : 1) * (run ? 8 : 3),
});
st.dy -= Math.abs(Math.sin(phase)) * (run ? 0.012 : 0.006);
}
break;
}
case "jump": {
if (!active) break;
const h = a.height ?? 0.08;
if (p < 0.15) { st.sy *= 1 - 0.1 * (p / 0.15); st.sx *= 1 + 0.06 * (p / 0.15); st.body = withBody(st.body, { crouch: 0.35 * (p / 0.15) }); }
else if (p < 0.85) {
const q = (p - 0.15) / 0.7;
st.dy -= h * 4 * q * (1 - q);
st.sy *= 1.07; st.sx *= 0.95;
st.body = withBody(st.body, { arms: { raise: 120, bend: -10 }, legs: { raise: 6, bend: 30 } });
} else { const q = (p - 0.85) / 0.15; st.sy *= 1 - 0.08 * (1 - q); st.sx *= 1 + 0.05 * (1 - q); }
break;
}
case "nod": st.body = withBody(st.body, { headNod: st.body.headNod + Math.sin(p * Math.PI * 2 * (a.times ?? 2)) * 0.6 * env }); break;
case "shake_head": st.body = withBody(st.body, { headTurn: st.body.headTurn + Math.sin(p * Math.PI * 2 * (a.times ?? 2)) * 0.7 * env }); break;
case "tremble": if (active) { st.dx += Math.sin(t * 77.7) * 0.004 * env; st.dy += Math.cos(t * 91.3) * 0.002 * env; } break;
case "bounce": st.dy -= Math.abs(Math.sin(p * Math.PI * (a.times ?? 2))) * 0.02 * env; break;
case "fall": {
const side = a.dir === "right" ? 1 : -1;
st.rot = side * 88 * ease(p);
st.dy += 0.02 * ease(p);
st.face = blendFace(st.face, faceOf("shocked"), Math.min(1, p * 3));
break;
}
case "sit": st.body = blendBody(st.body, withBody(st.body, { crouch: 1, arms: { raise: 14, bend: 40 } }), ease(p)); break;
case "stand_up": st.body = blendBody(st.body, withBody(st.body, { crouch: 0 }), ease(p)); break;
case "turn": {
const flipped = !st.flip;
if (p >= 0.5) st.flip = flipped;
if (active) st.sx *= Math.max(0.15, Math.abs(Math.cos(p * Math.PI)));
break;
}
case "talk": {
if (!active) break;
// Palavras da narração dentro da fala; sem elas, o texto da ação repartido pela duração (vogal pesa mais).
let spoken = words.filter((w) => w.endS > s && w.startS < s + d);
if (!spoken.length && a.text) {
const list = a.text.split(/\s+/).filter(Boolean);
const total = list.reduce((n, w) => n + w.length + 1, 0);
let c = s;
spoken = list.map((w) => { const len = (d * (w.length + 1)) / total; const out = { text: w, startS: c, endS: c + len * 0.88 }; c += len; return out; });
}
if (spoken.length) {
st.face = speak(st.face, visemeAt(spoken, t, speech.env), Math.min(1, (t - s) / 0.08, (s + d - t) / 0.08 + 0.2), emphasisAt(t, speech.env));
} else {
const flap = Math.abs(Math.sin((t - s) * Math.PI * 2 * 4.3 + seed)) * (0.6 + 0.4 * Math.sin((t - s) * 9.1 + seed));
st.face = { ...st.face, mouthOpen: Math.max(st.face.mouthOpen, (0.12 + 0.5 * flap) * env), teeth: st.face.teeth || flap > 0.6 };
}
// Quem fala mexe a cabeça de leve e acompanha as sílabas fortes.
st.body = withBody(st.body, { headTilt: st.body.headTilt + Math.sin((t - s) * 5.3) * 2 * env, headNod: st.body.headNod + emphasisAt(t, speech.env) * 0.25 });
break;
}
case "look": {
const gx = a.dir === "left" ? -0.9 : a.dir === "right" ? 0.9 : 0;
const gy = a.dir === "up" ? -0.8 : a.dir === "down" ? 0.8 : 0;
const k = ease(p);
st.face = { ...st.face, gazeX: st.face.gazeX + (gx - st.face.gazeX) * k, gazeY: st.face.gazeY + (gy - st.face.gazeY) * k };
st.body = withBody(st.body, { headTurn: st.body.headTurn + (gx * 0.5 - st.body.headTurn) * k, headNod: st.body.headNod + (gy * -0.4 - st.body.headNod) * k });
break;
}
case "emote": if (active) st.emote = { text: a.text ?? "!", k: env }; break;
// Martelar: braço direito sobe e desce batendo (`times` golpes), cabeça acompanha cada batida.
case "hammer": if (active) {
const beat = Math.abs(Math.sin(p * Math.PI * (a.times ?? 5)));
st.body = withBody(st.body, { armR: { raise: 40 + beat * 95 * Math.min(1, env * 1.5), bend: 60 + beat * 40 }, headNod: st.body.headNod + (1 - beat) * 0.15 * env });
break;
}
case "wave": if (active) st.body = withBody(st.body, { armR: { raise: 140 * Math.min(1, env * 1.5), bend: -25 + Math.sin(p * Math.PI * 2 * (a.times ?? 3)) * 30 } }); break;
}
}
// Vida: piscar (a não ser de olhos quase fechados), respirar e um balanço leve de cabeça.
const blink = blinkAt(t, seed);
if (blink < 1) st.face = { ...st.face, eyeL: st.face.eyeL * Math.max(0.08, blink), eyeR: st.face.eyeR * Math.max(0.08, blink) };
st.body = withBody(st.body, { headTilt: st.body.headTilt + Math.sin(t * 0.9 + seed) * 1.2 });
return st;
}
/** Confere uma linha do tempo (lista de problemas; vazia = ok). */
export function validateTimeline(timeline: unknown): string[] {
if (timeline === undefined) return [];
if (!Array.isArray(timeline) || timeline.length > 40) return ["timeline: lista de até 40 ações"];
const errors: string[] = [];
timeline.forEach((a: Partial<Action>, i) => {
if (!a || !ACTIONS.includes(a.do as ActionKind)) errors.push(`timeline[${i}].do: ${ACTIONS.join(", ")}`);
for (const k of ["at", "atP", "dur", "to", "times", "height"] as const) {
if (a[k] !== undefined && (typeof a[k] !== "number" || !Number.isFinite(a[k]))) errors.push(`timeline[${i}].${k}: número`);
}
if (a.atP !== undefined && !(a.atP >= 0 && a.atP <= 1)) errors.push(`timeline[${i}].atP entre 0 e 1`);
if (a.dur !== undefined && !(a.dur > 0 && a.dur <= 30)) errors.push(`timeline[${i}].dur entre 0 e 30 s`);
});
return errors;
}
@@ -0,0 +1,167 @@
// Rig do personagem: o rosto e o corpo são PARÂMETROS contínuos, não desenhos prontos. Uma expressão ou uma
// pose é só um conjunto de valores; dá para misturar (blend), ajustar um valor ("sorriso 0,3 a mais") e criar
// novas sem mexer no desenho. Ângulos em graus; "para fora" positivo nos dois lados (o desenho espelha).
export type FaceParams = {
/** Sobrancelha: y (px; negativo sobe) e tilt (graus; positivo = ponta de dentro sobe, como triste/preocupado). */
browL: { y: number; tilt: number };
browR: { y: number; tilt: number };
/** Abertura dos olhos (0 fechado · 1 normal · 1,35 arregalado). */
eyeL: number;
eyeR: number;
/** Tamanho da pupila (0,4 pavor · 1 normal · 1,3 encantado). */
pupil: number;
/** Direção do olhar (-1…1). */
gazeX: number;
gazeY: number;
/** Boca: abertura 0…1, sorriso -1 (triste) … 1 (feliz), largura 0,5…1,4, dentes à mostra. */
mouthOpen: number;
smile: number;
mouthWidth: number;
/** Arredondamento dos lábios (0 normal … 1 bico de "o/u"): vem da fala (lipsync.ts). */
mouthRound: number;
/** Pálpebra de cima somada à de base do personagem (−0,5 arregala … 0,6 quase fecha). */
lid: number;
teeth: boolean;
/** Extras: rubor 0…1, gota de suor, lágrimas, veia de raiva. */
blush: number;
sweat: boolean;
tears: boolean;
anger: boolean;
};
export type Limb = {
/** Abertura a partir do corpo (0 = para baixo; 90 = horizontal para fora; 180 = para cima). */
raise: number;
/** Dobra do cotovelo/joelho (positivo = antebraço/canela para dentro, na frente do corpo). */
bend: number;
};
export type BodyParams = {
/** Inclinação do tronco (graus; positivo = para a direita de quem olha). */
lean: number;
/** Cabeça: inclinação (graus), virada (-1…1, finge 3/4) e aceno (-1 olha para cima … 1 para baixo). */
headTilt: number;
headTurn: number;
headNod: number;
armL: Limb;
armR: Limb;
legL: Limb;
legR: Limb;
/** Agachar/sentar: 0 em pé … 1 sentado (quadril desce, coxa encurta em perspectiva). */
crouch: number;
};
export const NEUTRAL_FACE: FaceParams = {
browL: { y: 0, tilt: 0 }, browR: { y: 0, tilt: 0 }, eyeL: 1, eyeR: 1, pupil: 1, gazeX: 0, gazeY: 0,
mouthOpen: 0, smile: 0.1, mouthWidth: 1, mouthRound: 0, lid: 0, teeth: false, blush: 0, sweat: false, tears: false, anger: false,
};
export const NEUTRAL_BODY: BodyParams = {
lean: 0, headTilt: 0, headTurn: 0, headNod: 0,
armL: { raise: 8, bend: 6 }, armR: { raise: 8, bend: 6 }, legL: { raise: 2, bend: 0 }, legR: { raise: 2, bend: 0 }, crouch: 0,
};
type FacePatch = Partial<Omit<FaceParams, "browL" | "browR">> & { browL?: Partial<FaceParams["browL"]>; browR?: Partial<FaceParams["browR"]>; brows?: Partial<FaceParams["browL"]>; eyes?: number };
type BodyPatch = Partial<Omit<BodyParams, "armL" | "armR" | "legL" | "legR">> & { armL?: Partial<Limb>; armR?: Partial<Limb>; legL?: Partial<Limb>; legR?: Partial<Limb>; arms?: Partial<Limb>; legs?: Partial<Limb> };
/** Aplica um ajuste parcial (aceita `brows`/`eyes`/`arms`/`legs` para os dois lados de uma vez). */
export function withFace(base: FaceParams, p: FacePatch = {}): FaceParams {
const { brows, eyes, browL, browR, ...rest } = p;
return {
...base, ...rest,
browL: { ...base.browL, ...brows, ...browL }, browR: { ...base.browR, ...brows, ...browR },
eyeL: rest.eyeL ?? eyes ?? base.eyeL, eyeR: rest.eyeR ?? eyes ?? base.eyeR,
};
}
export function withBody(base: BodyParams, p: BodyPatch = {}): BodyParams {
const { arms, legs, armL, armR, legL, legR, ...rest } = p;
return {
...base, ...rest,
armL: { ...base.armL, ...arms, ...armL }, armR: { ...base.armR, ...arms, ...armR },
legL: { ...base.legL, ...legs, ...legL }, legR: { ...base.legR, ...legs, ...legR },
};
}
/** Expressões prontas = atalhos de parâmetros (dá para ajustar qualquer valor por cima com `face`). */
export const EXPRESSION_PRESETS = {
neutral: {},
smile: { smile: 0.7, eyes: 0.9 },
happy: { smile: 0.9, mouthOpen: 0.3, teeth: true, eyes: 0.85, brows: { y: -3 } },
laugh: { smile: 1, mouthOpen: 0.75, teeth: true, eyes: 0.18, brows: { y: -5 }, blush: 0.4 },
proud: { smile: 0.6, lid: 0.35, brows: { y: -2 } },
sad: { smile: -0.7, brows: { tilt: 16 }, eyes: 0.8, gazeY: 0.5 },
cry: { smile: -0.9, mouthOpen: 0.35, brows: { tilt: 20 }, eyes: 0.4, tears: true },
worried: { smile: -0.3, brows: { tilt: 14, y: -2 }, eyes: 1.05, sweat: true },
angry: { smile: -0.4, brows: { tilt: -18, y: 3 }, lid: 0.25, mouthWidth: 0.9 },
furious: { smile: -0.6, mouthOpen: 0.6, teeth: true, brows: { tilt: -24, y: 4 }, lid: 0.3, anger: true },
surprised: { mouthOpen: 0.6, mouthWidth: 0.55, smile: 0, brows: { y: -8 }, eyes: 1.25, pupil: 0.8, lid: -0.5 },
scared: { mouthOpen: 0.5, mouthWidth: 0.9, smile: -0.5, teeth: true, brows: { tilt: 18, y: -6 }, eyes: 1.3, pupil: 0.55, sweat: true, lid: -0.5 },
shocked: { mouthOpen: 0.95, mouthWidth: 0.6, smile: 0, brows: { y: -10 }, eyes: 1.35, pupil: 0.45, lid: -0.5 },
suspicious: { smile: -0.1, mouthWidth: 0.8, browL: { y: -6, tilt: 0 }, browR: { y: 4, tilt: -10 }, lid: 0.45, gazeX: 0.6 },
smirk: { smile: 0.45, mouthWidth: 0.8, browL: { y: -5 }, lid: 0.3, gazeX: -0.3 },
confused: { smile: -0.2, mouthWidth: 0.75, browL: { y: -7 }, browR: { tilt: -8 }, gazeY: -0.6, gazeX: 0.4 },
disgusted: { smile: -0.7, mouthWidth: 1.1, brows: { tilt: -10, y: 2 }, lid: 0.35 },
sleepy: { lid: 0.6, brows: { y: 3 }, mouthOpen: 0.1, smile: 0 },
determined: { smile: 0.1, mouthWidth: 0.85, brows: { tilt: -10, y: 2 }, lid: 0.2 },
embarrassed: { smile: 0.3, blush: 1, gazeY: 0.6, gazeX: -0.4, eyes: 0.8, sweat: true },
} satisfies Record<string, FacePatch>;
/** Poses prontas = atalhos de ângulos (ajustáveis por cima com `body`). */
export const POSE_PRESETS = {
stand: {},
point: { armR: { raise: 46, bend: -128 } },
wave: { armR: { raise: 140, bend: -25 } },
hold: { armR: { raise: 34, bend: 106 } },
arms_up: { arms: { raise: 158, bend: -10 } },
celebrate: { arms: { raise: 146, bend: -26 }, headNod: -0.35 },
shrug: { arms: { raise: 38, bend: 100 }, headTilt: 7 },
think: { armR: { raise: -24, bend: 138 }, headTilt: -5 },
hands_on_hips: { arms: { raise: 42, bend: 105 } },
cross_arms: { arms: { raise: 24, bend: 128 } },
facepalm: { armR: { raise: 125, bend: -103 }, headNod: 0.5, headTilt: 8 },
cover_mouth: { armR: { raise: -34, bend: 130 } },
defend: { arms: { raise: 62, bend: 118 }, lean: -4 },
reach: { armR: { raise: 68, bend: -15 }, lean: 6 },
sit: { crouch: 1, arms: { raise: 14, bend: 40 } },
kneel: { crouch: 0.6, arms: { raise: 10, bend: 20 } },
lean_in: { lean: 8, headTilt: 6 },
// Duas mãos segurando um objeto largo (livro, tábua) pelas bordas, na frente do peito.
hold_both: { arms: { raise: 42, bend: 104 } },
// Joinha: cotovelo dobrado, mão na altura do peito/ombro (a forma da mão vem do desenho: `thumbs_up`).
thumbs_up: { armR: { raise: 22, bend: 148 } },
} satisfies Record<string, BodyPatch>;
export type ExpressionName = keyof typeof EXPRESSION_PRESETS;
export type PoseName = keyof typeof POSE_PRESETS;
export const EXPRESSION_NAMES = Object.keys(EXPRESSION_PRESETS) as ExpressionName[];
export const POSE_NAMES = Object.keys(POSE_PRESETS) as PoseName[];
export const faceOf = (name: string | undefined, patch?: FacePatch): FaceParams =>
withFace(withFace(NEUTRAL_FACE, (EXPRESSION_PRESETS as Record<string, FacePatch>)[name ?? "neutral"] ?? {}), patch);
export const bodyOf = (name: string | undefined, patch?: BodyPatch): BodyParams =>
withBody(withBody(NEUTRAL_BODY, (POSE_PRESETS as Record<string, BodyPatch>)[name ?? "stand"] ?? {}), patch);
const lerp = (a: number, b: number, k: number) => a + (b - a) * k;
const limb = (a: Limb, b: Limb, k: number): Limb => ({ raise: lerp(a.raise, b.raise, k), bend: lerp(a.bend, b.bend, k) });
/** Mistura duas expressões (k = 0 → a, 1 → b). Os "liga/desliga" trocam na metade. */
export function blendFace(a: FaceParams, b: FaceParams, k: number): FaceParams {
const pick = <T,>(x: T, y: T) => (k < 0.5 ? x : y);
return {
browL: { y: lerp(a.browL.y, b.browL.y, k), tilt: lerp(a.browL.tilt, b.browL.tilt, k) },
browR: { y: lerp(a.browR.y, b.browR.y, k), tilt: lerp(a.browR.tilt, b.browR.tilt, k) },
eyeL: lerp(a.eyeL, b.eyeL, k), eyeR: lerp(a.eyeR, b.eyeR, k), pupil: lerp(a.pupil, b.pupil, k),
gazeX: lerp(a.gazeX, b.gazeX, k), gazeY: lerp(a.gazeY, b.gazeY, k),
mouthOpen: lerp(a.mouthOpen, b.mouthOpen, k), smile: lerp(a.smile, b.smile, k), mouthWidth: lerp(a.mouthWidth, b.mouthWidth, k), mouthRound: lerp(a.mouthRound, b.mouthRound, k), lid: lerp(a.lid, b.lid, k),
teeth: pick(a.teeth, b.teeth), blush: lerp(a.blush, b.blush, k), sweat: pick(a.sweat, b.sweat), tears: pick(a.tears, b.tears), anger: pick(a.anger, b.anger),
};
}
export function blendBody(a: BodyParams, b: BodyParams, k: number): BodyParams {
return {
lean: lerp(a.lean, b.lean, k), headTilt: lerp(a.headTilt, b.headTilt, k), headTurn: lerp(a.headTurn, b.headTurn, k), headNod: lerp(a.headNod, b.headNod, k),
armL: limb(a.armL, b.armL, k), armR: limb(a.armR, b.armR, k), legL: limb(a.legL, b.legL, k), legR: limb(a.legR, b.legR, k), crouch: lerp(a.crouch, b.crouch, k),
};
}
export type { FacePatch, BodyPatch };
@@ -0,0 +1,9 @@
// Versão REDUZIDA do contrato do CenaForge (cartoon/src/spec.ts): só os tipos que o desenho do personagem usa.
// No projeto real este arquivo é bem maior (cena, lugar, animais, textos…); não é preciso mexer nele.
export const TIMES = ["night", "dawn", "day"] as const;
export type TimeOfDay = (typeof TIMES)[number];
export const ICONS = ["house", "generator", "fuel", "battery", "phone", "door", "eye", "bulb", "solar", "warning", "money", "clock",
"olive", "hammer", "tablet", "book", "ruler"] as const;
export type IconId = (typeof ICONS)[number];
export const TONES = ["info", "danger", "ok"] as const;
export type Tone = (typeof TONES)[number];
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"noEmit": true
},
"include": ["src", "render-sheet.tsx"]
}
+2
View File
@@ -23,3 +23,5 @@ este resumo basta, não é preciso abrir o `CLAUDE.md` inteiro.
`frame_check.py` e abra só a imagem que ele indicar (uma por render). Reaproveite as cenas da biblioteca.
- **Windows/PowerShell:** rode o pnpm como `pnpm.cmd` (o `pnpm.ps1` é bloqueado pela política de
execução) e leia texto com `Get-Content -Raw -Encoding UTF8`. Economize: leia só o que a tarefa pede.
+41
View File
@@ -0,0 +1,41 @@
{
"schemaVersion": 1,
"id": "cam",
"name": "Cam",
"kind": "cartoon",
"look": {
"build": "heavy",
"height": 1,
"skin": "#9a6440",
"hair": {
"style": "curly",
"color": "#3a2a1e"
},
"beard": {
"style": "stubble",
"color": "#3a2a1e"
},
"glasses": "none",
"brows": "thin",
"top": {
"style": "robe",
"color": "#56704a",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "round",
"lids": 0.1,
"wrinkles": 0,
"head": "wide",
"belly": true
},
"caption": "Filho de Noé",
"description": "homem de 40 anos, moreno, forte, cabelo cacheado preto, barba por fazer, túnica verde, sandália",
"createdAt": "2026-11-18T03:23:14.030Z",
"updatedAt": "2026-11-18T03:23:57.151Z"
}
@@ -0,0 +1,40 @@
{
"schemaVersion": 1,
"id": "esposa-de-noe",
"name": "Esposa de Noé",
"kind": "cartoon",
"look": {
"build": "average",
"height": 0.92,
"skin": "#d09a70",
"hair": {
"style": "long",
"color": "#c9c9cf"
},
"beard": {
"style": "none",
"color": "#a9a9b0"
},
"glasses": "none",
"brows": "thick",
"top": {
"style": "robe",
"color": "#8a6f9e",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "button",
"lids": 0.3,
"wrinkles": 0.7,
"head": "round"
},
"caption": "Família de Noé",
"description": "senhora idosa, mulher, cabelo longo grisalho, túnica roxa, sandália, rugas, olhar gentil",
"createdAt": "2026-11-18T03:23:13.978Z",
"updatedAt": "2026-11-18T03:23:57.084Z"
}
+40
View File
@@ -0,0 +1,40 @@
{
"schemaVersion": 1,
"id": "jafe",
"name": "Jafé",
"kind": "cartoon",
"look": {
"build": "slim",
"height": 1.08,
"skin": "#d4a074",
"hair": {
"style": "side",
"color": "#6b4226"
},
"beard": {
"style": "goatee",
"color": "#6b4226"
},
"glasses": "none",
"brows": "thin",
"top": {
"style": "robe",
"color": "#c8443a",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "round",
"lids": 0.1,
"wrinkles": 0,
"head": "round"
},
"caption": "Filho de Noé",
"description": "homem de 35 anos, magro, alto, cabelo repartido castanho, cavanhaque, túnica vermelha, sandália",
"createdAt": "2026-11-18T03:23:14.057Z",
"updatedAt": "2026-11-18T03:23:57.183Z"
}
+40
View File
@@ -0,0 +1,40 @@
{
"schemaVersion": 1,
"id": "noe",
"name": "Noé",
"kind": "cartoon",
"look": {
"build": "slim",
"height": 0.96,
"skin": "#c98a5e",
"hair": {
"style": "long",
"color": "#e2e2e8"
},
"beard": {
"style": "long",
"color": "#eeeef2"
},
"glasses": "none",
"brows": "thick",
"top": {
"style": "robe",
"color": "#a8865a",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "long",
"lids": 0.5,
"wrinkles": 0.85,
"head": "oval"
},
"caption": "Construtor da arca",
"description": "idoso de 600 anos, barba branca longa, cabelo longo grisalho, túnica, sandália, rugas, pálpebra caída, olhar sereno, magro",
"createdAt": "2026-11-18T03:23:13.290Z",
"updatedAt": "2026-11-18T03:23:57.049Z"
}
+40
View File
@@ -0,0 +1,40 @@
{
"schemaVersion": 1,
"id": "sem",
"name": "Sem",
"kind": "cartoon",
"look": {
"build": "average",
"height": 1.02,
"skin": "#c08055",
"hair": {
"style": "short",
"color": "#6b4226"
},
"beard": {
"style": "full",
"color": "#6b4226"
},
"glasses": "none",
"brows": "thin",
"top": {
"style": "robe",
"color": "#2f6db3",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "round",
"lids": 0.1,
"wrinkles": 0.4,
"head": "round"
},
"caption": "Filho de Noé",
"description": "homem de 45 anos, barba cheia castanha, cabelo curto castanho, túnica azul, sandália",
"createdAt": "2026-11-18T03:23:14.006Z",
"updatedAt": "2026-11-18T03:23:57.118Z"
}
@@ -0,0 +1,93 @@
Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+3 -1
View File
@@ -26,6 +26,8 @@
"exports": {
"./character": "./src/character.ts",
"./figure": "./src/CharacterFigure.tsx",
"./spec": "./src/spec.ts"
"./spec": "./src/spec.ts",
"./motion": "./src/motion.ts",
"./rig": "./src/rig.ts"
}
}
+36
View File
@@ -45,6 +45,42 @@ function readJobs(): Job[] {
async function still() {
const propsFile = arg("props");
const out = arg("out");
// `--still --spec <trecho.json> --out <png> [--frame N]`: um quadro de um trecho (conferir peças sem gerar o vídeo).
// `--still --list <lista.json>` ([{spec, out, frame?}]): vários quadros num empacotamento só (folhas de conferência).
const listFile = arg("list");
if (listFile) {
const list = JSON.parse(fs.readFileSync(resolve(listFile), "utf8")) as { spec: string; out: string; frame?: number }[];
const serveUrl = await bundle({ entryPoint: path.join(HERE, "src", "index.ts"), publicDir: path.join(REPO, "assets") });
const results: { out: string; frames: number; ms: number }[] = [];
for (const item of list) {
const t0 = Date.now();
const spec = JSON.parse(fs.readFileSync(resolve(item.spec), "utf8")) as ShotSpec;
const errors = validateSpec(spec);
if (errors.length) throw new Error(`${item.spec}: ${errors.join("; ")}`);
const inputProps = spec as unknown as Record<string, unknown>;
const composition = await selectComposition({ serveUrl, id: "Shot", inputProps });
fs.mkdirSync(path.dirname(resolve(item.out)), { recursive: true });
const frame = Math.min(frameCount(spec) - 1, item.frame ?? Math.floor(frameCount(spec) / 2));
await renderStill({ composition, serveUrl, inputProps, output: resolve(item.out), frame, imageFormat: "png", browserExecutable: process.env.CARTOON_CHROME || null });
results.push({ out: path.relative(REPO, resolve(item.out)).replace(/\\/g, "/"), frames: 1, ms: Date.now() - t0 });
}
console.log(JSON.stringify({ ok: true, results }));
return;
}
const specFile = arg("spec");
if (specFile && out) {
const spec = JSON.parse(fs.readFileSync(resolve(specFile), "utf8")) as ShotSpec;
const errors = validateSpec(spec);
if (errors.length) throw new Error(`spec: ${errors.join("; ")}`);
const serveUrl = await bundle({ entryPoint: path.join(HERE, "src", "index.ts"), publicDir: path.join(REPO, "assets") });
const inputProps = spec as unknown as Record<string, unknown>;
const composition = await selectComposition({ serveUrl, id: "Shot", inputProps });
fs.mkdirSync(path.dirname(resolve(out)), { recursive: true });
const frame = Math.min(frameCount(spec) - 1, Number(arg("frame") ?? Math.floor(frameCount(spec) / 2)));
await renderStill({ composition, serveUrl, inputProps, output: resolve(out), frame, imageFormat: "png", browserExecutable: process.env.CARTOON_CHROME || null });
console.log(JSON.stringify({ ok: true, results: [{ out: path.relative(REPO, resolve(out)).replace(/\\/g, "/"), frames: 1, ms: 0 }] }));
return;
}
if (!propsFile || !out) throw new Error("--still precisa de --props e --out");
const inputProps = JSON.parse(fs.readFileSync(resolve(propsFile), "utf8")) as Record<string, unknown>;
const looks = (inputProps.figures as { look: unknown }[] | undefined) ?? [];
+15 -4
View File
@@ -3,7 +3,7 @@
import React from "react";
import { AbsoluteFill, useCurrentFrame, useVideoConfig } from "remotion";
import { CharacterFigure } from "./CharacterFigure";
import { TagLabel } from "./overlays";
import { Grain, TagLabel } from "./overlays";
import { loadFonts } from "./theme";
import type { CharacterLook, Expression, Pose } from "./character";
import type { IconId } from "./spec";
@@ -13,25 +13,36 @@ loadFonts();
export type CardProps = {
width: number; height: number;
background?: string;
/** "face": enquadra só a cabeça (conferir expressões de perto). */
framing?: "full" | "face";
figures: { look: CharacterLook; expression?: Expression; pose?: Pose; item?: IconId; label?: string }[];
};
export function CharacterCard({ figures, background = "#2a2e45" }: CardProps) {
export function CharacterCard({ figures, background = "#2a2e45", framing = "full" }: CardProps) {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const n = Math.max(1, figures.length);
return (
<AbsoluteFill style={{ background, containerType: "size" }}>
<div style={{ position: "absolute", inset: "8% 2% 4%", display: "grid", gridTemplateColumns: `repeat(${n}, 1fr)`, alignItems: "end" }}>
<div style={{ position: "absolute", inset: "8% 2% 4%", display: "grid", gridTemplateColumns: `repeat(${n}, minmax(0, 1fr))`, alignItems: "end" }}>
{figures.map((f, i) => (
<div key={i} style={{ position: "relative", height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "flex-end" }}>
{f.label && <div style={{ marginBottom: "4%" }}><TagLabel text={f.label} size={n > 3 ? 2.2 : 3.4} /></div>}
<div style={{ width: "90%", aspectRatio: "200 / 440", maxHeight: "86%" }}>
{framing === "face" ? (
<div style={{ width: "92%", aspectRatio: "1 / 1", overflow: "hidden", position: "relative" }}>
<div style={{ position: "absolute", left: "-15%", top: "-36%", width: "130%", aspectRatio: "200 / 440" }}>
<CharacterFigure look={f.look} expression={f.expression} pose={f.pose} item={f.item} t={frame / fps} />
</div>
</div>
) : (
<div style={{ width: "90%", aspectRatio: "200 / 440", maxHeight: "86%" }}>
<CharacterFigure look={f.look} expression={f.expression} pose={f.pose} item={f.item} t={frame / fps} />
</div>
)}
</div>
))}
</div>
<Grain />
</AbsoluteFill>
);
}
File diff suppressed because it is too large Load Diff
+72 -16
View File
@@ -4,10 +4,12 @@ import React from "react";
import { AbsoluteFill, useCurrentFrame, useVideoConfig } from "remotion";
import { CrowdFigure, PersonFigure } from "./actors";
import { Icon } from "./icons";
import { Captions, CrossOut, Hud, Rings, TagLabel, TextLayer, pop, shake } from "./overlays";
import { Captions, CrossOut, Grain, Hud, Rings, TagLabel, TextLayer, pop, shake } from "./overlays";
import { SceneBackground } from "./scenes";
import { CharacterFigure } from "./CharacterFigure";
import { LightLayer } from "./places";
import { CharacterFigure, HandsInsert } from "./CharacterFigure";
import { evaluate } from "./motion";
import { LightLayer, PlaceForeground, WeatherLayer } from "./places";
import { AnimalFigure, BIRDS, SPECIES_HEIGHT } from "./animals";
import type { ShotSpec } from "./spec";
import { loadFonts } from "./theme";
@@ -28,23 +30,74 @@ export function Shot(spec: ShotSpec) {
const k = pop(frame, fps, a.enterS ?? 0);
if (a.kind === "crowd") {
return (
<div key={i} style={{ position: "absolute", left: "-2%", width: "104%", top: `${(a.y - 0.16) * 100}%`, height: "16%",
<div key={i} style={{ position: "absolute", left: "-2%", width: "104%", top: `${(a.y - 0.34) * 100}%`, height: "34%",
opacity: k, transform: `translateY(${(1 - k) * 8}%)` }}>
<CrowdFigure c={a} frame={frame} />
<CrowdFigure c={a} frame={frame} fps={fps} />
</div>
);
}
if (a.character) {
// Personagem da biblioteca: mesmo visual em toda cena; muda expressão, pose e objeto na mão.
const ch = height * 0.36 * (a.scale ?? 1);
const cw = (ch * 200) / 440;
const label = a.label ?? a.character.name;
if (a.kind === "animal") {
// Animal (ou fila/casal): anda de x até walk.to; ave voando sobe e desce em onda. Olha para onde anda.
const t = frame / fps;
const w = a.walk;
const s0 = w?.startS ?? 0;
const d = w?.dur ?? Math.max(0.5, spec.durationS - s0);
const p = w ? Math.max(0, Math.min(1, (t - s0) / d)) : 0;
const moving = !!w && t >= s0 && p < 1;
const flip = w ? w.to < a.x !== !!a.flip : !!a.flip;
const h = height * SPECIES_HEIGHT[a.species] * (a.scale ?? 1);
const n = a.count ?? 1;
const gap = a.gap ?? 0.16 * (a.scale ?? 1) * (SPECIES_HEIGHT[a.species] / 0.12);
const dir = w ? Math.sign(w.to - a.x) || 1 : flip ? -1 : 1;
const fly = !!a.fly && BIRDS.includes(a.species);
return (
<div key={i} style={{ position: "absolute", left: a.x * width - cw / 2, top: a.y * height - ch, width: cw, height: ch,
opacity: Math.min(1, k * 1.5), transform: `translateY(${(1 - k) * 10}%) scaleX(${a.flip ? -1 : 1})` }}>
<CharacterFigure look={a.character.look} expression={a.expression} pose={a.pose} item={a.item} t={frame / fps} />
{label && (
<div style={{ position: "absolute", left: "50%", top: "-15%", transform: `translateX(-50%) scaleX(${a.flip ? -1 : 1})`, textAlign: "center" }}>
<React.Fragment key={i}>
{Array.from({ length: n }, (_, j) => (a.pair ? [0, 1] : [0]).map((m) => {
const x0 = a.x - dir * j * gap + (w ? (w.to - a.x) * p : 0);
const y = a.y - m * 0.012 + (fly ? Math.sin(t * 2.4 + j) * 0.012 : 0);
const x = x0 - dir * m * gap * 0.35;
return (
<div key={`${j}-${m}`} style={{ position: "absolute", left: x * width - h / 2, top: y * height - h, width: h, height: h,
opacity: Math.min(1, k * 1.5), transform: `scale(${flip ? -1 : 1}, 1) translateY(${(1 - k) * 10}%)`, zIndex: m ? 0 : 1 }}>
<AnimalFigure species={a.species} color={a.color} t={t} walking={moving && !fly} flying={fly} carry={a.carry} seed={j * 3 + m} />
</div>
);
}))}
</React.Fragment>
);
}
if (a.character) {
// Personagem da biblioteca: mesmo visual em toda cena. Expressão, pose, andar, pular, falar… saem da
// linha do tempo (motion.ts), com a boca na fala (palavras + volume do áudio).
const t = frame / fps;
const st = evaluate({ x: a.x, expression: a.expression, pose: a.pose, face: a.face, body: a.body, flip: a.flip, timeline: a.timeline },
t, spec.durationS, spec.seed + i * 13, { words: spec.words ?? [], env: spec.audioEnv });
// Vista "insert": close das mãos (antebraços entrando por baixo) segurando o objeto.
if (a.framing === "insert") {
return (
<div key={i} style={{ position: "absolute", left: "-6%", width: "112%", top: `${(0.92 - 0.62) * 100}%`, aspectRatio: "1 / 1", opacity: Math.min(1, k * 1.5),
transform: `translateY(${(1 - k) * 8}%)` }}>
<HandsInsert look={a.character.look} item={a.item} t={t} />
</div>
);
}
// Caixa do desenho (200×440, cabeça ~1/3): corpo inteiro ~52% da altura do quadro; meio corpo corta nos
// joelhos; close corta na cintura, com a cabeça ocupando ~1/3 do quadro.
const box = a.framing === "close" ? 1.05 : a.framing === "medium" ? 0.8 : 0.52 * (a.scale ?? 1);
const zoom = box / 0.52;
const ch = height * box;
const cw = (ch * 200) / 440;
const baseY = a.framing === "close" ? 1.17 : a.framing === "medium" ? 1.04 : a.y;
const label = a.label ?? a.character.name;
const showLabel = label && Math.abs(st.rot) < 30;
return (
<div key={i} style={{ position: "absolute", left: (st.x + st.dx) * width - cw / 2, top: (baseY + st.dy) * height - ch, width: cw, height: ch,
opacity: Math.min(1, k * 1.5), transformOrigin: "50% 100%",
transform: `translateY(${(1 - k) * 10}%) rotate(${st.rot}deg) scale(${(st.flip ? -1 : 1) * st.sx}, ${st.sy})` }}>
{/* A luz da cena vem sempre do mesmo lado: espelhado, a sombra do desenho troca de lado. */}
<CharacterFigure look={a.character.look} item={a.item} t={t} state={st} shadeSide={st.flip ? -1 : 1} />
{showLabel && (
<div style={{ position: "absolute", left: zoom > 1 ? "8%" : "50%", top: zoom > 1 ? "22%" : "-15%", transform: `translateX(-50%) scaleX(${st.flip ? -1 : 1})`, textAlign: "center" }}>
<TagLabel text={label} />
{a.character.caption && <div style={{ marginTop: "0.6cqw" }}><TagLabel text={a.character.caption} tone="ok" size={2.4} /></div>}
</div>
@@ -77,9 +130,12 @@ export function Shot(spec: ShotSpec) {
</div>
);
})}
<LightLayer light={spec.light} palette={spec.palette} />
{spec.scene.kind === "place" && <PlaceForeground spec={spec} frame={frame} progress={progress} />}
<WeatherLayer spec={spec} frame={frame} />
<LightLayer light={spec.light} palette={spec.palette} spec={spec} />
{(spec.texts ?? []).map((t, i) => <TextLayer key={i} t={t} frame={frame} fps={fps} />)}
</AbsoluteFill>
{(spec.grain ?? 0.11) > 0 && <Grain opacity={spec.grain ?? 0.11} seed={spec.seed} />}
{spec.hud && <Hud hud={spec.hud} frame={frame} fps={fps} />}
{spec.words?.length ? <Captions words={spec.words} frame={frame} fps={fps} /> : null}
</AbsoluteFill>
+43 -13
View File
@@ -4,6 +4,9 @@ import React from "react";
import { COLORS } from "./colors";
import { rng } from "./random";
import type { Crowd, Person } from "./spec";
import type { CharacterLook } from "./character";
import { CharacterFigure } from "./CharacterFigure";
import { evaluate } from "./motion";
/** Pessoa em pé num viewBox 200×420; (0,0) do grupo = pés no centro. */
export function PersonFigure({ p, frame, fps }: { p: Person; frame: number; fps: number }) {
@@ -44,23 +47,50 @@ export function PersonFigure({ p, frame, fps }: { p: Person; frame: number; fps:
);
}
/** Fila de silhuetas pretas (multidão no portão). */
export function CrowdFigure({ c, frame }: { c: Crowd; frame: number }) {
const SKINS = ["#f1c7a3", "#e0b48f", "#d09a70", "#c08055", "#a8704a", "#8d5a3b", "#6e4630"];
const HAIRS = ["#2a1e16", "#3a2a1e", "#6b4226", "#c9c9cf", "#e8c35a", "#1e1612", "#8a8a92"];
const CLOTHES = ["#3f6b8a", "#c8443a", "#5b6b3a", "#e8b13a", "#7a5ce0", "#2f6db3", "#d98a5c", "#4f7a4a", "#8a6f9e", "#56704a", "#e9ecef"];
const pick = <T,>(r: () => number, list: readonly T[]): T => list[Math.floor(r() * list.length) % list.length];
/** Aparência sorteada de quem está na multidão: cada um diferente (cabeça, altura, cabelo, roupa, acessório). */
export function crowdLook(seed: number): CharacterLook {
const r = rng(seed * 7919 + 17);
const female = r() < 0.45;
const old = r() < 0.25;
const hairStyle = female ? pick(r, ["long", "bun", "curly", "side"] as const) : pick(r, ["short", "side", "bald", "curly", "spiky", "cap"] as const);
const top = pick(r, female ? (["shirt", "dress", "hoodie", "jacket"] as const) : (["shirt", "jacket", "hoodie", "uniform", "shirt"] as const));
const acc: NonNullable<CharacterLook["accessories"]> = [];
const roll = r();
if (!female && roll < 0.14) { acc.push("helmet", "vest"); } else if (roll < 0.22) acc.push("scarf"); else if (roll < 0.3) acc.push("watch");
return {
build: pick(r, ["slim", "average", "average", "heavy"] as const), height: 0.86 + r() * 0.26, skin: pick(r, SKINS),
hair: { style: hairStyle, color: old ? "#c9c9cf" : pick(r, HAIRS) },
beard: { style: female ? "none" : pick(r, ["none", "none", "stubble", "mustache", "full", "goatee"] as const), color: old ? "#b0b0b8" : pick(r, HAIRS) },
glasses: r() < 0.22 ? pick(r, ["round", "square"] as const) : "none", brows: r() < 0.5 ? "thick" : "thin",
top: { style: top, color: pick(r, CLOTHES), accent: pick(r, CLOTHES) }, bottom: { style: female && r() < 0.3 ? "skirt" : "pants", color: pick(r, ["#2c3346", "#3a3f4a", "#5a4a3a", "#2b3a5a"]) },
shoes: pick(r, ["#1d1d24", "#5a3a22", "#f2f2f2"]), head: pick(r, ["round", "oval", "square", "wide"] as const), nose: pick(r, ["curve", "round", "button", "wide", "long"] as const),
lids: 0.1 + r() * 0.35, wrinkles: old ? 0.6 : 0, belly: !female && r() < 0.2, ...(acc.length ? { accessories: acc, accessoryColor: acc[0] === "helmet" ? "#f2a31a" : undefined } : {}),
};
}
/** Multidão: pessoas desenhadas com o mesmo traço dos personagens, cada uma diferente, em duas fileiras. */
export function CrowdFigure({ c, frame, fps = 30 }: { c: Crowd; frame: number; fps?: number }) {
const rand = rng(c.count * 31 + 3);
const people = Array.from({ length: c.count }, (_, i) => ({ x: (i + 0.5) / c.count, h: 0.8 + rand() * 0.35, p: rand() * 6 }));
const people = Array.from({ length: c.count }, (_, i) => ({ i, x: (i + 0.5) / c.count + (rand() - 0.5) * 0.04, back: i % 2 === 1, p: rand() * 6 }))
.sort((a, b) => Number(b.back) - Number(a.back));
const t = frame / fps;
return (
<svg viewBox="0 0 1000 300" width="100%" height="100%" preserveAspectRatio="none" overflow="visible">
{people.map((m, i) => {
const bob = Math.sin(frame / 14 + m.p) * 3;
const x = m.x * 1000;
const h = 260 * m.h;
<div style={{ position: "absolute", inset: 0 }}>
{people.map((m) => {
const h = m.back ? 78 : 92;
const st = evaluate({ x: 0, expression: pick(rng(m.i + 5), ["neutral", "smile", "happy", "neutral", "smirk", "surprised"] as const) }, t, 3600, m.i * 7 + 3);
return (
<g key={i} transform={`translate(${x} ${300 + bob})`} fill="#06070f">
<rect x={-26} y={-h * 0.62} width={52} height={h * 0.62} rx={18} />
<circle cx={0} cy={-h * 0.75} r={h * 0.13} />
</g>
<div key={m.i} style={{ position: "absolute", left: `${m.x * 100 - h * 0.11}%`, bottom: `${(m.back ? 8 : 0) + Math.sin(t * 2 + m.p) * 0.4}%`, height: `${h}%`, aspectRatio: "200 / 440",
filter: m.back ? "brightness(0.82)" : undefined }}>
<CharacterFigure look={crowdLook(m.i + c.count * 13)} t={t} state={st} shadeSide={1} />
</div>
);
})}
</svg>
</div>
);
}
+157
View File
@@ -0,0 +1,157 @@
// Animais do estilo Cartoon: figuras reaproveitáveis em qualquer história (não são cena pronta). Cada espécie
// é desenhada por formas chapadas no mesmo traço dos personagens, olhando para a direita, com as patas em
// (100, 200) num viewBox 200×200. Andar mexe as patas; ave voando bate as asas. Cor e escala vêm do spec.
import React from "react";
export const SPECIES = ["dove", "raven", "elephant", "giraffe", "lion", "sheep", "horse", "camel"] as const;
export type Species = (typeof SPECIES)[number];
/** Altura de referência de cada espécie (fração da altura do quadro, com scale 1). */
export const SPECIES_HEIGHT: Record<Species, number> = {
dove: 0.05, raven: 0.055, elephant: 0.2, giraffe: 0.3, lion: 0.12, sheep: 0.085, horse: 0.17, camel: 0.19,
};
/** Aves podem voar (asas batendo, sem patas no chão). */
export const BIRDS: readonly Species[] = ["dove", "raven"];
const INK = "#15161f";
const DEFAULT_COLOR: Record<Species, string> = {
dove: "#f4f4f8", raven: "#23242e", elephant: "#9aa0ab", giraffe: "#e8b54a", lion: "#d99a3a", sheep: "#f1ece0", horse: "#8a5a3a", camel: "#c9a06a",
};
function shade(hex: string, k: number): string {
const n = parseInt(hex.slice(1), 16);
const c = (v: number) => Math.max(0, Math.min(255, Math.round(v * k))).toString(16).padStart(2, "0");
return `#${c((n >> 16) & 255)}${c((n >> 8) & 255)}${c(n & 255)}`;
}
/** Perna que balança pelo quadril: `phase` vem do passo (0 parado). */
function Leg({ x, y, len, w, fill, swing }: { x: number; y: number; len: number; w: number; fill: string; swing: number }) {
return <rect x={x - w / 2} y={y} width={w} height={len} rx={w / 2.4} fill={fill} transform={`rotate(${swing} ${x} ${y})`} />;
}
function Eye({ x, y, r = 4.5, light }: { x: number; y: number; r?: number; light?: boolean }) {
return <g><circle cx={x} cy={y} r={r} fill={light ? "#ffffff" : INK} />{light ? <circle cx={x + 1} cy={y} r={r * 0.55} fill={INK} /> : <circle cx={x + 1.3} cy={y - 1.3} r={r * 0.3} fill="#ffffff" />}</g>;
}
/** Ramo de oliveira no bico (pomba da história do dilúvio, mas serve para qualquer ave). */
function Branch({ x, y }: { x: number; y: number }) {
return (
<g transform={`translate(${x} ${y})`}>
<path d="M0 0 Q14 6 30 4" stroke="#6b4a2a" strokeWidth={2.4} fill="none" strokeLinecap="round" />
{[[8, 2, -30], [16, 6, 30], [22, 2, -30], [28, 6, 25]].map(([lx, ly, r], i) => <ellipse key={i} cx={lx} cy={ly} rx={6} ry={2.6} fill={i % 2 ? "#7fa24a" : "#5f8a3a"} transform={`rotate(${r} ${lx} ${ly})`} />)}
</g>
);
}
export function AnimalFigure({ species, color, t = 0, walking = false, flying = false, carry, seed = 0 }: {
species: Species; color?: string; t?: number; walking?: boolean; flying?: boolean; carry?: "olive"; seed?: number;
}) {
const c = color ?? DEFAULT_COLOR[species];
const dark = shade(c, 0.78);
// Passo: pernas da frente e de trás em oposição; corpo sobe e desce de leve.
const ph = walking ? Math.sin((t + seed * 0.37) * Math.PI * 2 * 1.6) : 0;
const bob = walking ? Math.abs(ph) * -3 : Math.sin(t * 2 + seed) * 0.8;
const flap = flying ? Math.sin((t + seed * 0.21) * Math.PI * 2 * 3.2) : 0;
const body = (inner: React.ReactNode) => <svg viewBox="0 0 200 200" width="100%" height="100%" overflow="visible"><g transform={`translate(0 ${bob})`}>{inner}</g></svg>;
switch (species) {
case "dove": case "raven": {
const beak = species === "dove" ? "#e8a04a" : "#3a3b46";
if (flying) {
return body(<g>
<path d={`M78 112 Q60 ${100 - flap * 50} 30 ${96 - flap * 70} Q66 ${112 - flap * 20} 84 124 Z`} fill={dark} />
<ellipse cx={100} cy={122} rx={36} ry={18} fill={c} />
<path d="M66 120 L40 112 L44 132 Z" fill={dark} />
<circle cx={134} cy={112} r={15} fill={c} />
<path d="M147 110 L162 114 L147 118 Z" fill={beak} />
<Eye x={138} y={109} r={3.2} />
<path d={`M104 116 Q118 ${100 - flap * 48} 150 ${92 - flap * 64} Q124 ${114 - flap * 18} 112 126 Z`} fill={c} stroke={dark} strokeWidth={2} />
{carry === "olive" && <Branch x={156} y={116} />}
</g>);
}
return body(<g>
<path d="M86 186 L84 200 M106 186 L108 200" stroke="#e07a4a" strokeWidth={4} strokeLinecap="round" />
<ellipse cx={96} cy={164} rx={36} ry={26} fill={c} />
<path d="M64 160 L36 150 L42 176 Z" fill={dark} />
<path d="M80 158 Q100 146 118 166 Q100 178 80 158 Z" fill={dark} />
<circle cx={128} cy={134} r={17} fill={c} />
<path d="M143 132 L160 137 L143 142 Z" fill={beak} />
<Eye x={132} y={130} r={3.4} />
{carry === "olive" && <Branch x={154} y={138} />}
</g>);
}
case "elephant": return body(<g>
<Leg x={52} y={128} len={70} w={26} fill={dark} swing={-ph * 10} />
<Leg x={128} y={128} len={70} w={26} fill={dark} swing={ph * 10} />
<ellipse cx={92} cy={112} rx={66} ry={50} fill={c} />
<Leg x={72} y={130} len={68} w={26} fill={c} swing={ph * 10} />
<Leg x={148} y={128} len={70} w={26} fill={c} swing={-ph * 10} />
<path d="M28 104 Q16 116 22 134" stroke={dark} strokeWidth={5} fill="none" strokeLinecap="round" />
<circle cx={154} cy={90} r={34} fill={c} />
<path d={`M176 98 Q192 128 182 158 Q178 ${170 + ph * 4} 190 ${172 + ph * 4}`} stroke={c} strokeWidth={16} fill="none" strokeLinecap="round" />
<path d="M130 70 Q100 74 104 108 Q116 132 140 116 Z" fill={dark} />
<path d="M172 112 L184 124" stroke="#f4f0e4" strokeWidth={6} strokeLinecap="round" />
<Eye x={166} y={84} r={4} />
</g>);
case "giraffe": return body(<g>
<Leg x={58} y={118} len={80} w={11} fill={dark} swing={-ph * 12} />
<Leg x={118} y={118} len={80} w={11} fill={dark} swing={ph * 12} />
<ellipse cx={90} cy={112} rx={44} ry={24} fill={c} />
<Leg x={70} y={120} len={78} w={11} fill={c} swing={ph * 12} />
<Leg x={128} y={118} len={80} w={11} fill={c} swing={-ph * 12} />
<path d="M116 100 L150 10 L166 16 L134 108 Z" fill={c} />
{[[80, 104], [100, 116], [66, 116], [104, 98], [138, 60], [148, 34], [130, 84]].map(([x, y], i) => <circle key={i} cx={x} cy={y} r={6} fill={shade(c, 0.62)} />)}
<ellipse cx={168} cy={14} rx={22} ry={12} fill={c} />
<path d="M156 0 L154 -14 M164 0 L164 -14" stroke={dark} strokeWidth={4} strokeLinecap="round" />
<Eye x={170} y={9} r={3.4} />
<path d="M46 104 Q36 120 40 136" stroke={dark} strokeWidth={3} fill="none" />
</g>);
case "lion": {
const mane = shade(c, 0.62);
return body(<g>
<Leg x={58} y={138} len={60} w={15} fill={dark} swing={-ph * 12} />
<Leg x={124} y={138} len={60} w={15} fill={dark} swing={ph * 12} />
<ellipse cx={92} cy={138} rx={52} ry={26} fill={c} />
<Leg x={72} y={140} len={58} w={15} fill={c} swing={ph * 12} />
<Leg x={136} y={138} len={60} w={15} fill={c} swing={-ph * 12} />
<path d={`M42 132 Q20 ${120 + ph * 6} 22 102`} stroke={c} strokeWidth={6} fill="none" strokeLinecap="round" />
<circle cx={22} cy={100} r={7} fill={mane} />
<circle cx={146} cy={112} r={34} fill={mane} />
<circle cx={150} cy={116} r={22} fill={c} />
<ellipse cx={164} cy={124} rx={9} ry={7} fill={shade(c, 1.15)} />
<circle cx={168} cy={121} r={3.4} fill={INK} />
<Eye x={156} y={108} r={3.4} />
</g>);
}
case "sheep": return body(<g>
<Leg x={70} y={150} len={50} w={9} fill="#3a3540" swing={-ph * 12} />
<Leg x={118} y={150} len={50} w={9} fill="#3a3540" swing={ph * 12} />
{[[66, 140], [86, 128], [108, 128], [126, 140], [96, 152], [76, 156], [116, 156]].map(([x, y], i) => <circle key={i} cx={x} cy={y} r={22} fill={c} />)}
<Leg x={82} y={160} len={40} w={9} fill="#2e2a33" swing={ph * 12} />
<Leg x={128} y={156} len={44} w={9} fill="#2e2a33" swing={-ph * 12} />
<ellipse cx={152} cy={128} rx={16} ry={20} fill="#3a3540" />
<ellipse cx={140} cy={116} rx={10} ry={5} fill="#3a3540" transform="rotate(-20 140 116)" />
<circle cx={146} cy={110} r={12} fill={c} />
<Eye x={158} y={124} r={3.2} light />
</g>);
case "horse": case "camel": {
const camel = species === "camel";
return body(<g>
<Leg x={60} y={116} len={84} w={13} fill={dark} swing={-ph * 14} />
<Leg x={124} y={116} len={84} w={13} fill={dark} swing={ph * 14} />
<ellipse cx={92} cy={110} rx={52} ry={28} fill={c} />
{camel && <path d="M62 92 Q76 50 96 88 Q110 54 126 92 Z" fill={c} />}
<Leg x={74} y={118} len={82} w={13} fill={c} swing={ph * 14} />
<Leg x={134} y={116} len={84} w={13} fill={c} swing={-ph * 14} />
<path d={camel ? "M132 100 Q160 96 158 60 L174 56 Q178 104 142 116 Z" : "M128 96 L152 50 L170 58 L146 112 Z"} fill={c} />
<ellipse cx={camel ? 178 : 168} cy={camel ? 56 : 56} rx={camel ? 17 : 22} ry={camel ? 11 : 13} fill={c} transform={`rotate(${camel ? 10 : 30} ${camel ? 178 : 168} 56)`} />
{!camel && <path d="M150 48 Q132 70 128 98" stroke={shade(c, 0.5)} strokeWidth={9} fill="none" strokeLinecap="round" />}
{!camel && <path d={`M42 104 Q24 ${120 + ph * 4} 30 146`} stroke={shade(c, 0.5)} strokeWidth={9} fill="none" strokeLinecap="round" />}
{camel && <path d="M42 106 Q34 120 38 134" stroke={dark} strokeWidth={4} fill="none" />}
<path d="M158 42 L156 30 L166 40 Z" fill={dark} />
<Eye x={camel ? 182 : 170} y={camel ? 52 : 50} r={3.4} />
</g>);
}
default: return null;
}
}
+39 -8
View File
@@ -4,16 +4,26 @@
export const BUILDS = ["slim", "average", "heavy"] as const;
export const HAIR_STYLES = ["short", "side", "bun", "long", "curly", "spiky", "bald", "cap"] as const;
export const BEARD_STYLES = ["none", "stubble", "mustache", "full", "goatee"] as const;
export const BEARD_STYLES = ["none", "stubble", "mustache", "full", "goatee", "long"] as const;
export const GLASSES = ["none", "round", "square", "sun"] as const;
export const BROWS = ["thin", "thick"] as const;
export const TOP_STYLES = ["shirt", "jacket", "hoodie", "dress", "uniform"] as const;
/** "robe" = túnica longa até a canela (com faixa na cintura), de roupa antiga. */
export const TOP_STYLES = ["shirt", "jacket", "hoodie", "dress", "uniform", "robe"] as const;
export const BOTTOM_STYLES = ["pants", "shorts", "skirt"] as const;
export const EXPRESSIONS = ["neutral", "happy", "sad", "worried", "angry", "surprised", "scared"] as const;
export const POSES = ["stand", "point", "wave", "hold", "arms_up", "shrug", "think"] as const;
export const HEAD_SHAPES = ["round", "oval", "square", "wide"] as const;
export const NOSES = ["button", "curve", "round", "long", "wide"] as const;
/** Calçado: sapato fechado (cor em `shoes`), sandália de tiras ou pé descalço. */
export const FOOTWEAR = ["shoes", "sandals", "bare"] as const;
/** Acessórios desenhados por cima da roupa (combináveis). */
export const ACCESSORIES = ["towel", "whistle", "tie", "vest", "helmet", "watch", "badge", "apron", "scarf", "headset", "chain"] as const;
export type Accessory = (typeof ACCESSORIES)[number];
// Expressões e poses são ATALHOS do rig (rig.ts): parâmetros contínuos que dá para ajustar e misturar.
import { EXPRESSION_NAMES, POSE_NAMES, type ExpressionName, type PoseName } from "./rig";
export type Expression = (typeof EXPRESSIONS)[number];
export type Pose = (typeof POSES)[number];
export const EXPRESSIONS = EXPRESSION_NAMES;
export const POSES = POSE_NAMES;
export type Expression = ExpressionName;
export type Pose = PoseName;
export type CharacterLook = {
build: (typeof BUILDS)[number];
@@ -27,6 +37,20 @@ export type CharacterLook = {
top: { style: (typeof TOP_STYLES)[number]; color: string; accent?: string };
bottom: { style: (typeof BOTTOM_STYLES)[number]; color: string };
shoes: string;
/** Tipo de calçado (padrão "shoes"); a cor continua em `shoes`. */
footwear?: (typeof FOOTWEAR)[number];
/** Detalhe de ilustração (opcionais; sem eles o personagem sai no traço simples). */
head?: (typeof HEAD_SHAPES)[number];
nose?: (typeof NOSES)[number];
/** Pálpebra de cima de base (0 olho aberto … 0,6 meio caído, olhar cansado/esperto). */
lids?: number;
/** Rugas (0 nenhuma … 1 muitas: testa e canto dos olhos). */
wrinkles?: number;
/** Barriga saliente (o "forte" de barriga). */
belly?: boolean;
accessories?: Accessory[];
/** Cor dos acessórios principais (toalha, gravata, colete, capacete…). */
accessoryColor?: string;
};
/** Ficha do personagem na biblioteca. `kind: "3d"` aponta para a pessoa articulada da Godot (godot/kits). */
@@ -73,8 +97,15 @@ export function validateLook(look: unknown): string[] {
if (!one(BROWS, l.brows)) errors.push(`brows: ${BROWS.join("|")}`);
if (!one(TOP_STYLES, l.top?.style)) errors.push(`top.style: ${TOP_STYLES.join("|")}`);
if (!one(BOTTOM_STYLES, l.bottom?.style)) errors.push(`bottom.style: ${BOTTOM_STYLES.join("|")}`);
if (l.head !== undefined && !one(HEAD_SHAPES, l.head)) errors.push(`head: ${HEAD_SHAPES.join("|")}`);
if (l.nose !== undefined && !one(NOSES, l.nose)) errors.push(`nose: ${NOSES.join("|")}`);
if (l.lids !== undefined && !(typeof l.lids === "number" && l.lids >= 0 && l.lids <= 0.8)) errors.push("lids entre 0 e 0,8");
if (l.wrinkles !== undefined && !(typeof l.wrinkles === "number" && l.wrinkles >= 0 && l.wrinkles <= 1)) errors.push("wrinkles entre 0 e 1");
if (l.accessories !== undefined && (!Array.isArray(l.accessories) || l.accessories.some((a) => !one(ACCESSORIES, a)))) errors.push(`accessories: ${ACCESSORIES.join("|")}`);
if (l.footwear !== undefined && !one(FOOTWEAR, l.footwear)) errors.push(`footwear: ${FOOTWEAR.join("|")}`);
if (l.accessoryColor !== undefined && !HEX.test(l.accessoryColor)) errors.push("accessoryColor: cor #rrggbb");
return errors;
}
export const isExpression = (v: unknown): v is Expression => one(EXPRESSIONS, v);
export const isPose = (v: unknown): v is Pose => one(POSES, v);
export const isExpression = (v: unknown): v is Expression => typeof v === "string" && (EXPRESSIONS as string[]).includes(v);
export const isPose = (v: unknown): v is Pose => typeof v === "string" && (POSES as string[]).includes(v);
+379
View File
@@ -0,0 +1,379 @@
// Construções e objetos de exterior: casa, prédio, muro, fachada com colunas, loja com toldo, cerca, poste…
// Base em (0,0); luz da esquerda (a face da direita fica na sombra). Medidas pensadas para uma pessoa de ~600.
import React from "react";
import { mix, type Paint } from "./paint";
import type { Draw } from "./nature";
/** Caixa em 2 tons: frente na cor base, faixa da direita na sombra e (opcional) topo iluminado. */
export function Box({ x, y, w, h, fill, p, side = 0.14, top = 0, rx = 0, k = 0.32 }: {
x: number; y: number; w: number; h: number; fill: string; p: Paint; side?: number; top?: number; rx?: number; k?: number;
}) {
return <g>
<rect x={x} y={y} width={w} height={h} rx={rx} fill={p.c(fill)} />
{side > 0 && <rect x={x + w * (1 - side)} y={y} width={w * side} height={h} rx={Math.min(rx, (w * side) / 2)} fill={p.lo(fill, k)} />}
{top > 0 && <rect x={x} y={y} width={w} height={top} rx={Math.min(rx, top / 2)} fill={p.hi(fill, 0.28)} />}
</g>;
}
/** Janela de fachada: moldura, vidro (aceso à noite, céu refletido de dia), cruz e peitoril. */
export function FacadeWindow({ x, y, w, h, p, lit, frame = "#efe6d6", arch = false }: { x: number; y: number; w: number; h: number; p: Paint; lit: boolean; frame?: string; arch?: boolean }) {
const glass = lit ? mix(p.pal.light, "#ffb050", 0.15) : mix(p.pal.sky[1], p.pal.ink, p.night ? 0.55 : 0.18);
const top = arch ? `M${x} ${y + w / 2} A${w / 2} ${w / 2} 0 0 1 ${x + w} ${y + w / 2} L${x + w} ${y + h} L${x} ${y + h} Z` : "";
const inset = 10;
return <g>
{arch ? <path d={top} fill={p.c(frame)} /> : <rect x={x} y={y} width={w} height={h} rx={4} fill={p.c(frame)} />}
{arch
? <path d={`M${x + inset} ${y + w / 2} A${w / 2 - inset} ${w / 2 - inset} 0 0 1 ${x + w - inset} ${y + w / 2} L${x + w - inset} ${y + h - inset} L${x + inset} ${y + h - inset} Z`} fill={p.c(glass)} />
: <rect x={x + inset} y={y + inset} width={w - inset * 2} height={h - inset * 2} fill={p.c(glass)} />}
<path d={`M${x + inset} ${y + h - inset} L${x + w - inset} ${y + h - inset} L${x + w - inset} ${y + h * 0.45} Z`} fill={lit ? p.hi(glass, 0.3) : p.lo(glass, 0.25)} opacity={0.6} />
{!lit && <path d={`M${x + w * 0.25} ${y + h * 0.75} L${x + w * 0.55} ${y + h * 0.2} L${x + w * 0.68} ${y + h * 0.2} L${x + w * 0.38} ${y + h * 0.75} Z`} fill="#ffffff" opacity={0.18} />}
<rect x={x + w / 2 - 4} y={y + inset} width={8} height={h - inset * 2} fill={p.c(frame)} />
<rect x={x + inset} y={y + h * 0.48} width={w - inset * 2} height={8} fill={p.c(frame)} />
<rect x={x - 8} y={y + h - 4} width={w + 16} height={14} rx={3} fill={p.hi(frame, 0.2)} />
<rect x={x - 8} y={y + h + 10} width={w + 16} height={8} fill={p.lo(frame, 0.5)} opacity={0.6} />
</g>;
}
/** Linhas de telha num trapézio (um path só: fileiras + juntas desencontradas). */
function tiles(x0: number, x1: number, y0: number, y1: number, rows: number, inset: number): string {
let d = "";
for (let k = 1; k <= rows; k++) {
const t = k / rows;
const y = y0 + (y1 - y0) * t;
const l = x0 + inset * (1 - t);
const r = x1 - inset * (1 - t);
d += `M${l} ${y} L${r} ${y} `;
const yPrev = y0 + (y1 - y0) * ((k - 1) / rows);
for (let x = l + (k % 2 ? 22 : 0); x < r; x += 44) d += `M${x} ${y} L${x} ${yPrev + 6} `;
}
return d;
}
export const BUILT: Record<string, Draw> = {
house: (p, color) => {
const wall = color ?? mix(p.pal.near, "#f2e2c6", 0.45);
const roof = mix("#c4613a", p.pal.near, 0.15);
const lit = () => p.night && p.r() > 0.35;
const doorX = p.r() > 0.5 ? 60 : -170;
return <g>
{/* lado da casa (fundo, na sombra) */}
<polygon points="300,0 300,-460 392,-430 392,-14" fill={p.lo(wall, 0.42)} />
<polygon points="300,-460 392,-430 392,-400 300,-424" fill={p.lo(wall, 0.6)} />
<rect x={-300} y={-460} width={600} height={460} fill={p.c(wall)} />
<rect x={-300} y={-460} width={26} height={460} fill={p.hi(wall, 0.14)} />
{[[-240, -120, 70, 26], [140, -320, 90, 22], [-80, -380, 60, 18]].map(([x, y, w, h], i) => <rect key={i} x={x} y={y} width={w} height={h} rx={h / 2} fill={p.lo(wall, 0.14)} />)}
<rect x={-300} y={-36} width={600} height={36} fill={p.lo(wall, 0.38)} />
{/* telhado de telha: frente, quina iluminada à esquerda e água da direita na sombra */}
<polygon points="-350,-452 -235,-660 235,-660 350,-452" fill={p.c(roof)} />
<path d={tiles(-350, 350, -660, -452, 5, 115)} stroke={p.lo(roof, 0.4)} strokeWidth={5} fill="none" />
<polygon points="-350,-452 -235,-660 -205,-660 -300,-452" fill={p.hi(roof, 0.22)} />
<polygon points="235,-660 350,-452 430,-430 300,-640" fill={p.lo(roof, 0.4)} />
<rect x={-356} y={-458} width={712} height={16} rx={4} fill={p.lo(roof, 0.2)} />
<rect x={-300} y={-442} width={600} height={30} fill={p.lo(wall, 0.5)} opacity={0.8} />
<rect x={150} y={-720} width={54} height={90} fill={p.c(mix(roof, "#8a5a4a", 0.4))} /><rect x={184} y={-720} width={20} height={90} fill={p.lo(roof, 0.5)} />
{/* janelas e porta */}
{(doorX > 0 ? [-230, -60] : [-20, 160]).map((x) => <FacadeWindow key={x} x={x} y={-330} w={110} h={130} p={p} lit={lit()} />)}
<rect x={doorX - 12} y={-282} width={124} height={282} rx={4} fill={p.c("#efe6d6")} />
<rect x={doorX} y={-270} width={100} height={270} fill={p.c(mix("#7a4a2c", wall, 0.1))} />
<rect x={doorX + 74} y={-270} width={26} height={270} fill={p.lo("#7a4a2c", 0.4)} />
<rect x={doorX + 14} y={-250} width={60} height={90} rx={3} fill={p.lo("#7a4a2c", 0.25)} />
<circle cx={doorX + 80} cy={-130} r={7} fill={p.c("#e6c27a")} />
<rect x={doorX - 24} y={-12} width={148} height={12} fill={p.hi("#b0a898", 0.1)} />
</g>;
},
building: (p, color) => {
const floors = 4 + Math.floor(p.r() * 4);
const fh = 150;
const H = floors * fh;
const body = color ?? p.pal.far;
const rows = Array.from({ length: floors - 1 }, (_, f) => f);
return <g>
<polygon points={`210,0 210,${-H} 276,${-H + 26} 276,0`} fill={p.lo(body, 0.42)} />
<rect x={-210} y={-H} width={420} height={H} fill={p.c(body)} />
<rect x={-210} y={-H} width={22} height={H} fill={p.hi(body, 0.14)} />
<rect x={-224} y={-H - 26} width={448} height={30} fill={p.hi(body, 0.2)} />
<polygon points={`224,${-H - 26} 290,${-H} 290,${-H + 4} 224,${-H + 4}`} fill={p.lo(body, 0.5)} />
{rows.map((f) => <rect key={f} x={-210} y={-(f + 1) * fh - 6} width={420} height={8} fill={p.lo(body, 0.2)} />)}
{rows.flatMap((f) => [-160, -40, 80].map((x) => (
<FacadeWindow key={`${f}${x}`} x={x} y={-(f + 2) * fh + 28} w={80} h={90} p={p} lit={p.night ? p.r() > 0.55 : false} frame={mix(body, "#ffffff", 0.45)} />
)))}
<rect x={-70} y={-130} width={140} height={130} fill={p.c(mix(body, p.pal.ink, 0.6))} />
<rect x={-60} y={-120} width={120} height={120} fill={p.c(p.night ? mix(p.pal.light, "#ffb050", 0.3) : mix(p.pal.sky[1], p.pal.ink, 0.4))} opacity={0.85} />
<rect x={-96} y={-150} width={192} height={22} fill={p.c(mix(body, p.pal.ink, 0.35))} />
<rect x={-210} y={-20} width={420} height={20} fill={p.lo(body, 0.45)} />
</g>;
},
wall: (p, color) => {
// Muro comprido de reboco com capa por cima e pilares (passa da borda do quadro).
const w = color ?? mix(p.pal.near, "#c8885e", 0.5);
const patches = Array.from({ length: 7 }, () => [-660 + p.r() * 1260, -250 + p.r() * 190, 40 + p.r() * 90]);
return <g>
<rect x={-720} y={-300} width={1440} height={300} fill={p.c(w)} />
{patches.map(([x, y, s], i) => <rect key={i} x={x} y={y} width={s} height={s * 0.36} rx={s * 0.18} fill={i % 2 ? p.lo(w, 0.14) : p.hi(w, 0.14)} />)}
{[-540, -180, 180, 540].map((x) => <g key={x}><rect x={x - 26} y={-312} width={52} height={312} fill={p.c(w)} /><rect x={x + 8} y={-312} width={18} height={312} fill={p.lo(w, 0.3)} /></g>)}
<rect x={-730} y={-324} width={1460} height={28} rx={4} fill={p.hi(w, 0.22)} />
<rect x={-730} y={-300} width={1460} height={22} fill={p.lo(w, 0.5)} opacity={0.75} />
<rect x={-720} y={-34} width={1440} height={34} fill={p.lo(w, 0.4)} />
</g>;
},
facade: (p, color) => {
// Prédio público visto de frente: escadaria, colunas, frontão triangular.
const stone = color ?? "#e6dac2";
const back = p.lo(stone, 0.42);
const cols = [-400, -240, -80, 80, 240, 400];
return <g>
<rect x={-470} y={-690} width={940} height={600} fill={back} />
{[-320, -160, 0, 160, 320].map((x) => <path key={x} d={`M${x - 42} -180 L${x - 42} -470 A42 42 0 0 1 ${x + 42} -470 L${x + 42} -180 Z`} fill={p.c(mix(p.pal.sky[1], p.pal.ink, p.night ? 0.7 : 0.45))} />)}
{[-320, -160, 0, 160, 320].map((x) => <rect key={x} x={x - 42} y={-200} width={84} height={20} fill={p.lo(stone, 0.45)} />)}
{cols.map((x) => <g key={x}>
<rect x={x - 32} y={-660} width={64} height={560} fill={p.c(stone)} />
<rect x={x - 32} y={-660} width={14} height={560} fill={p.hi(stone, 0.3)} />
<rect x={x + 8} y={-660} width={24} height={560} fill={p.lo(stone, 0.42)} />
<rect x={x - 46} y={-686} width={92} height={28} rx={4} fill={p.hi(stone, 0.12)} />
<rect x={x + 18} y={-686} width={28} height={28} fill={p.lo(stone, 0.3)} />
<rect x={x - 44} y={-120} width={88} height={24} fill={p.c(stone)} /><rect x={x + 16} y={-120} width={28} height={24} fill={p.lo(stone, 0.3)} />
</g>)}
<rect x={-500} y={-770} width={1000} height={86} fill={p.c(stone)} />
<rect x={-500} y={-704} width={1000} height={20} fill={p.lo(stone, 0.35)} />
<rect x={-500} y={-770} width={1000} height={14} fill={p.hi(stone, 0.3)} />
<polygon points="-530,-770 0,-930 530,-770" fill={p.c(stone)} />
<polygon points="-440,-786 0,-904 440,-786" fill={p.lo(stone, 0.22)} />
<polygon points="0,-930 530,-770 500,-770 0,-916" fill={p.lo(stone, 0.4)} />
<polygon points="-530,-770 0,-930 0,-916 -500,-770" fill={p.hi(stone, 0.3)} />
{/* base e degraus */}
<rect x={-490} y={-100} width={980} height={30} fill={p.c(stone)} />
{[0, 1, 2].map((i) => <g key={i}>
<rect x={-520 - i * 30} y={-70 + i * 24} width={1040 + i * 60} height={24} fill={p.c(mix(stone, "#a8a090", 0.2))} />
<rect x={-520 - i * 30} y={-70 + i * 24} width={1040 + i * 60} height={6} fill={p.hi(stone, 0.35)} />
</g>)}
</g>;
},
shopfront: (p, color) => {
// Loja/oficina de rua: toldo listrado, letreiro em branco, porta de enrolar meio aberta e o interior escuro.
const wall = mix(p.pal.near, "#eeb04a", 0.75);
const awn = color ?? "#d65a3a";
const inside = mix(wall, p.pal.ink, 0.62);
const n = 9;
const stripe = 800 / n;
return <g>
<polygon points="400,0 400,-700 470,-670 470,-10" fill={p.lo(wall, 0.42)} />
<rect x={-400} y={-700} width={800} height={700} fill={p.c(wall)} />
<rect x={-400} y={-700} width={24} height={700} fill={p.hi(wall, 0.16)} />
{/* vão da garagem com ferramentas na parede do fundo */}
<rect x={-300} y={-420} width={600} height={420} fill={p.c(inside)} />
<rect x={-300} y={-420} width={600} height={60} fill={p.lo(inside, 0.4)} />
<rect x={40} y={-330} width={220} height={150} rx={6} fill={p.c(mix(inside, "#8a6a4a", 0.35))} />
{[70, 110, 150, 190, 230].map((x, i) => <rect key={x} x={x - 6} y={-310} width={12} height={i % 2 ? 90 : 70} rx={5} fill={p.c(i % 3 ? "#b8bcc4" : "#e8b030")} />)}
<rect x={-270} y={-200} width={200} height={14} fill={p.c(mix(inside, "#8a6a4a", 0.4))} />
{[0, 1].map((i) => <ellipse key={i} cx={-200 + i * 50} cy={-60 - i * 10} rx={60} ry={60} fill={p.c("#2a2a32")} />)}
{[0, 1].map((i) => <ellipse key={i} cx={-200 + i * 50} cy={-60 - i * 10} rx={26} ry={26} fill={p.c("#4a4a56")} />)}
<rect x={-300} y={-440} width={600} height={70} fill={p.c(mix(wall, "#c8c8cc", 0.6))} />
{[0, 1, 2, 3].map((i) => <rect key={i} x={-300} y={-432 + i * 16} width={600} height={4} fill={p.lo("#c8c8cc", 0.35)} />)}
<rect x={-312} y={-452} width={24} height={452} fill={p.hi(wall, 0.1)} /><rect x={288} y={-452} width={24} height={452} fill={p.lo(wall, 0.25)} />
{/* letreiro */}
<rect x={-340} y={-580} width={680} height={110} rx={10} fill={p.c("#f4ecdc")} />
<rect x={-340} y={-490} width={680} height={20} rx={6} fill={p.lo("#f4ecdc", 0.28)} />
{/* toldo listrado com a borda em ondas */}
<polygon points="-380,-700 380,-700 450,-610 -450,-610" fill={p.c(awn)} />
{Array.from({ length: n }, (_, i) => i % 2 === 1 && (
<polygon key={i} points={`${-380 + i * (760 / n)},-700 ${-380 + (i + 1) * (760 / n)},-700 ${-450 + (i + 1) * stripe * 1.125},-610 ${-450 + i * stripe * 1.125},-610`} fill={p.lo(awn, 0.2)} />
))}
{Array.from({ length: n }, (_, i) => <path key={i} d={`M${-450 + i * 100} -610 a50 26 0 0 0 100 0 Z`} fill={i % 2 ? p.lo(awn, 0.2) : p.c(awn)} />)}
<rect x={-450} y={-614} width={900} height={10} fill={p.lo(awn, 0.25)} />
<rect x={-400} y={-584} width={800} height={16} fill={p.lo(wall, 0.45)} opacity={0.7} />
<rect x={-400} y={-28} width={800} height={28} fill={p.lo(wall, 0.4)} />
</g>;
},
fence: (p, color) => {
const wood = color ?? mix(p.pal.trunk, "#d8c0a0", 0.35);
const xs = Array.from({ length: 13 }, (_, i) => -450 + i * 75);
const body = xs.map((x) => `M${x - 18} 0 L${x - 18} -200 L${x} -230 L${x + 18} -200 L${x + 18} 0 Z`).join(" ");
const side = xs.map((x) => `M${x + 6} 0 L${x + 6} -212 L${x} -230 L${x + 18} -200 L${x + 18} 0 Z`).join(" ");
return <g>
<rect x={-470} y={-170} width={940} height={26} fill={p.lo(wood, 0.35)} />
<rect x={-470} y={-70} width={940} height={26} fill={p.lo(wood, 0.35)} />
<path d={body} fill={p.c(wood)} />
<path d={side} fill={p.lo(wood, 0.36)} />
</g>;
},
bench: (p, color) => {
const wood = color ?? "#a0663e";
const iron = p.pal.ink;
return <g>
{[-200, 200].map((x) => <g key={x}>
<path d={`M${x - 16} 0 L${x - 10} -150 L${x + 10} -150 L${x + 16} 0 Z`} fill={p.c(mix(iron, "#555a66", 0.4))} />
<path d={`M${x - 6} -150 L${x - 2} -300 L${x + 14} -300 L${x + 10} -150 Z`} fill={p.c(mix(iron, "#555a66", 0.4))} />
</g>)}
<Box x={-260} y={-168} w={520} h={22} fill={wood} p={p} side={0.08} top={6} rx={5} />
<Box x={-260} y={-140} w={520} h={18} fill={mix(wood, "#000000", 0.1)} p={p} side={0.08} rx={5} />
{[-300, -250].map((y) => <Box key={y} x={-260} y={y} w={520} h={36} fill={wood} p={p} side={0.08} top={8} rx={6} />)}
<rect x={-260} y={-146} width={520} height={10} fill={p.lo(wood, 0.55)} opacity={0.7} />
</g>;
},
lamp: (p) => {
const pole = mix(p.pal.ink, "#4a5060", 0.35);
return <g>
{p.night && <path d="M-40 -780 L-260 0 L260 0 L40 -780 Z" fill={p.pal.light} opacity={0.07} />}
<rect x={-34} y={-60} width={68} height={60} rx={8} fill={p.c(pole)} />
<rect x={-12} y={-820} width={24} height={780} fill={p.c(pole)} /><rect x={2} y={-820} width={10} height={780} fill={p.lo(pole, 0.4)} />
<path d="M-56 -800 L56 -800 L40 -870 L-40 -870 Z" fill={p.c(p.night ? p.pal.light : mix(p.pal.sky[2], "#ffffff", 0.4))} />
<rect x={-64} y={-806} width={128} height={14} rx={5} fill={p.c(pole)} />
<path d="M-50 -870 L50 -870 L0 -904 Z" fill={p.c(pole)} /><path d="M0 -904 L50 -870 L20 -870 Z" fill={p.lo(pole, 0.4)} />
{p.night && <circle cx={0} cy={-836} r={90} fill={p.pal.light} opacity={0.12} />}
</g>;
},
gravestone: (p, color) => {
const s = color ?? p.pal.stone;
return <g>
<path d="M-110 0 L-110 -240 Q-110 -340 0 -340 Q110 -340 110 -240 L110 0 Z" fill={p.c(s)} />
<path d="M60 -330 Q110 -310 110 -240 L110 0 L68 0 L68 -240 Q68 -300 60 -330 Z" fill={p.lo(s, 0.38)} />
<path d="M-110 -240 Q-110 -330 -20 -340 Q-80 -320 -88 -240 Z" fill={p.hi(s, 0.2)} />
{[-230, -192, -156].map((y, i) => <rect key={y} x={-56 + i * 6} y={y} width={112 - i * 12} height={10} rx={5} fill={p.lo(s, 0.5)} />)}
<path d="M-130 0 Q-100 -30 -80 0 M90 0 Q110 -26 130 0" stroke={p.c(p.pal.leaf)} strokeWidth={10} fill="none" />
</g>;
},
cross: (p, color) => {
const s = color ?? p.pal.stone;
return <g>
<rect x={-24} y={-400} width={48} height={400} fill={p.c(s)} /><rect x={6} y={-400} width={18} height={400} fill={p.lo(s, 0.38)} />
<rect x={-120} y={-320} width={240} height={44} fill={p.c(s)} /><rect x={-120} y={-288} width={240} height={12} fill={p.lo(s, 0.45)} />
<rect x={-120} y={-320} width={240} height={8} fill={p.hi(s, 0.25)} />
</g>;
},
car: (p, color) => {
const c = color ?? "#c8443a";
const glass = mix(p.pal.sky[1], "#ffffff", 0.25);
return <g transform="scale(2.5)">
<path d="M-150 -40 L-150 -90 Q-140 -110 -100 -112 L-60 -160 L70 -160 L110 -112 L150 -100 L150 -40 Z" fill={p.c(c)} />
<path d="M-150 -74 L150 -74 L150 -40 L-150 -40 Z" fill={p.lo(c, 0.3)} />
<path d="M-100 -112 L-60 -160 L-40 -160 L-80 -112 Z" fill={p.hi(c, 0.25)} />
<path d="M-50 -150 L-4 -150 L-4 -114 L-78 -114 Z" fill={p.c(glass)} /><path d="M8 -150 L64 -150 L96 -114 L8 -114 Z" fill={p.lo(glass, 0.25)} />
<path d="M-30 -146 L-16 -146 L-34 -118 L-48 -118 Z" fill="#ffffff" opacity={0.5} />
<rect x={140} y={-96} width={12} height={14} rx={3} fill={p.c("#ffe6a0")} /><rect x={-152} y={-92} width={10} height={12} rx={3} fill={p.c("#e84a3a")} />
<rect x={-156} y={-48} width={312} height={10} rx={4} fill={p.lo(c, 0.5)} />
{[-90, 95].map((x) => <g key={x}><circle cx={x} cy={-35} r={32} fill={p.c("#1e1f26")} /><circle cx={x} cy={-35} r={15} fill={p.c("#9ea2ac")} /><circle cx={x + 4} cy={-33} r={8} fill={p.lo("#9ea2ac", 0.4)} /></g>)}
</g>;
},
sign: (p, color) => {
const c = color ?? "#2f6d3a";
return <g>
<rect x={-12} y={-440} width={24} height={440} fill={p.c(p.pal.ink)} /><rect x={2} y={-440} width={10} height={440} fill={p.lo(p.pal.ink, 0.3)} />
<rect x={-180} y={-540} width={360} height={150} rx={14} fill={p.c("#ffffff")} />
<rect x={-170} y={-530} width={340} height={130} rx={10} fill={p.c(c)} />
<rect x={-170} y={-430} width={340} height={30} rx={10} fill={p.lo(c, 0.3)} />
<rect x={-130} y={-500} width={200} height={14} rx={7} fill="#ffffff" opacity={0.55} /><rect x={-130} y={-472} width={140} height={14} rx={7} fill="#ffffff" opacity={0.4} />
</g>;
},
crate: (p, color) => {
const w = color ?? "#b0804a";
const dark = p.lo(w, 0.45);
return <g>
<polygon points="-130,-260 -92,-300 168,-300 130,-260" fill={p.hi(w, 0.25)} />
<polygon points="130,-260 168,-300 168,-38 130,0" fill={p.lo(w, 0.4)} />
<rect x={-130} y={-260} width={260} height={260} fill={p.c(w)} />
{[-195, -130, -65].map((y) => <rect key={y} x={-130} y={y} width={260} height={5} fill={dark} opacity={0.6} />)}
<path d="M-112 -242 L112 -18" stroke={p.c(mix(w, "#5a3a1a", 0.35))} strokeWidth={26} />
<path d="M-104 -250 L120 -26" stroke={dark} strokeWidth={6} />
<rect x={-130} y={-260} width={260} height={260} fill="none" stroke={p.c(mix(w, "#5a3a1a", 0.35))} strokeWidth={22} />
<rect x={108} y={-260} width={22} height={260} fill={dark} opacity={0.6} />
</g>;
},
tent: (p, color) => {
const c = color ?? "#d9773a";
return <g>
<path d="M-340 0 L0 -440 L340 0 Z" fill={p.c(c)} />
<path d="M0 -440 L340 0 L60 0 Z" fill={p.lo(c, 0.36)} />
<path d="M0 -440 L-340 0 L-300 0 Z" fill={p.hi(c, 0.25)} />
<path d="M-90 0 L0 -250 L90 0 Z" fill={p.c(mix(c, p.pal.ink, 0.75))} />
<path d="M0 -250 L-130 0 L-90 0 Z" fill={p.hi(c, 0.15)} />
<path d="M0 -440 L0 -480 M-340 0 L-420 -20 M340 0 L420 -20" stroke={p.c(p.pal.ink)} strokeWidth={6} />
</g>;
},
fire: (p) => <g>
<ellipse cx={0} cy={-8} rx={260} ry={40} fill={p.pal.light} opacity={0.22} />
<path d="M-110 -10 L100 -50 M-100 -50 L110 -10" stroke={p.c(p.pal.trunk)} strokeWidth={30} strokeLinecap="round" />
<path d="M-104 -16 L96 -54" stroke={p.lo(p.pal.trunk, 0.4)} strokeWidth={10} strokeLinecap="round" />
<path d="M-80 -30 Q-100 -150 -24 -230 Q-14 -150 34 -132 Q54 -210 18 -290 Q130 -200 86 -30 Z" fill="#e8562a" />
<path d="M-56 -32 Q-66 -120 -10 -180 Q0 -110 40 -100 Q54 -150 40 -200 Q100 -130 66 -32 Z" fill="#ff9a2a" />
<path d="M-24 -32 Q-34 -96 8 -130 Q16 -84 40 -76 Q48 -54 34 -32 Z" fill="#ffe066" />
</g>,
ark: (p, color) => {
// Arca: casco de tábuas com betume escuro embaixo, casa de um andar em cima com janelinhas e uma porta.
const wood = color ?? "#8a5a32";
const cabin = mix(wood, "#ffffff", 0.12);
return <g>
<path d="M-390 -150 L390 -150 Q362 -26 290 0 L-290 0 Q-362 -26 -390 -150 Z" fill={p.c(wood)} />
<path d="M-390 -150 L-340 -150 Q-330 -40 -270 0 L-290 0 Q-362 -26 -390 -150 Z" fill={p.hi(wood, 0.2)} />
<path d="M180 -150 L390 -150 Q362 -26 290 0 L160 0 Q200 -60 180 -150 Z" fill={p.lo(wood, 0.3)} />
<path d="M-370 -60 Q-330 -6 -290 0 L290 0 Q330 -6 370 -60 Z" fill={p.c("#3a2a22")} opacity={0.8} />
{[-120, -92, -64, -36].map((y) => <path key={y} d={`M${-386 + (y + 150) * 0.2} ${y} L${386 - (y + 150) * 0.2} ${y}`} stroke={p.lo(wood, 0.5)} strokeWidth={5} opacity={0.7} />)}
<rect x={-400} y={-162} width={800} height={18} rx={6} fill={p.hi(mix(wood, "#6b4426", 0.5), 0.2)} />
<rect x={-230} y={-290} width={460} height={130} fill={p.c(cabin)} />
<rect x={150} y={-290} width={80} height={130} fill={p.lo(cabin, 0.32)} />
{[-180, -110, -40, 30, 100].map((x) => <rect key={x} x={x} y={-262} width={34} height={26} rx={3} fill={p.c(mix(p.pal.ink, wood, 0.3))} />)}
<rect x={160} y={-224} width={56} height={64} rx={4} fill={p.lo("#4a2f1c", 0.3)} />
<polygon points="-262,-288 0,-352 262,-288" fill={p.c("#6a4428")} />
<polygon points="0,-352 262,-288 120,-288" fill={p.lo("#6a4428", 0.35)} />
</g>;
},
ark_frame: (p, color) => {
// Arca em construção: quilha, costelas curvas de madeira clara e só as primeiras fileiras de tábuas.
const wood = color ?? "#c9955a";
return <g>
<rect x={-380} y={-26} width={760} height={26} rx={6} fill={p.c("#7a5232")} />
{Array.from({ length: 11 }, (_, i) => {
const x = -330 + i * 66;
const k = 1 - Math.abs(x) / 420;
const d = `M${x} -20 Q${x * 1.02} ${-110 - k * 40} ${x * 1.14} ${-170 - k * 30}`;
return <g key={i}><path d={d} stroke={p.c(wood)} strokeWidth={16} fill="none" strokeLinecap="round" />
<path d={d} transform="translate(5 0)" stroke={p.lo(wood, 0.35)} strokeWidth={6} fill="none" strokeLinecap="round" /></g>;
})}
<path d="M-360 -60 Q-320 -12 -280 -14 L280 -14 Q320 -12 360 -60 L340 -92 Q300 -54 270 -56 L-270 -56 Q-300 -54 -340 -92 Z" fill={p.c("#8a5a32")} />
<path d="M-300 -34 L300 -34" stroke={p.lo("#8a5a32", 0.5)} strokeWidth={5} />
<rect x={-390} y={-200} width={780} height={12} rx={5} fill={p.c(wood)} />
<rect x={-390} y={-192} width={780} height={4} rx={2} fill={p.lo(wood, 0.4)} />
</g>;
},
scaffold: (p, color) => {
const wood = color ?? "#a87a48";
return <g strokeLinecap="round">
<path d="M-110 0 L-110 -330 M110 0 L110 -330" strokeWidth={14} stroke={p.c(wood)} />
<path d="M-104 0 L-104 -330 M116 0 L116 -330" strokeWidth={5} stroke={p.lo(wood, 0.4)} />
<path d="M-130 -120 L130 -120 M-130 -240 L130 -240" strokeWidth={18} stroke={p.c("#7a5232")} />
<path d="M-130 -114 L130 -114 M-130 -234 L130 -234" strokeWidth={6} stroke={p.lo("#7a5232", 0.4)} />
<path d="M-110 -10 L110 -120 M110 -130 L-110 -240" strokeWidth={8} stroke={p.c(wood)} opacity={0.85} />
</g>;
},
planks: (p, color) => {
const w = color ?? "#c9955a";
return <g>{[0, 1, 2, 3].map((i) => <Box key={i} x={-170 + (i % 2) * 22} y={-26 - i * 22} w={340 - i * 14} h={20} fill={i % 2 ? w : mix(w, "#000000", 0.12)} p={p} side={0.1} top={5} rx={4} />)}</g>;
},
};
/**
* Parte da FRENTE das peças que podem ter gente dentro (casco e amurada da arca; lataria abaixo das janelas do
* carro). Com `occupied: true` no lugar, ela é desenhada de novo POR CIMA dos personagens: eles ficam "dentro".
*/
export const FRONT_PART: Record<string, Draw> = {
ark: (p, color) => {
const wood = color ?? "#8a5a32";
return <g>
<path d="M-390 -150 L390 -150 Q362 -26 290 0 L-290 0 Q-362 -26 -390 -150 Z" fill={p.c(wood)} />
<path d="M-390 -150 L-340 -150 Q-330 -40 -270 0 L-290 0 Q-362 -26 -390 -150 Z" fill={p.hi(wood, 0.2)} />
<path d="M180 -150 L390 -150 Q362 -26 290 0 L160 0 Q200 -60 180 -150 Z" fill={p.lo(wood, 0.3)} />
<path d="M-370 -60 Q-330 -6 -290 0 L290 0 Q330 -6 370 -60 Z" fill={p.c("#3a2a22")} opacity={0.8} />
{[-120, -92, -64, -36].map((y) => <path key={y} d={`M${-386 + (y + 150) * 0.2} ${y} L${386 - (y + 150) * 0.2} ${y}`} stroke={p.lo(wood, 0.5)} strokeWidth={5} opacity={0.7} />)}
<rect x={-400} y={-162} width={800} height={18} rx={6} fill={p.hi(mix(wood, "#6b4426", 0.5), 0.2)} />
</g>;
},
car: (p, color) => {
const c = color ?? "#c8443a";
return <g transform="scale(2.5)">
<path d="M-150 -40 L-150 -90 Q-140 -110 -100 -112 L150 -100 L150 -40 Z" fill={p.c(c)} />
<path d="M-150 -74 L150 -74 L150 -40 L-150 -40 Z" fill={p.lo(c, 0.3)} />
<rect x={140} y={-96} width={12} height={14} rx={3} fill={p.c("#ffe6a0")} /><rect x={-152} y={-92} width={10} height={12} rx={3} fill={p.c("#e84a3a")} />
<rect x={-156} y={-48} width={312} height={10} rx={4} fill={p.lo(c, 0.5)} />
{[-90, 95].map((x) => <g key={x}><circle cx={x} cy={-35} r={32} fill={p.c("#1e1f26")} /><circle cx={x} cy={-35} r={15} fill={p.c("#9ea2ac")} /><circle cx={x + 4} cy={-33} r={8} fill={p.lo("#9ea2ac", 0.4)} /></g>)}
</g>;
},
};
+343
View File
@@ -0,0 +1,343 @@
// Peças de interior: porta, janela, mesa, cama, estante, arquivo, armários de metal, quadro, luminárias, escrivaninha,
// varal. Base em (0,0) no chão; as de parede (janela, quadro, varal) já desenham na altura certa acima do chão; a
// luminária pendente tem a origem no TETO (y cresce para baixo). Luz da esquerda.
import React from "react";
import { mix, type Paint } from "./paint";
import { Box } from "./built";
import type { Draw } from "./nature";
const BOOKS = ["#c8483a", "#e0a63a", "#3f78b8", "#4f9a6a", "#e8e0cc", "#7a4a8a", "#2f4a6a", "#b86a3a"];
const CLOTHES = ["#4f9a5a", "#e2b33a", "#c8483a", "#3f6aa8", "#e8e2d6", "#7f9a5a", "#8a5ab0"];
/** Taça de troféu (dourada), base no chão da prateleira. */
function Trophy({ x, y, s, p }: { x: number; y: number; s: number; p: Paint }) {
const g = "#d6a536";
return <g transform={`translate(${x} ${y}) scale(${s})`}>
<rect x={-24} y={-14} width={48} height={14} rx={2} fill={p.c(mix(g, "#5a4020", 0.4))} />
<rect x={-6} y={-40} width={12} height={28} fill={p.c(g)} />
<path d="M-34 -100 L34 -100 Q32 -52 0 -40 Q-32 -52 -34 -100 Z" fill={p.c(g)} />
<path d="M6 -100 L34 -100 Q32 -52 0 -40 Q14 -60 6 -100 Z" fill={p.lo(g, 0.38)} />
<path d="M-34 -92 Q-56 -88 -48 -70 Q-42 -60 -26 -62 M34 -92 Q56 -88 48 -70 Q42 -60 26 -62" stroke={p.c(g)} strokeWidth={6} fill="none" />
<rect x={-26} y={-96} width={8} height={30} rx={4} fill={p.hi(g, 0.5)} />
</g>;
}
/** O que vai numa prateleira (sorteado pela semente): livros, troféu, potes/caixas ou planta. */
function ShelfItems({ x0, x1, y, h, p }: { x0: number; x1: number; y: number; h: number; p: Paint }) {
const kind = p.r();
if (kind < 0.18) return <Trophy x={(x0 + x1) / 2 + (p.r() - 0.5) * 80} y={y} s={h / 110} p={p} />;
if (kind < 0.3) {
return <g>{[0, 1, 2].map((i) => {
const c = BOOKS[Math.floor(p.r() * BOOKS.length)];
const w = 60 + p.r() * 30;
const hh = h * (0.4 + p.r() * 0.35);
const x = x0 + 14 + i * ((x1 - x0) / 3);
return <g key={i}><rect x={x} y={y - hh} width={w} height={hh} rx={6} fill={p.c(c)} /><rect x={x + w * 0.7} y={y - hh} width={w * 0.3} height={hh} rx={4} fill={p.lo(c, 0.35)} /></g>;
})}</g>;
}
if (kind < 0.38) {
const pot = "#c0704a";
const cx = (x0 + x1) / 2;
return <g>
<path d={`M${cx - 40} ${y - 60} L${cx + 40} ${y - 60} L${cx + 30} ${y} L${cx - 30} ${y} Z`} fill={p.c(pot)} />
<path d={`M${cx + 10} ${y - 60} L${cx + 40} ${y - 60} L${cx + 30} ${y} L${cx + 8} ${y} Z`} fill={p.lo(pot, 0.35)} />
{[-50, -15, 20, 50].map((dx, i) => <ellipse key={i} cx={cx + dx} cy={y - 70 - (i % 2) * 30} rx={22} ry={44} transform={`rotate(${dx / 2} ${cx + dx} ${y - 70})`} fill={i % 2 ? p.lo(p.pal.leaf, 0.3) : p.c(p.pal.leaf)} />)}
</g>;
}
// Livros em pé, de alturas e cores variadas (às vezes um deitado no fim da fileira).
const books: React.ReactNode[] = [];
let x = x0 + 6;
while (x < x1 - 30) {
const w = 18 + p.r() * 16;
const hh = h * (0.62 + p.r() * 0.32);
const c = BOOKS[Math.floor(p.r() * BOOKS.length)];
books.push(<g key={x}><rect x={x} y={y - hh} width={w} height={hh} rx={2} fill={p.c(c)} /><rect x={x + w * 0.62} y={y - hh} width={w * 0.38} height={hh} fill={p.lo(c, 0.35)} />
<rect x={x} y={y - hh * 0.8} width={w} height={4} fill={p.hi(c, 0.4)} /></g>);
x += w + 2;
if (p.r() < 0.12) x += 24;
}
return <g>{books}</g>;
}
export const INDOOR: Record<string, Draw> = {
door: (p, color) => {
const d = color ?? "#6e4a30";
const trim = mix(p.pal.wall, "#f4ece0", 0.55);
return <g>
<rect x={-172} y={-664} width={344} height={664} rx={6} fill={p.c(trim)} />
<rect x={140} y={-664} width={32} height={664} fill={p.lo(trim, 0.3)} />
<rect x={-150} y={-640} width={300} height={640} fill={p.c(d)} />
<rect x={110} y={-640} width={40} height={640} fill={p.lo(d, 0.35)} />
{[[-600, 250], [-320, 270]].map(([y, h]) => <g key={y}>
<rect x={-112} y={y} width={200} height={h} rx={4} fill={p.lo(d, 0.16)} />
<rect x={-112} y={y} width={12} height={h} fill={p.lo(d, 0.42)} /><rect x={-112} y={y} width={200} height={10} fill={p.lo(d, 0.42)} />
<rect x={76} y={y} width={12} height={h} fill={p.hi(d, 0.25)} /><rect x={-112} y={y + h - 10} width={200} height={10} fill={p.hi(d, 0.25)} />
</g>)}
<rect x={96} y={-350} width={22} height={70} rx={8} fill={p.c("#c9a560")} />
<circle cx={107} cy={-316} r={12} fill={p.hi("#e6c27a", 0.3)} />
</g>;
},
window: (p, color) => {
// Janela na parede: moldura, céu lá fora (claro de dia, escuro com lua à noite), copa de árvore, cortinas.
const trim = mix(p.pal.wall, "#f4ece0", 0.6);
const out = color ?? (p.night ? "#1c2a5a" : mix(p.pal.sky[2], "#ffffff", 0.25));
const outTop = p.night ? "#121c44" : mix(p.pal.sky[1], "#ffffff", 0.2);
const curtain = p.r() > 0.45 ? ["#b8483a", "#3f6aa8", "#c89a3a", "#6a8a4a"][Math.floor(p.r() * 4)] : null;
return <g>
<rect x={-210} y={-640} width={420} height={420} rx={6} fill={p.c(trim)} />
<rect x={180} y={-640} width={30} height={420} fill={p.lo(trim, 0.3)} />
<rect x={-186} y={-616} width={372} height={372} fill={p.c(out)} />
<rect x={-186} y={-616} width={372} height={170} fill={p.c(outTop)} />
{p.night && <circle cx={-90} cy={-540} r={30} fill={p.c("#f4ecc8")} />}
<g fill={p.night ? p.c("#1a3040") : p.c(mix(p.pal.leaf, out, 0.35))}>
<circle cx={-140} cy={-300} r={90} /><circle cx={-40} cy={-280} r={70} /><circle cx={120} cy={-290} r={80} /><circle cx={-170} cy={-380} r={60} />
</g>
<path d="M-120 -616 L-40 -616 L-186 -380 L-186 -510 Z" fill="#ffffff" opacity={0.14} />
<rect x={-8} y={-616} width={16} height={372} fill={p.c(trim)} /><rect x={-186} y={-438} width={372} height={16} fill={p.c(trim)} />
<rect x={2} y={-616} width={6} height={372} fill={p.lo(trim, 0.3)} />
<rect x={-232} y={-236} width={464} height={26} rx={5} fill={p.hi(trim, 0.2)} />
<rect x={-224} y={-210} width={448} height={14} fill={p.lo(p.pal.wall, 0.45)} opacity={0.7} />
{curtain && [-1, 1].map((s) => <g key={s}>
<path d={`M${s * 190} -666 L${s * 270} -666 L${s * 290} -200 L${s * 200} -200 Q${s * 214} -440 ${s * 190} -666 Z`} fill={p.c(curtain)} />
<path d={`M${s * 236} -666 L${s * 270} -666 L${s * 290} -200 L${s * 250} -200 Z`} fill={s > 0 ? p.lo(curtain, 0.35) : p.hi(curtain, 0.18)} />
<path d={`M${s * 214} -640 L${s * 224} -210`} stroke={p.lo(curtain, 0.3)} strokeWidth={6} />
</g>)}
{curtain && <rect x={-300} y={-680} width={600} height={16} rx={8} fill={p.c(mix(p.pal.trunk, "#8a6a4a", 0.3))} />}
</g>;
},
table: (p, color) => {
const w = color ?? "#9a643c";
return <g>
{[-236, 220].map((x) => <rect key={x} x={x} y={-300} width={18} height={270} fill={p.lo(w, 0.5)} />)}
<polygon points="-280,-270 280,-270 250,-304 -250,-304" fill={p.hi(w, 0.22)} />
<rect x={-280} y={-270} width={560} height={28} fill={p.c(w)} />
<rect x={-280} y={-248} width={560} height={6} fill={p.lo(w, 0.45)} />
<rect x={236} y={-270} width={44} height={28} fill={p.lo(w, 0.32)} />
{[-262, 236].map((x) => <g key={x}><rect x={x} y={-242} width={26} height={242} fill={p.c(w)} /><rect x={x + 14} y={-242} width={12} height={242} fill={p.lo(w, 0.38)} /></g>)}
</g>;
},
bed: (p, color) => {
const blanket = color ?? "#4f64a8";
const wood = mix(p.pal.trunk, "#9a6a40", 0.4);
const sheet = "#ecebe6";
return <g>
<path d="M-390 0 L-390 -330 Q-390 -380 -350 -380 Q-320 -380 -320 -330 L-320 0 Z" fill={p.c(wood)} />
<rect x={-340} y={-380} width={20} height={380} fill={p.lo(wood, 0.35)} />
<rect x={-330} y={-118} width={680} height={50} fill={p.c(wood)} /><rect x={-330} y={-80} width={680} height={12} fill={p.lo(wood, 0.4)} />
<rect x={-320} y={-210} width={660} height={96} rx={18} fill={p.c(sheet)} />
<rect x={-312} y={-262} width={160} height={64} rx={28} fill={p.hi(sheet, 0.2)} />
<path d="M-180 -262 Q-160 -230 -168 -200" stroke={p.lo(sheet, 0.3)} strokeWidth={6} fill="none" />
<path d="M-120 -222 Q100 -238 344 -214 L350 -96 Q120 -88 -120 -100 Z" fill={p.c(blanket)} />
<path d="M-120 -222 Q100 -238 344 -214 L344 -196 Q100 -214 -120 -204 Z" fill={p.hi(blanket, 0.25)} />
<path d="M0 -224 Q20 -160 -10 -100 M150 -228 Q180 -170 160 -94" stroke={p.lo(blanket, 0.35)} strokeWidth={10} fill="none" strokeLinecap="round" />
<rect x={300} y={-216} width={50} height={120} fill={p.lo(blanket, 0.3)} />
<rect x={340} y={-260} width={36} height={260} rx={6} fill={p.c(wood)} /><rect x={360} y={-260} width={16} height={260} fill={p.lo(wood, 0.4)} />
{[-310, 320].map((x) => <rect key={x} x={x} y={-70} width={22} height={70} fill={p.lo(wood, 0.3)} />)}
</g>;
},
shelf: (p, color) => {
const w = color ?? mix(p.pal.trunk, "#8a5a36", 0.4);
const back = p.lo(w, 0.55);
const ys = [-616, -466, -316, -166];
return <g>
<polygon points="200,0 200,-640 236,-664 236,-16" fill={p.lo(w, 0.42)} />
<rect x={-200} y={-640} width={400} height={640} fill={p.c(w)} />
<rect x={-176} y={-616} width={352} height={590} fill={back} />
{ys.map((y) => <g key={y}>
<rect x={-176} y={y + 122} width={352} height={14} fill={p.lo(w, 0.7)} opacity={0.5} />
<ShelfItems x0={-170} x1={170} y={y + 128} h={118} p={p} />
<rect x={-180} y={y + 128} width={360} height={22} fill={p.c(w)} />
<rect x={-180} y={y + 128} width={360} height={6} fill={p.hi(w, 0.3)} />
</g>)}
<rect x={-200} y={-640} width={24} height={640} fill={p.hi(w, 0.14)} />
<rect x={176} y={-640} width={24} height={640} fill={p.lo(w, 0.25)} />
<rect x={-214} y={-664} width={428} height={28} rx={4} fill={p.hi(w, 0.18)} />
<polygon points="214,-664 250,-686 250,-662 214,-636" fill={p.lo(w, 0.5)} />
</g>;
},
cabinet: (p, color) => {
// Arquivo/armário de gavetas.
const m = color ?? "#6f7f8a";
return <g>
<polygon points="150,0 150,-560 192,-584 192,-18" fill={p.lo(m, 0.42)} />
<polygon points="-150,-560 -108,-584 192,-584 150,-560" fill={p.hi(m, 0.3)} />
<rect x={-150} y={-560} width={300} height={560} fill={p.c(m)} />
{[0, 1, 2, 3].map((i) => {
const y = -540 + i * 132;
return <g key={i}>
<rect x={-130} y={y} width={260} height={118} rx={5} fill={p.c(mix(m, "#ffffff", 0.06))} />
<rect x={-130} y={y + 108} width={260} height={10} fill={p.lo(m, 0.4)} />
<rect x={-130} y={y} width={260} height={6} fill={p.hi(m, 0.25)} />
<rect x={-34} y={y + 26} width={68} height={26} rx={3} fill={p.c("#ece6d4")} />
<rect x={-46} y={y + 64} width={92} height={16} rx={8} fill={p.lo(m, 0.55)} />
<rect x={-46} y={y + 64} width={92} height={6} rx={3} fill={p.hi(m, 0.4)} />
</g>;
})}
<rect x={118} y={-560} width={32} height={560} fill={p.lo(m, 0.25)} />
</g>;
},
locker: (p, color) => {
// Fileira de 3 armários de metal (vestiário, escola, fábrica).
const m = color ?? "#3f5f8c";
return <g>
<polygon points="300,0 300,-760 340,-784 340,-20" fill={p.lo(m, 0.45)} />
<polygon points="-300,-760 -260,-784 340,-784 300,-760" fill={p.hi(m, 0.25)} />
<rect x={-300} y={-760} width={600} height={760} fill={p.lo(m, 0.3)} />
{[-1, 0, 1].map((k) => {
const x = k * 198 - 96;
return <g key={k}>
<rect x={x} y={-744} width={192} height={680} rx={4} fill={p.c(m)} />
<rect x={x + 160} y={-744} width={32} height={680} fill={p.lo(m, 0.28)} />
<rect x={x} y={-744} width={192} height={6} fill={p.hi(m, 0.3)} />
{[0, 1, 2, 3].map((i) => <rect key={i} x={x + 36} y={-700 + i * 26} width={110} height={12} rx={6} fill={p.lo(m, 0.55)} />)}
{[0, 1, 2].map((i) => <rect key={i} x={x + 36} y={-150 + i * 26} width={110} height={12} rx={6} fill={p.lo(m, 0.55)} />)}
<rect x={x + 150} y={-430} width={16} height={86} rx={8} fill={p.hi(m, 0.4)} />
<rect x={x + 60} y={-560} width={56} height={34} rx={4} fill={p.c("#ece6d4")} opacity={0.85} />
</g>;
})}
<rect x={-300} y={-64} width={600} height={64} fill={p.lo(m, 0.5)} />
</g>;
},
frame: (p, color) => {
// Quadro na parede (paisagem, foto de grupo, retrato ou abstrato).
const f = color ?? "#9a6a3a";
const kind = Math.floor(p.r() * 4);
const x = -170;
const y = -700;
const w = 340;
const h = 260;
const ix = x + 26;
const iy = y + 26;
const iw = w - 52;
const ih = h - 52;
const sepia = mix("#d8c8a0", p.pal.wall, 0.15);
const pic: React.ReactNode =
kind === 0 ? <g>
<rect x={ix} y={iy} width={iw} height={ih} fill={p.c(mix(p.pal.sky[1], "#ffffff", 0.3))} />
<circle cx={ix + iw * 0.25} cy={iy + ih * 0.3} r={22} fill={p.c("#ffe08a")} />
<path d={`M${ix} ${iy + ih} L${ix} ${iy + ih * 0.62} Q${ix + iw * 0.3} ${iy + ih * 0.4} ${ix + iw * 0.55} ${iy + ih * 0.62} Q${ix + iw * 0.8} ${iy + ih * 0.45} ${ix + iw} ${iy + ih * 0.6} L${ix + iw} ${iy + ih} Z`} fill={p.c("#6a9a5a")} />
<path d={`M${ix + iw * 0.55} ${iy + ih * 0.62} Q${ix + iw * 0.8} ${iy + ih * 0.45} ${ix + iw} ${iy + ih * 0.6} L${ix + iw} ${iy + ih} L${ix + iw * 0.5} ${iy + ih} Z`} fill={p.lo("#6a9a5a", 0.3)} />
</g>
: kind === 1 ? <g>
<rect x={ix} y={iy} width={iw} height={ih} fill={p.c(sepia)} />
{[0, 1, 2, 3, 4].map((i) => {
const cx = ix + 40 + i * ((iw - 80) / 4);
return <g key={i} fill={p.lo(sepia, 0.55)}><circle cx={cx} cy={iy + ih * 0.42} r={17} /><rect x={cx - 24} y={iy + ih * 0.42 + 18} width={48} height={ih * 0.4} rx={14} /></g>;
})}
<rect x={ix} y={iy + ih * 0.86} width={iw} height={ih * 0.14} fill={p.lo(sepia, 0.3)} />
</g>
: kind === 2 ? <g>
<rect x={ix} y={iy} width={iw} height={ih} fill={p.c("#c8b490")} />
<circle cx={ix + iw / 2} cy={iy + ih * 0.42} r={40} fill={p.lo("#c8b490", 0.5)} />
<path d={`M${ix + iw / 2 - 80} ${iy + ih} Q${ix + iw / 2} ${iy + ih * 0.55} ${ix + iw / 2 + 80} ${iy + ih} Z`} fill={p.lo("#c8b490", 0.5)} />
</g>
: <g>
<rect x={ix} y={iy} width={iw} height={ih} fill={p.c("#ece2cc")} />
<rect x={ix + 20} y={iy + 20} width={iw * 0.45} height={ih * 0.5} fill={p.c("#c8483a")} />
<rect x={ix + iw * 0.55} y={iy + ih * 0.35} width={iw * 0.35} height={ih * 0.5} fill={p.c("#3f6aa8")} />
<circle cx={ix + iw * 0.4} cy={iy + ih * 0.7} r={30} fill={p.c("#e2b33a")} />
</g>;
return <g>
<rect x={x + 14} y={y + 16} width={w} height={h} rx={4} fill={p.pal.ink} opacity={0.22} />
<rect x={x} y={y} width={w} height={h} rx={4} fill={p.c(f)} />
<rect x={x} y={y} width={w} height={10} fill={p.hi(f, 0.3)} /><rect x={x} y={y} width={10} height={h} fill={p.hi(f, 0.3)} />
<rect x={x + w - 12} y={y} width={12} height={h} fill={p.lo(f, 0.38)} /><rect x={x} y={y + h - 12} width={w} height={12} fill={p.lo(f, 0.38)} />
{pic}
<rect x={ix} y={iy} width={iw} height={8} fill={p.pal.ink} opacity={0.2} /><rect x={ix} y={iy} width={8} height={ih} fill={p.pal.ink} opacity={0.15} />
</g>;
},
pendant: (p, color) => {
// Luminária pendente: origem no teto, fio descendo, cúpula e a lâmpada acesa por baixo.
const s = color ?? "#2f3f6a";
return <g>
<rect x={-3} y={-20} width={6} height={290} fill={p.c(p.pal.ink)} />
<rect x={-18} y={250} width={36} height={24} rx={4} fill={p.c(mix(s, p.pal.ink, 0.3))} />
<circle cx={0} cy={372} r={150} fill={p.pal.light} opacity={0.14} />
<path d="M-130 370 Q-124 272 0 266 Q124 272 130 370 Z" fill={p.c(s)} />
<path d="M30 268 Q124 274 130 370 L60 370 Q66 300 30 268 Z" fill={p.lo(s, 0.38)} />
<path d="M-104 352 Q-104 296 -40 276 Q-84 300 -84 352 Z" fill={p.hi(s, 0.3)} />
<ellipse cx={0} cy={370} rx={130} ry={20} fill={p.pal.light} />
<ellipse cx={0} cy={376} rx={44} ry={24} fill="#fffbe8" />
</g>;
},
desklamp: (p, color) => {
// Luminária de mesa articulada, acesa (poça de luz na base). Fica em cima de mesa/escrivaninha próxima.
const m = color ?? "#5f7a4a";
return <g>
<path d="M40 -250 L240 0 L-40 0 L-10 -230 Z" fill={p.pal.light} opacity={0.16} />
<ellipse cx={100} cy={-4} rx={150} ry={22} fill={p.pal.light} opacity={0.3} />
<ellipse cx={-60} cy={-12} rx={70} ry={16} fill={p.c(m)} /><rect x={-130} y={-12} width={140} height={12} fill={p.lo(m, 0.35)} />
<path d="M-60 -16 L-100 -200 M-100 -200 L20 -300" stroke={p.c(m)} strokeWidth={18} strokeLinecap="round" fill="none" />
<path d="M-54 -18 L-94 -198" stroke={p.lo(m, 0.4)} strokeWidth={6} strokeLinecap="round" />
<circle cx={-100} cy={-200} r={16} fill={p.lo(m, 0.3)} />
<g transform="translate(20 -300) rotate(35)">
<path d="M-30 -30 L30 -30 L80 60 L-80 60 Z" fill={p.c(m)} />
<path d="M10 -30 L30 -30 L80 60 L40 60 Z" fill={p.lo(m, 0.4)} />
<ellipse cx={0} cy={60} rx={80} ry={14} fill={p.pal.light} />
<ellipse cx={0} cy={62} rx={30} ry={10} fill="#fffbe8" />
</g>
</g>;
},
desk: (p, color) => {
// Escrivaninha de 2 gaveteiros, com papéis, livros e caneca por cima.
const w = color ?? "#8a5a36";
const knob = "#d8b060";
return <g>
<rect x={-110} y={-276} width={220} height={236} fill={p.lo(w, 0.62)} />
{[-310, 110].map((x) => <g key={x}>
<rect x={x} y={-276} width={200} height={276} fill={p.c(w)} />
<rect x={x + 170} y={-276} width={30} height={276} fill={p.lo(w, 0.3)} />
{[0, 1, 2].map((i) => <g key={i}>
<rect x={x + 14} y={-262 + i * 86} width={172} height={74} rx={4} fill={p.c(mix(w, "#ffffff", 0.05))} />
<rect x={x + 14} y={-196 + i * 86} width={172} height={8} fill={p.lo(w, 0.45)} />
<circle cx={x + 100} cy={-226 + i * 86} r={11} fill={p.hi(knob, 0.2)} /><circle cx={x + 104} cy={-223 + i * 86} r={5} fill={p.lo(knob, 0.4)} />
</g>)}
</g>)}
<polygon points="-330,-300 330,-300 304,-330 -304,-330" fill={p.hi(w, 0.22)} />
<rect x={-330} y={-300} width={660} height={26} fill={p.c(w)} /><rect x={-330} y={-280} width={660} height={6} fill={p.lo(w, 0.5)} />
<rect x={290} y={-300} width={40} height={26} fill={p.lo(w, 0.32)} />
<g transform={`translate(${p.r() > 0.5 ? 90 : -230} -312)`}>
{[0, 1, 2].map((i) => <rect key={i} x={i * 4} y={-i * 7} width={130} height={8} rx={2} fill={p.c(i % 2 ? "#f2eee4" : "#e2dccc")} />)}
</g>
<g transform="translate(200 -312)">
<rect x={0} y={-30} width={100} height={30} rx={3} fill={p.c("#3f6aa8")} /><rect x={6} y={-54} width={90} height={24} rx={3} fill={p.c("#c8483a")} />
<rect x={70} y={-30} width={30} height={30} fill={p.lo("#3f6aa8", 0.35)} />
</g>
<g transform="translate(-90 -312)">
<rect x={-22} y={-48} width={44} height={48} rx={6} fill={p.c("#ece6d8")} /><rect x={6} y={-48} width={16} height={48} fill={p.lo("#ece6d8", 0.3)} />
<path d="M22 -38 Q42 -30 22 -14" stroke={p.c("#ece6d8")} strokeWidth={7} fill="none" />
</g>
</g>;
},
clothesline: (p, color) => {
// Varal: corda com roupas presas. Ao ar livre tem dois postes; dentro de casa fica preso na parede.
const rope = mix(p.pal.trunk, "#c8b08a", 0.5);
// Dentro de casa a corda vai de parede a parede (mais alta e mais comprida, sem postes).
const y0 = p.indoor ? -880 : -720;
const half = p.indoor ? 720 : 500;
const yAt = (t: number) => y0 + 120 * t * (1 - t);
const items = p.indoor ? [0.12, 0.25, 0.38, 0.51, 0.64, 0.77, 0.9] : [0.1, 0.26, 0.42, 0.58, 0.74, 0.9];
return <g>
{!p.indoor && [-500, 500].map((x) => <g key={x}><rect x={x - 14} y={-760} width={28} height={760} fill={p.c(p.pal.trunk)} /><rect x={x + 2} y={-760} width={12} height={760} fill={p.lo(p.pal.trunk, 0.4)} /></g>)}
<path d={`M${-half} ${y0} Q0 ${y0 + 120} ${half} ${y0}`} stroke={p.c(rope)} strokeWidth={6} fill="none" />
{items.map((t, i) => {
const x = -half + 2 * half * t;
const y = yAt(t);
const c = color && i % 2 === 0 ? color : CLOTHES[Math.floor(p.r() * CLOTHES.length)];
const towel = p.r() < 0.3;
const tilt = (t - 0.5) * 10;
return <g key={i} transform={`translate(${x} ${y - 4}) rotate(${tilt})`}>
{towel
? <g><rect x={-46} y={0} width={92} height={150} rx={4} fill={p.c(c)} /><rect x={18} y={0} width={28} height={150} fill={p.lo(c, 0.35)} />
<rect x={-46} y={120} width={92} height={10} fill={p.hi(c, 0.4)} /></g>
: <g>
<path d="M-40 0 L-86 26 L-68 64 L-46 54 L-46 168 L46 168 L46 54 L68 64 L86 26 L40 0 Q0 18 -40 0 Z" fill={p.c(c)} />
<path d="M14 8 L40 0 L86 26 L68 64 L46 54 L46 168 L14 168 Z" fill={p.lo(c, 0.35)} />
<path d="M-40 0 Q0 18 40 0 L28 -2 Q0 10 -28 -2 Z" fill={p.hi(c, 0.5)} />
</g>}
<rect x={-30} y={-12} width={10} height={22} rx={2} fill={p.c("#c8a070")} /><rect x={20} y={-12} width={10} height={22} rx={2} fill={p.c("#c8a070")} />
</g>;
})}
</g>;
},
};
+142
View File
@@ -0,0 +1,142 @@
// Peças da natureza: árvores, mato, pedras, montanha, nuvem, palmeira, ondas. Base em (0,0); luz da esquerda.
import React from "react";
import { mix, type Paint } from "./paint";
export type Draw = (p: Paint, color?: string) => React.ReactNode;
type Blob = [number, number, number];
/** Copa/moita/nuvem em 2 tons: tudo na cor da sombra, a parte de cima-esquerda na base e brilho nos topos. */
export function Foliage({ blobs, color, p, shadeK = 0.5, hiK = 0.14, lift = 0.16 }: { blobs: Blob[]; color: string; p: Paint; shadeK?: number; hiK?: number; lift?: number }) {
const cx = blobs.reduce((s, b) => s + b[0], 0) / blobs.length;
const cy = blobs.reduce((s, b) => s + b[1], 0) / blobs.length;
const top = Math.min(...blobs.map((b) => b[1] - b[2]));
return (
<g>
<g fill={p.lo(color, shadeK)}>{blobs.map(([x, y, r], i) => <circle key={i} cx={x} cy={y} r={r} />)}</g>
<g fill={p.c(color)}>{blobs.map(([x, y, r], i) => <circle key={i} cx={x - r * lift * 0.8} cy={y - r * lift} r={r * 0.8} />)}</g>
{hiK > 0 && <g fill={p.hi(color, hiK)}>
{blobs.filter(([x, y, r]) => x <= cx + 40 && y - r <= top + (cy - top) * 0.5).map(([x, y, r], i) => <circle key={i} cx={x - r * 0.24} cy={y - r * 0.3} r={r * 0.6} />)}
</g>}
</g>
);
}
const jitter = (p: Paint, blobs: Blob[], k = 1): Blob[] => blobs.map(([x, y, s]) => [x + (p.r() - 0.5) * 36 * k, y + (p.r() - 0.5) * 28 * k, s * (0.9 + p.r() * 0.2)]);
export const NATURE: Record<string, Draw> = {
tree: (p, color) => {
const leaf = color ?? p.pal.leaf;
const bark = p.pal.trunk;
const blobs = jitter(p, [[-210, -560, 150], [205, -575, 150], [0, -520, 170], [-100, -700, 175], [120, -710, 170], [5, -840, 150],
[-285, -660, 110], [285, -670, 105], [0, -660, 200]]);
return <g>
<path d="M-56 0 Q-30 -10 -30 -200 L-28 -400 L28 -400 Q30 -200 32 -10 Q50 0 62 0 Z" fill={p.c(bark)} />
<path d="M6 -2 Q20 -150 16 -400 L28 -400 Q30 -200 32 -10 Q50 0 62 0 Z" fill={p.lo(bark, 0.4)} />
<path d="M-12 -330 Q-90 -420 -170 -520 M8 -360 Q70 -460 150 -560 M0 -380 L-6 -560" stroke={p.c(bark)} strokeWidth={30} strokeLinecap="round" fill="none" />
<path d="M14 -364 Q76 -456 156 -552" stroke={p.lo(bark, 0.4)} strokeWidth={12} strokeLinecap="round" fill="none" />
<path d="M-20 -60 Q-14 -120 -18 -180 M-4 -240 Q2 -280 -2 -320" stroke={p.lo(bark, 0.3)} strokeWidth={5} strokeLinecap="round" fill="none" />
<Foliage blobs={blobs} color={leaf} p={p} />
</g>;
},
pine: (p, color) => {
const leaf = color ?? mix(p.pal.leaf, "#1f5a46", 0.35);
const tiers: [number, number, number][] = [[-200, -90, -440], [-165, -300, -640], [-125, -500, -840]];
return <g>
<rect x={-22} y={-110} width={44} height={110} fill={p.c(p.pal.trunk)} />
<rect x={4} y={-110} width={18} height={110} fill={p.lo(p.pal.trunk, 0.4)} />
{tiers.map(([w, b, t], i) => <g key={i}>
<polygon points={`0,${t} ${w},${b} ${-w},${b}`} fill={p.c(leaf)} />
<polygon points={`0,${t} ${-w},${b} ${-w * 0.1},${b}`} fill={p.lo(leaf, 0.42)} />
<polygon points={`0,${t} ${w * 0.55},${b - (b - t) * 0.42} ${w * 0.25},${b - (b - t) * 0.4}`} fill={p.hi(leaf, 0.2)} />
<path d={`M${w} ${b} L${-w} ${b} L${-w * 0.92} ${b - 18} L${w * 0.92} ${b - 18} Z`} fill={p.lo(leaf, 0.55)} />
</g>)}
</g>;
},
deadtree: (p, color) => {
const bark = color ?? p.pal.trunk;
return <g strokeLinecap="round" fill="none">
<g stroke={p.c(bark)}>
<path d="M0 0 L0 -440" strokeWidth={52} />
<path d="M0 -240 L-140 -400 M-80 -320 L-160 -300 M0 -340 L120 -500 M60 -420 L160 -430 M0 -440 L-40 -560" strokeWidth={24} />
</g>
<g stroke={p.lo(bark, 0.45)}>
<path d="M14 0 L14 -430" strokeWidth={18} />
<path d="M8 -346 L124 -496" strokeWidth={9} />
</g>
<path d="M-30 0 Q-60 4 -80 0 M30 0 Q60 4 84 0" stroke={p.c(bark)} strokeWidth={20} />
</g>;
},
bush: (p, color) => <Foliage blobs={jitter(p, [[-90, -70, 85], [15, -105, 105], [115, -66, 80], [-165, -42, 56], [180, -38, 52], [40, -50, 70]], 0.6)} color={color ?? p.pal.leaf} p={p} />,
rock: (p, color) => {
const s = color ?? p.pal.stone;
return <g>
<path d="M-120 0 Q-138 -84 -52 -118 Q34 -150 104 -84 Q146 -34 120 0 Z" fill={p.c(s)} />
<path d="M30 -134 Q96 -116 114 -66 Q140 -30 120 0 L6 0 Q44 -64 30 -134 Z" fill={p.lo(s, 0.38)} />
<path d="M-106 -40 Q-110 -98 -44 -116 Q-16 -124 6 -122 Q-44 -100 -66 -40 Z" fill={p.hi(s, 0.25)} />
</g>;
},
mountain: (p, color) => {
const m = color ?? p.pal.far;
return <g>
<polygon points="-520,0 -60,-470 0,-520 70,-460 520,0" fill={p.c(m)} />
<polygon points="0,-520 70,-460 520,0 80,0 150,-140 40,-260 60,-380" fill={p.lo(m, 0.3)} />
<polygon points="-60,-470 0,-520 -40,-400 -140,-250 -260,-150 -150,-300" fill={p.hi(m, 0.12)} />
<polygon points="-110,-410 -60,-470 0,-520 70,-460 110,-410 50,-432 10,-396 -40,-436" fill={p.c("#ffffff")} opacity={0.85} />
<polygon points="0,-520 70,-460 110,-410 50,-432 22,-410" fill={p.lo("#e8ecf4", 0.3)} opacity={0.85} />
</g>;
},
cloud: (p, color) => {
const base = color ?? mix("#ffffff", p.pal.light, 0.12);
return <g opacity={0.95}>
<Foliage blobs={[[-80, -50, 52], [0, -78, 66], [78, -52, 50], [-140, -34, 34], [140, -32, 32]]} color={base} p={p} shadeK={0.2} hiK={0} lift={0.22} />
<rect x={-174} y={-34} width={348} height={34} rx={17} fill={p.lo(base, 0.22)} />
</g>;
},
palm: (p, color) => {
const leaf = color ?? p.pal.leaf;
const bark = mix(p.pal.trunk, "#b08a5a", 0.35);
const fronds: [number, number][] = [[-250, -470], [-210, -600], [-40, -700], [150, -650], [270, -500], [60, -560]];
return <g>
<path d="M-22 0 Q-40 -260 20 -560 L52 -556 Q2 -260 26 0 Z" fill={p.c(bark)} />
<path d="M8 0 Q-6 -260 40 -558 L52 -556 Q2 -260 26 0 Z" fill={p.lo(bark, 0.4)} />
{Array.from({ length: 9 }, (_, i) => {
const y = -40 - i * 58;
const x = -14 + (i / 9) * 40 - Math.sin((i / 9) * 2) * 10;
return <path key={i} d={`M${x - 20} ${y} Q${x + 4} ${y + 10} ${x + 30} ${y}`} stroke={p.lo(bark, 0.5)} strokeWidth={6} fill="none" strokeLinecap="round" />;
})}
{fronds.map(([x, y], i) => {
const ox = 36;
const oy = -560;
const mx = (ox + x) / 2;
const my = Math.min(oy, y) - 70;
return <g key={i}>
<path d={`M${ox} ${oy} Q${mx} ${my - 34} ${x} ${y} Q${mx} ${my + 44} ${ox} ${oy} Z`} fill={p.c(leaf)} />
<path d={`M${ox} ${oy} Q${mx} ${my + 6} ${x} ${y} Q${mx} ${my + 44} ${ox} ${oy} Z`} fill={p.lo(leaf, 0.42)} />
</g>;
})}
<circle cx={24} cy={-540} r={20} fill={p.c("#6a4a2a")} /><circle cx={52} cy={-532} r={18} fill={p.lo("#6a4a2a", 0.3)} />
</g>;
},
outcrop: (p, color) => {
const s = color ?? mix(p.pal.stone, p.pal.ground.dirt, 0.5);
return <g>
<path d="M-330 0 Q-300 -70 -160 -96 Q0 -116 170 -94 Q310 -70 330 0 Z" fill={p.c(s)} />
<path d="M60 -110 Q200 -96 290 -60 Q320 -36 330 0 L40 0 Q110 -50 60 -110 Z" fill={p.lo(s, 0.32)} />
{[-30, -56, -78].map((y, i) => <path key={y} d={`M${-300 + i * 40} ${y} Q0 ${y - 22} ${300 - i * 40} ${y}`} stroke={p.lo(s, 0.5)} strokeWidth={5} fill="none" />)}
<path d="M-330 0 Q-300 -70 -160 -96 L-150 -80 Q-280 -50 -300 0 Z" fill={p.hi(s, 0.3)} />
</g>;
},
rainbow: () => {
const bands = ["#e8463d", "#f28c28", "#f2c230", "#5cc48a", "#4fb0e8", "#7a5ce0"];
return <g fill="none" opacity={0.78}>{bands.map((c, i) => <path key={c} d={`M${-600 + i * 26} 0 A${600 - i * 26} ${600 - i * 26} 0 0 1 ${600 - i * 26} 0`} stroke={c} strokeWidth={27} />)}</g>;
},
waves: (p, color) => {
const water = color ?? p.pal.ground.water;
const d = Array.from({ length: 7 }, (_, i) => `Q${-300 + i * 100 + 50} -70 ${-300 + (i + 1) * 100} 0`).join(" ");
return <g>
<path d={`M-300 0 ${d} L400 40 L-300 40 Z`} fill={p.lo(water, 0.3)} />
<path d={`M-300 6 ${d} L400 12 L-300 12 Z`} fill={p.c(water)} opacity={0.7} />
<path d={`M-300 0 ${d}`} stroke={p.hi("#ffffff", 0)} strokeWidth={9} fill="none" opacity={0.75} strokeLinecap="round" />
</g>;
},
};
+88
View File
@@ -0,0 +1,88 @@
// Tinta do cenário: paletas, mistura de cor e o "pincel" de cada peça. Toda peça pinta em 2 tons (cel): a cor
// base e o lado da sombra, num tom mais escuro e frio da própria cor (nunca contorno preto). A luz vem da
// ESQUERDA em todas as peças. A distância (z) puxa a cor para a do céu/parede (perspectiva atmosférica) e a
// frente fica um pouco mais escura e contrastada — tudo por mistura de cor, sem filtro (render barato).
export const PALETTES = ["night", "sepia", "day", "dusk", "gray"] as const;
export type PaletteId = (typeof PALETTES)[number];
export type Pal = {
/** Céu: topo, meio e perto do horizonte. */
sky: [string, string, string];
wall: string;
ground: Record<string, string>;
far: string; near: string; ink: string; leaf: string; trunk: string; stone: string;
/** Cor da luz (lado iluminado, lâmpada, sol). */
light: string;
/** Cor fria para onde as sombras puxam. */
shade: string;
/** Sol/lua: cor do disco e do halo. */
sun: string; halo: string;
/** Contraluz: quanto toda peça escurece para o frio (entardecer = sol baixo atrás das coisas). */
dim?: number;
};
const P: Record<PaletteId, Pal> = {
night: { sky: ["#070a1c", "#141a3e", "#2a3264"], wall: "#25304f", far: "#2c3463", near: "#3d4a7c", ink: "#0c0d1a", leaf: "#2a4a5a", trunk: "#3a2e40",
stone: "#5a6088", light: "#ffc965", shade: "#05081c", sun: "#f4ecc8", halo: "#8a9ad8",
ground: { grass: "#22384a", street: "#232842", dirt: "#33304a", floor: "#2a2e48", sand: "#4a4868", water: "#16305a" } },
sepia: { sky: ["#b8956a", "#dcc196", "#f0dfb8"], wall: "#6e6248", far: "#b49a74", near: "#7a5e46", ink: "#2a2018", leaf: "#7f8048", trunk: "#5a4330",
stone: "#a39a8a", light: "#ffdc8e", shade: "#2c2a3a", sun: "#fff0c0", halo: "#ffd890",
ground: { grass: "#8f8c54", street: "#76685a", dirt: "#8a6a48", floor: "#7a5e44", sand: "#d8bd8a", water: "#6f8a8a" } },
day: { sky: ["#3f8fd8", "#7fbdec", "#d4ecf8"], wall: "#e6d6b6", far: "#a6c8de", near: "#e09a68", ink: "#22252e", leaf: "#5aa84a", trunk: "#7a5232",
stone: "#a9adb5", light: "#fff2be", shade: "#2a3a78", sun: "#fff8d8", halo: "#fff2b0",
ground: { grass: "#7cc25e", street: "#8a8f99", dirt: "#c49060", floor: "#c69c6c", sand: "#f0d79a", water: "#3f9ad8" } },
dusk: { sky: ["#5c5a9a", "#e49a72", "#f8d08a"], wall: "#5a4658", far: "#b48a98", near: "#c98a6a", ink: "#20141c", leaf: "#6a8540", trunk: "#5e3a2a",
stone: "#9a8a92", light: "#ffcf86", shade: "#3a2a62", sun: "#ffe7a8", halo: "#ffc070", dim: 0.12,
ground: { grass: "#6e8448", street: "#6a5a64", dirt: "#c27a4c", floor: "#6e5048", sand: "#dba878", water: "#5a6aa0" } },
gray: { sky: ["#5f6670", "#8d949c", "#c0c4c8"], wall: "#565b63", far: "#8f969e", near: "#646a72", ink: "#1b1d21", leaf: "#5a6b55", trunk: "#4a4038",
stone: "#9aa0a8", light: "#f2e6c8", shade: "#1e2430", sun: "#e8e8e0", halo: "#c8ccd0",
ground: { grass: "#5f6e55", street: "#4a4f57", dirt: "#5e5246", floor: "#4a4d54", sand: "#a8a08a", water: "#5a6f80" } },
};
export const palette = (id: PaletteId | undefined): Pal => P[id ?? "night"] ?? P.night;
/** Mistura duas cores hex (#rrggbb) em k (0 = a, 1 = b). */
export function mix(a: string, b: string, k: number): string {
const pa = parseInt(a.slice(1, 7), 16);
const pb = parseInt(b.slice(1, 7), 16);
const q = Math.max(0, Math.min(1, k));
const ch = (s: number) => Math.round(((pa >> s) & 255) * (1 - q) + ((pb >> s) & 255) * q);
return `#${[16, 8, 0].map((s) => ch(s).toString(16).padStart(2, "0")).join("")}`;
}
/** Pincel de uma peça: já sabe a profundidade, a paleta e o sorteio da semente. */
export type Paint = {
pal: Pal;
r: () => number;
indoor: boolean;
night: boolean;
/** Cor base (com a névoa da distância). */
c: (hex: string) => string;
/** Lado da sombra: mais escuro e frio (k = quanto). */
lo: (hex: string, k?: number) => string;
/** Lado da luz: mais claro e quente. */
hi: (hex: string, k?: number) => string;
};
/**
* `haze` = quanto a peça puxa para a cor do fundo (0–1); `front` = quanto escurece por estar na frente (0–0,2).
* Os resultados ficam em cache por peça: o mesmo hex sai sempre igual.
*/
export function makePaint(pal: Pal, r: () => number, opts: { haze: number; hazeColor: string; front: number; indoor: boolean; night: boolean }): Paint {
const cache = new Map<string, string>();
const base = (hex: string) => {
const hit = cache.get(hex);
if (hit) return hit;
let v = pal.dim ? mix(hex, pal.shade, pal.dim) : hex;
if (opts.front > 0) v = mix(v, pal.ink, opts.front);
if (opts.haze > 0) v = mix(v, opts.hazeColor, opts.haze);
cache.set(hex, v);
return v;
};
return {
pal, r, indoor: opts.indoor, night: opts.night,
c: base,
lo: (hex, k = 0.3) => base(mix(hex, pal.shade, k)),
hi: (hex, k = 0.2) => base(mix(hex, pal.light, k)),
};
}
+392
View File
@@ -0,0 +1,392 @@
// Biblioteca de MÃOS desenhadas no estilo de ilustração cartoon de referência (quadro canônico 120×120):
// - Proporções cheias, compactas e arredondadas (como em referencia/recortes/joinha.png, maos-segurando.png,
// mao-prancheta.png e apontando.png): sem dedos compridos em salsicha;
// - Base do pulso cilíndrica arredondada centrada em `wrist` (emenda perfeita com o antebraço ou punho da manga);
// - Sulcos quentes e curtos entre os dedos dobrados, e sombreado cel limpo em 2 tons acompanhando o volume;
// - Camadas `back` (atrás do objeto) e `front` (dedos/polegar na frente do objeto) para que qualquer objeto seguro
// fique claramente DENTRO da mão.
import React from "react";
import type { IconId } from "./spec";
export const HAND_SHAPES = [
"relaxed",
"open",
"point",
"thumbs_up",
"grip",
"pinch_edge",
"pinch_low",
"fist",
"on_face",
"think",
"crossed",
] as const;
export type HandShape = (typeof HAND_SHAPES)[number];
type ShapeDef = {
/** Silhueta principal (camada de trás quando `bodyBehind` é true). */
body: string;
/** Sombra cel em crescente macio (recortada pela silhueta `body`). */
shadow: string;
/** Linhas internas quentes: separação dos dedos, nós e dobras da palma. */
lines: string;
/** Peça por cima (polegar ou dedos que abraçam o objeto pela frente), com sombra e linhas próprias. */
over?: { body: string; shadow?: string; lines?: string };
/** Unhas discretas (só quando a vista pede): [cx, cy, rx, ry, giro]. */
nails?: [number, number, number, number, number][];
overNails?: [number, number, number, number, number][];
/** Pulso no quadro (centro da junta redonda onde termina o antebraço). */
wrist: [number, number];
/** Ângulo do antebraço para o qual a forma foi desenhada (0 = descendo; formas alinhadas = 0). */
wristDeg: number;
upright: boolean;
/** Com objeto: `body` fica ATRÁS do objeto e `over` fica NA FRENTE dele (objeto dentro da mão). */
bodyBehind?: boolean;
/** Ponto onde passa o cabo (`grip`) ou encosta a borda (`pinch_edge`/`pinch_low`). */
hold?: [number, number];
};
// Base redonda no pulso (centro (60, 0), raio ~13.5): garante emenda contínua em qualquer rotação.
const WRIST_CAP = "M46.5 0 A13.5 11 0 0 1 73.5 0";
const SHAPES: Record<HandShape, ShapeDef> = {
// Caída ao lado do corpo: formas arredondadas e carnudas, polegar voltado para dentro, dedos juntos curvando suavemente.
relaxed: {
body: `${WRIST_CAP}`
+ " C76 8 82.5 18 84 31 C85.2 43 84.4 55 82 65 C80.8 70.5 77.8 73.5 74.5 73 C72.2 72.6 70.8 70.5 70.4 67.5"
+ " C69.8 74 68 79 64.2 79.6 C60.8 80.2 58.6 77.5 58.2 73"
+ " C57.4 78.5 55.2 82 51.2 82 C47.5 82 45.4 78.5 45.2 73.5"
+ " C44.2 76.5 42 78 39.2 77.4 C35.8 76.6 34.2 72.5 34.8 66 C35.5 57 37.2 48 39 41"
+ " C37 46.5 35 51.5 32.2 54 C29 56.8 25 55.5 24.2 51 C23.2 45.8 25.5 37.5 29.5 29.5"
+ " C34 21 41 13.5 45 5.5 C46 3.5 46.5 1.8 46.5 0 Z",
shadow: "M66 -10 C69 5 75.5 16 78 30 C79.8 43 78.8 56 76 67 C72.5 75 62 80 44 78 L44 90 L92 90 L92 -10 Z",
lines: "M39 41 C40.8 35 41.5 28.5 40.5 22.5 M45.2 73.5 C45.8 65.5 46.8 58 48.2 52 M58.2 73 C58.8 65 59.5 57.5 60.2 51.5 M70.4 67.5 C71 61 71.6 55 72 50",
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Mão aberta (acenando / comemorando): palma carnuda, dedos abrindo em leque macio que afinam na ponta, polegar na base.
open: {
body: `${WRIST_CAP}`
+ " C75.5 7 81.5 16 83.8 28 C85 35 86 43 88 51.5 C89.2 56.8 88 61.2 84.8 62.2 C81.5 63.2 78.6 60.4 76.6 55"
+ " C74.8 50.2 73.2 45.2 71.8 41.2 C73 50 74.2 60.5 74.6 68.8 C74.9 74.6 72.2 78.2 68.4 78.2 C64.8 78.2 62.6 74.8 62.2 69"
+ " C61.8 60.5 61.2 51.5 60.8 44 C60.5 54 60.2 65.5 59.6 74.2 C59.2 80.4 56.2 83.6 52.2 83.4 C48.4 83.2 46.2 79.6 46.2 73.5"
+ " C46.2 64.5 46.8 54 47.5 44.5 C46 52.5 44.5 61.5 43.5 68.5 C42.6 74 39.6 76.8 36 76.2 C32.4 75.5 30.8 72 31.5 66.2"
+ " C32.8 56 35.2 44.5 37.5 35 C33.5 38.8 29.2 42.8 25 45.5 C20.8 48.2 16.4 47 15.2 43 C14 39 16.5 34 21.2 30.2"
+ " C27.2 25.4 34.8 20.8 40.2 14.5 C43.8 10.2 46 5 46.5 0 Z",
shadow: "M67 -10 C70 5 77 16 80 30 C82 40 83.5 50 86 60 L96 60 L96 -10 Z"
+ " M46 28 C53 33.5 63 35.5 72 32 C68 38.5 57 40.5 47 35.5 Z",
lines: "M43 37 C53 34 64.5 34.5 73.5 38.5 M38.5 34 C42.8 28 46 21 47 14",
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Apontando (como em referencia/recortes/apontando.png):
// Polegar redondo na lateral interna (esquerda), indicador comprido subindo firme ao lado dele,
// e os 3 outros dedos (médio, anelar, mínimo) dobrados em escada arredondada macia na direita.
point: {
body: `${WRIST_CAP}`
+ " C76 8 82.5 18 84.5 30 C86 39 86.5 48 84 55.5 C82 61 77.2 63.5 72.5 61.5"
+ " C71 66.8 66.2 69.8 60.8 68.6 C58 68 55.8 66 54.6 63.5"
+ " C53 67.5 51 69.5 48.8 69.5 C48.8 79.5 48.8 90.5 48.4 98.5"
+ " C48 105.5 44.2 109.2 39.4 109 C34.6 108.8 31.4 104.6 31.8 97.5"
+ " C32.4 85 33.8 69.5 35 55.5 C29 51.5 25 44.5 25.8 36.2 C26.6 28 32.2 21 38.8 15.2"
+ " C43.2 11 45.8 5.2 46.5 0 Z",
shadow: "M65 -10 C68.5 5 76 15 79 29 C81 39 80.5 49 78 56 C73 60.5 63 64.5 50 65.5 L50 75 L93 75 L93 -10 Z"
+ " M42.8 58 C44.2 72 44.2 88 43.2 109 L49.5 109 L49.5 58 Z",
lines: "M50.5 68.5 C50.8 60.5 51.6 53 53.5 47.5 M61.8 68 C62.4 60 63.2 53 64.8 47.5 M72.5 61.5 C73.2 55 74 49 75.2 44.5"
+ " M49 48.5 C57.5 46 67.5 44.5 78 43",
over: {
body: "M25.8 36.2 C26.6 27.5 33.8 21 41.2 24.2 C47 26.8 52.2 34.5 55.5 42.2 C58.5 49 57.5 56.5 52.2 58.8 C47 61.2 39.2 57.8 33.2 51.5 C27.8 45.8 25.2 41.2 25.8 36.2 Z",
shadow: "M28.5 43.5 C33.8 50.8 42.2 56.5 50.5 58 L47.5 62 L26.5 48.5 Z",
lines: "M35 27.5 C41.2 32.5 48 39.5 52.5 46.5",
},
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Joinha (proporção compacta e redonda idêntica a referencia/recortes/joinha.png):
// Punho cheio e arredondado (largura ~52, altura ~56 na palma), 4 dedos gordinhos empilhados com sulcos curtos,
// e polegar forte subindo na vertical do topo da palma.
thumbs_up: {
body: "M74 88 A13.5 13.5 0 0 0 90 66"
+ " C87 57 82 49 75 43"
+ " C75.5 32 75 19 73 10.5 C71.2 3.5 66.5 0 60.5 0.5 C54.8 1 51.2 6 51 14.5"
+ " C50.8 23.5 51.2 32.5 50 39 C41 38.5 33 40 29.5 45.5 C26.2 50.6 27.8 57 33 58.8"
+ " C27.2 61.2 26.8 68.8 32.2 71.6 C28.2 74.4 28.8 81.8 34 84"
+ " C31.8 87.5 34.2 93.8 41 95 C51 96.8 63 96 70.5 91.5 C72.5 90.2 73.5 89 74 88 Z",
shadow: "M67 2 C70.8 10 72 25 72 41 C78.5 46 84 55 87 65 L92 74 L74 92 L34 97 L30 89"
+ " C44 93.5 59 93 68.5 88.5 C75.5 85 78.5 76 77 65 C75.5 54 72 46.5 66 42.5 L66 2 Z"
+ " M31.5 57.2 C40.5 59.8 50.5 60 59 58.5 L59 61.2 C49.5 62.6 40.5 62.2 31 59.8 Z"
+ " M31 70 C40 72.6 50.5 72.8 59 71.2 L59 74 C49.5 75.4 40 75 30.5 72.6 Z"
+ " M33 82.4 C41.5 84.8 50 85 57.5 83.8 L57.5 86.5 C49 87.6 41.5 87.2 32.5 85 Z",
lines: "M33 58.8 C41 60.8 50 61 58 59.5 M32.2 71.6 C40.5 73.6 50 73.8 58 72.2 M34 84 C41.8 85.8 49.5 86 56.5 84.8"
+ " M51 36.5 C56.5 39.8 64.5 40.2 71.5 37.5",
wrist: [82, 76], wristDeg: 135, upright: true,
},
// Punho segurando um cabo ou prancheta (proporção compacta e redonda idêntica a referencia/recortes/mao-prancheta.png):
// - `body` (atrás do cabo): base da palma;
// - `over` (na frente do cabo): mão redonda e carnuda com 4 dedos roliços empilhados e 3 sulcos curtos.
grip: {
body: "M88 77 A13.5 13.5 0 0 0 88 50"
+ " C81 44 71 40 59 40 C47 40 37 43 33.5 51 C30 59 31 73 36 83"
+ " C41 91 54 93 67 90 C77 87.5 84 83 88 77 Z",
shadow: "M76 44 C83 52 86 64 83 75 C80 84 72 90 60 92 L92 92 L92 44 Z",
lines: "",
over: {
body: "M86 48 C79 38 66 33.5 53 34 C41 34.5 33 38 30.5 44.5 C28.5 49.5 30.2 53.5 34.5 55.2"
+ " C28 57 26 63 29.5 68 C31 70 33 71 35.5 71.6"
+ " C29.5 73.8 29 80.5 34 83.5 C32 86.8 34.2 92.5 41 93.8"
+ " C51.5 95.8 65 95 75 90.5 C83 87 88 81 89.5 74 C91 66 90 55 86 48 Z",
shadow: "M76 41 C84 49 87.5 61 85 73 C82 83 73.5 90 61.5 92.5 C49.5 95 39 94 32 90.5 L32 97 L92 97 L92 41 Z"
+ " M33.5 53.8 C42 56.2 52.5 56.2 61 54.5 L61 57.2 C52 59 41.5 58.8 32.5 56.2 Z"
+ " M33.8 70.2 C42 72.5 52 72.8 60 71.2 L60 74 C51 75.5 41 75 32.8 72.8 Z"
+ " M33.5 82.2 C41.5 84.5 51 84.8 58.5 83.5 L58.5 86.2 C50 87.5 40.5 87.2 32.5 84.8 Z",
lines: "M34.5 55.2 C43 57.2 53 57 60.5 55.2 M35.5 71.6 C43.5 73.6 52.5 73.8 59.5 72.2 M34 83.5 C42 85.5 50.5 85.8 57.5 84.5",
},
wrist: [86, 64], wristDeg: 45, upright: true, bodyBehind: true, hold: [44, 65],
},
// Segurando a borda lateral de um objeto largo (proporção redonda e compacta idêntica a referencia/recortes/maos-segurando.png):
// - `body` (atrás): palma arredondada que apoia por trás do objeto;
// - `over` (na frente da borda): mão redonda e gordinha (`largura ~50, altura ~58`) com 4 dedos roliços e 3 sulcos curtos!
pinch_edge: {
body: "M88 73 A13.5 13.5 0 0 0 88 46"
+ " C81 39 70 35 59 36 C47 37 40 44 40 58 C40 72 45 83 54 88"
+ " C63 93 75 91 83 83 C86 79.5 87.5 76 88 73 Z",
shadow: "M76 40 C83 48 86 60 83.5 72 C81 82 73 88 61 90 L92 92 L92 40 Z",
lines: "",
over: {
body: "M85 44 C77 34 63 30 49 31.5 C37.5 32.8 30.5 38.5 32.5 45.8"
+ " C26.8 48 25 55.2 30 59.5 C25 62.2 24.8 70 30.5 73.5"
+ " C27.2 77.2 29.2 84.5 36 87 C46 90.5 60 91 72 87"
+ " C80.5 84 86.5 78 88.2 70.5 C90 62 89 51 85 44 Z",
shadow: "M75 38 C83 47 86.5 59.5 84 71.5 C81.5 81.5 73 87.5 60.5 89 C47.5 90.5 37 88 31.5 83.5 L31.5 93 L92 93 L92 38 Z"
+ " M32 44.5 C40.5 47.2 50.5 47.5 58.5 46 L58.5 48.8 C49.5 50.2 39.5 50 31 47.2 Z"
+ " M29.5 58.2 C38 61 48 61.2 56 59.8 L56 62.5 C47 64 37 63.8 28.5 61 Z"
+ " M30 72.2 C38.5 74.8 48 75 55.5 73.6 L55.5 76.4 C46.5 77.8 37.5 77.5 29 75 Z",
lines: "M32.5 45.8 C41 48 50.5 48.2 58 46.8 M30 59.5 C38.5 61.8 48 62 55.5 60.5 M30.5 73.5 C38.8 75.8 47.8 76 54.8 74.6",
},
wrist: [85, 60], wristDeg: 62, upright: true, bodyBehind: true, hold: [44, 60],
},
// Pegada de borda com o antebraço vindo de baixo (HandsInsert): dedos atrás da página e polegar comprido + palma na frente.
pinch_low: {
body: "M84 106 A14 14 0 0 0 104 86"
+ " C99 76 95 64 92 52 C89 39 81 28 69 26 C59 24.5 52 30 51 40"
+ " C49.5 55 50 72 54 84 C58 93 69 98 84 106 Z",
shadow: "M78 28 C88 39 92 55 95 70 C97 80 100 86 105 92 L112 104 L76 108 L54 90 C66 93 78 90 83 80 C88 68 85 45 78 28 Z",
lines: "M52 44 C59 44.5 66.5 46.5 72.5 50 M51.5 58 C58.5 58.8 65.5 60.8 71.5 64 M52.5 72 C58.5 72.8 64.5 74.8 69.5 78",
over: {
body: "M84 106 A14 14 0 0 0 104 86"
+ " C98 76 91 64 82 54 C72 44 56 34 45 30.5 C36.5 27.8 30.5 32.5 33 40"
+ " C35.5 47.5 45 54.5 55 61 C61 65 65 73 68 84 C71 94 77 101 84 106 Z",
shadow: "M34 41 C42 49 52 56 60 62 C65 68 68 78 72 90 L98 106 L82 110 L62 92 L32 46 Z",
lines: "M56 61 C62 64 67 69 70 76",
},
wrist: [94, 96], wristDeg: 135, upright: true, bodyBehind: true, hold: [56, 52],
},
// Punho fechado: 4 dedos dobrados em arco macio, polegar travando por cima do indicador e do médio.
fist: {
body: `${WRIST_CAP}`
+ " C75.5 8 81 18 82.8 30 C84.2 40 84.2 50 81.5 56.5 C79.2 61.5 75.2 63.2 71.5 61.8"
+ " C69.8 66.2 65.5 68.5 60.8 67.6 C58.2 67 56.2 65.2 55 62.8"
+ " C53.2 66.8 48.8 68.8 44.2 67.6 C39.5 66.4 36.2 62.2 35 55.5"
+ " C33.2 46 33.5 35 36.5 25.5 C39.5 16.5 44 9 46.2 2.5 C46.4 1.5 46.5 0.8 46.5 0 Z",
shadow: "M65 -10 C68 5 75 15 78 29 C80 40 79 50 75 57 C68 63 54 66 38 62 L38 74 L92 74 L92 -10 Z",
lines: "M46 67 C46.2 59.5 47 52.5 48.8 47 M60.8 67.6 C61.2 60 61.8 53 63.4 47.5 M71.5 61.8 C72 55.5 72.6 49.5 73.8 45"
+ " M42 48.5 C53 45.8 65 44.5 76.5 43.2",
over: {
body: "M35.5 28 C41 34 49 41 55.5 46.5 C60.2 50.5 61 56.8 56.5 59.8 C52 62.8 44.8 60 39.5 54.2 C34.5 48.8 32.5 39.5 35.5 28 Z",
shadow: "M35 44 C39.5 51 46.5 56.5 54 58.5 L50 62.5 L33 50 Z",
},
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Mão no rosto (tapar a boca / facepalm): palma arredondada e macia, dedos unidos em concha com sulcos curtos nas pontas.
on_face: {
body: `${WRIST_CAP}`
+ " C75 8 80 18 81.5 30 C82.8 41 82.4 55 80.5 67 C79.5 73 76.8 76 73.5 75.5 C71.5 75.2 70.2 73.5 69.8 71"
+ " C69.2 76.5 67.2 81.5 63.2 82 C59.8 82.4 58 80 57.6 76.5"
+ " C57 81.5 54.6 85 50.6 85 C46.8 85 44.8 81.5 44.6 76.5"
+ " C43.8 79.8 41.4 81.8 38.2 81.2 C34.8 80.5 33 76.5 33.6 69.5 C34.5 58 36.2 46.5 38 38"
+ " C35.5 42.5 33 46.5 30 48.5 C26.8 50.5 23.2 49 22.6 45 C22 40 24.8 32.5 29.5 25.5"
+ " C34.5 18 41.8 11 45.2 4 C46 2.5 46.5 1.2 46.5 0 Z",
shadow: "M65 -10 C68 5 74.5 16 77 30 C78.5 43 78 58 75.5 71 C72.5 79 61 84 44 83 L44 92 L90 92 L90 -10 Z",
lines: "M38 38 C39.8 32.5 40.6 27 40 21 M44.6 76.5 C45 69.5 45.8 63 46.8 57.5 M57.6 76.5 C58 69.5 58.4 63 59 57.5 M69.8 71 C70.2 65 70.6 59.5 71 55",
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Mão pensando (apoiada no queixo): punho macio sob o queixo com o indicador estendido na bochecha/queixo
// e os outros 3 dedos dobrados em gomos arredondados (sem aspecto de garfo ou bloco).
think: {
body: `${WRIST_CAP}`
+ " C75.5 8 81.5 18 83.2 30 C84.5 40 84 50 81 57 C78.5 62.5 73.8 64.5 69.5 62.5"
+ " C67.8 67.2 63 69.5 58 68.2 C55.2 67.5 53.2 65.5 52.2 63"
+ " C50.5 66.5 47.8 68.2 44.8 67.5 C44.5 75 44 83.5 43 90"
+ " C42 96.2 38.2 99.5 33.8 98.8 C29.4 98 26.8 93.8 27.6 87"
+ " C29 75.5 31.2 61 33.5 48 C29.5 50.5 25 51.5 21.5 49.5 C17.8 47.5 16.5 42.5 18.8 37.5"
+ " C21.5 31.5 28 25.5 34.5 19.5 C40.5 14 44.8 7 46.5 0 Z",
shadow: "M65 -10 C68 5 75.5 16 78 30 C80 41 79 50 75 57 C69 63.5 57 66.5 43 65 L43 74 L91 74 L91 -10 Z"
+ " M38 56 C39.5 68 39.5 82 38.5 99 L44.5 99 L45 56 Z",
lines: "M33.5 48 C37.5 43 41 37 42.5 31 M45 66.5 C45.8 59 47 52 48.8 46.5 M58 68.2 C58.8 60.5 59.8 53.5 61.5 47.5 M69.5 62.5 C70.2 56 71 50 72.2 45",
wrist: [60, 0], wristDeg: 0, upright: false,
},
// Mão de braços cruzados apoiada no bíceps oposto (como em referencia/recortes/bracos-cruzados.png):
// 3 dedos roliços e macios pousados diagonalmente sobre o braço.
crossed: {
body: `${WRIST_CAP}`
+ " C74.5 8 79 18 80 29 C81 40 79.5 52 75.8 61.5 C73.2 68 68.5 71 63.8 69.5"
+ " C61.4 75.8 56.2 79.2 50.5 77.6 C47 76.6 44.6 73.6 43.8 69.5"
+ " C41.2 74 36.2 76 31.2 73.8 C26.4 71.6 24.4 66 26.8 59.2"
+ " C30 50 34.8 38.5 39 27.5 C42.2 19 45.4 9.5 46.5 0 Z",
shadow: "M64 -10 C67 5 72.5 16 74 30 C75 42 73.5 53 70 62 C65.5 70 52 75 33 72 L33 82 L88 82 L88 -10 Z",
lines: "M43.8 69.5 C46.5 59.5 49.8 50 53.2 42 M63.8 69.5 C65.8 60 67.8 51 70.2 43.5",
wrist: [60, 0], wristDeg: 0, upright: false,
},
};
/** Objetos seguros com as DUAS mãos (pelas bordas, na frente do peito). O resto vai numa mão só (`grip`). */
export const TWO_HANDED: IconId[] = ["book", "tablet"];
/**
* Como cada objeto entra no punho (`grip`): ponto do cabo no quadro 100×100 do ícone e o giro que deixa o cabo em pé
* (cabeça do martelo, ponta do ramo e da régua para cima) com sobra visível do cabo abaixo da mão.
*/
export const GRIP: Partial<Record<IconId, { x: number; y: number; rot: number }>> = {
hammer: { x: 50, y: 68, rot: 20 },
olive: { x: 36, y: 68, rot: -42 },
ruler: { x: 32, y: 50, rot: -78 },
phone: { x: 50, y: 62, rot: -6 },
fuel: { x: 50, y: 30, rot: 0 },
bulb: { x: 50, y: 74, rot: 0 },
};
/**
* Posição da forma: espelho (`mirror`), giro em graus e escala, a partir do pulso na tela, do ângulo do antebraço e do
* lado do braço. Formas alinhadas giram com o antebraço; as "em pé" acompanham o ângulo para o qual foram desenhadas.
*/
export function handPlacement(shape: HandShape, x: number, y: number, foreDeg: number, s: number, k: number) {
const def = SHAPES[shape];
let mirror: number;
let rot: number;
if (def.upright) {
mirror = s >= 0 ? 1 : -1;
rot = foreDeg - def.wristDeg * mirror;
} else {
const up = Math.cos((foreDeg * Math.PI) / 180) >= 0;
mirror = up ? s : -s;
rot = foreDeg;
}
const [wx, wy] = def.wrist;
const transform = `translate(${x} ${y}) rotate(${rot}) scale(${k * mirror} ${k}) translate(${-wx} ${-wy})`;
const r = (rot * Math.PI) / 180;
/** Ponto do quadro 120×120 → tela. */
const map = (px: number, py: number) => {
const lx = (px - wx) * k * mirror;
const ly = (py - wy) * k;
return { x: x + lx * Math.cos(r) - ly * Math.sin(r), y: y + lx * Math.sin(r) + ly * Math.cos(r) };
};
return { def, mirror, rot, transform, map, hold: def.hold ? map(def.hold[0], def.hold[1]) : null };
}
/** Pulso que põe o ponto `hold` da forma em (hx, hy) — para pôr as mãos nas bordas do objeto. */
export function wristForHold(shape: HandShape, hx: number, hy: number, foreDeg: number, s: number, k: number) {
const p = handPlacement(shape, 0, 0, foreDeg, s, k);
return { x: hx - (p.hold?.x ?? 0), y: hy - (p.hold?.y ?? 0) };
}
function shadeHex(hex: string, k: number): string {
const n = parseInt(hex.slice(1), 16);
const c = (v: number) => Math.max(0, Math.min(255, Math.round(v * k))).toString(16).padStart(2, "0");
return `#${c((n >> 16) & 255)}${c((n >> 8) & 255)}${c(n & 255)}`;
}
/** Mistura duas cores hex (0 = a, 1 = b). */
function mixHex(a: string, b: string, t: number): string {
const pa = parseInt(a.slice(1), 16), pb = parseInt(b.slice(1), 16);
const ch = (sh: number) => Math.round(((pa >> sh) & 255) * (1 - t) + ((pb >> sh) & 255) * t).toString(16).padStart(2, "0");
return `#${ch(16)}${ch(8)}${ch(0)}`;
}
function coolHex(hex: string, k: number): string {
const n = parseInt(hex.slice(1), 16);
const r = ((n >> 16) & 255) * k * 0.96, g = ((n >> 8) & 255) * k * 0.96, b = (n & 255) * k + 6;
const c = (v: number) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, "0");
return `#${c(r)}${c(g)}${c(b)}`;
}
/**
* Desenha a forma de mão no lugar. `layer`: "back" = o que fica atrás do objeto, "front" = o que fica na frente,
* "all" = tudo. `light` = lado da sombra na tela (1 = direita).
*/
export function HandArt({ shape, x, y, foreDeg, s, k, skin, light = 1, layer = "all", uid }: {
shape: HandShape; x: number; y: number; foreDeg: number; s: number; k: number; skin: string; light?: number;
layer?: "all" | "back" | "front"; uid: string;
}) {
const p = handPlacement(shape, x, y, foreDeg, s, k);
const def = p.def;
const rightOnScreen = p.mirror * Math.cos((p.rot * Math.PI) / 180);
const flipShadow = Math.sign(rightOnScreen || 1) !== Math.sign(light || 1);
const shadowT = flipShadow && !def.upright ? "translate(120 0) scale(-1 1)" : undefined;
const creaseColor = shadeHex(skin, 0.76);
const shadowFill = coolHex(skin, 0.86);
const skinLite = mixHex(skin, "#fff6ea", 0.06);
const gradId = `hg${uid}${layer}`;
const lineProps = {
stroke: creaseColor,
strokeWidth: 3.1,
strokeLinecap: "round" as const,
strokeLinejoin: "round" as const,
fill: "none",
opacity: 0.9,
};
const nail = ([cx, cy, rx, ry, a]: [number, number, number, number, number], i: number) => (
<ellipse
key={i}
cx={cx}
cy={cy}
rx={rx}
ry={ry}
transform={`rotate(${a} ${cx} ${cy})`}
fill={mixHex(skin, "#fae5de", 0.38)}
opacity={0.8}
/>
);
const bodyLayer = def.bodyBehind ? "back" : def.hold ? "front" : "all";
const showBody = layer === "all" || layer === bodyLayer || (bodyLayer === "all" && layer === "front");
const showOver = layer !== "back";
return (
<g transform={p.transform}>
<defs>
<linearGradient id={gradId} x1="15%" y1="10%" x2="85%" y2="90%">
<stop offset="0%" stopColor={skinLite} />
<stop offset="100%" stopColor={skin} />
</linearGradient>
<clipPath id={`hb${uid}${layer}`}><path d={def.body} /></clipPath>
{def.over && <clipPath id={`ho${uid}${layer}`}><path d={def.over.body} /></clipPath>}
</defs>
{showBody && (
<>
<path d={def.body} fill={`url(#${gradId})`} />
<g clipPath={`url(#hb${uid}${layer})`}>
<path d={def.shadow} fill={shadowFill} transform={shadowT} opacity={0.88} />
</g>
{def.lines && <path d={def.lines} {...lineProps} />}
{(def.nails ?? []).map(nail)}
</>
)}
{showOver && def.over && (
<>
<path d={def.over.body} fill={`url(#${gradId})`} />
<g clipPath={`url(#ho${uid}${layer})`}>
{def.over.shadow && <path d={def.over.shadow} fill={shadowFill} opacity={0.88} />}
</g>
{def.over.lines && <path d={def.over.lines} {...lineProps} />}
{(def.overNails ?? []).map(nail)}
</>
)}
</g>
);
}
+50
View File
@@ -70,6 +70,56 @@ const DRAW: Record<IconId, React.ReactNode> = {
<circle cx={50} cy={50} r={40} fill="#f4f6ff" /><circle cx={50} cy={50} r={34} fill="#232850" />
<rect x={48} y={24} width={4} height={28} rx={2} fill="#fff" /><rect x={48} y={48} width={22} height={4} rx={2} fill={COLORS.key} />
</>),
// Itens de mão e objetos de história antiga (também servem como objeto solto na cena).
olive: (<>
<path d="M14 94 Q44 62 86 14" stroke="#3d2814" strokeWidth={8.5} fill="none" strokeLinecap="round" />
<path d="M14 94 Q44 62 86 14" stroke="#7d5632" strokeWidth={5.5} fill="none" strokeLinecap="round" />
{[[38, 62, -38], [48, 52, 28], [58, 42, -38], [68, 32, 28], [78, 22, -38], [84, 15, -12]].map(([x, y, r], i) => (
<g key={i} transform={`rotate(${r} ${x} ${y})`}>
<ellipse cx={x} cy={y} rx={13.5} ry={6} fill={i % 2 ? "#557d32" : "#446827"} />
<ellipse cx={x} cy={y - 1} rx={12} ry={4.2} fill={i % 2 ? "#84ab4c" : "#6c943c"} />
<path d={`M${x - 9} ${y} L${x + 9} ${y}`} stroke="#9ec462" strokeWidth={1.2} strokeLinecap="round" opacity={0.7} />
</g>
))}
<circle cx={54} cy={54} r={4.5} fill="#2e2b4a" /><circle cx={52.5} cy={52.5} r={1.5} fill="#76729e" />
<circle cx={72} cy={35} r={4.5} fill="#2e2b4a" /><circle cx={70.5} cy={33.5} r={1.5} fill="#76729e" />
</>),
hammer: (<>
<g transform="rotate(-20 50 64)">
<rect x={42.5} y={28} width={15} height={68} rx={6} fill="#5c381c" />
<rect x={44} y={29} width={12} height={66} rx={5} fill="#9c6638" />
<rect x={45.5} y={30} width={4.5} height={64} rx={2} fill="#b87e4a" opacity={0.75} />
<rect x={42} y={32} width={16} height={6} rx={2} fill="#4a2e16" />
</g>
<g transform="rotate(-20 47 25)">
<rect x={18} y={11} width={58} height={25} rx={5} fill="#4d525e" />
<rect x={19} y={12} width={56} height={22} rx={4} fill="#8f96a3" />
<rect x={21} y={14} width={52} height={8} rx={3} fill="#b4bac6" opacity={0.7} />
<rect x={18} y={11} width={14} height={25} rx={4} fill="#686e7a" />
</g>
</>),
tablet: (<>
<path d="M18 10 Q50 4 82 10 L86 88 Q50 96 14 88 Z" fill="#8f6c4a" />
<path d="M20 12 Q50 6 80 12 L84 86 Q50 93 16 86 Z" fill="#b8916a" />
{Array.from({ length: 7 }, (_, i) => <path key={i} d={`M24 ${22 + i * 10} L76 ${22 + i * 10}`} stroke="#785638" strokeWidth={2.5} strokeDasharray="5 3 2 3" />)}
<path d="M70 70 L86 60 L86 88 L64 92 Z" fill="#000" opacity={0.18} />
</>),
book: (<>
<path d="M6 26 Q28 18 50 28 Q72 18 94 26 L94 86 Q72 78 50 88 Q28 78 6 86 Z" fill="#6b3022" />
<path d="M8 22 Q30 14 50 24 Q70 14 92 22 L92 80 Q70 72 50 82 Q30 72 8 80 Z" fill="#dfd2b5" />
<path d="M9 20 Q30 12 50 22 Q70 12 91 20 L91 77 Q70 69 50 79 Q30 69 9 77 Z" fill="#f5ecd6" />
<path d="M44 20 Q47 21 50 22 Q53 21 56 20 L56 78 Q53 78.5 50 79 Q47 78.5 44 78 Z" fill="#e2d5b8" />
<path d="M50 22 L50 79" stroke="#b9a882" strokeWidth={2.5} />
{[0, 1, 2, 3].map((i) => <g key={i}><path d={`M16 ${32 + i * 10.5} Q29 ${29 + i * 10.5} 43 ${34 + i * 10.5}`} stroke="#9a8a6a" strokeWidth={2.4} fill="none" strokeLinecap="round" /><path d={`M57 ${34 + i * 10.5} Q71 ${29 + i * 10.5} 84 ${32 + i * 10.5}`} stroke="#9a8a6a" strokeWidth={2.4} fill="none" strokeLinecap="round" /></g>)}
</>),
ruler: (<>
<g transform="rotate(-12 50 50)">
<rect x={4} y={36} width={92} height={26} rx={4} fill="#8c6230" />
<rect x={6} y={37} width={88} height={23} rx={3} fill="#e8c374" />
<rect x={8} y={53} width={84} height={6} rx={2} fill="#cfa656" />
{Array.from({ length: 11 }, (_, i) => <rect key={i} x={11 + i * 7.6} y={37} width={2.2} height={i % 2 ? 7 : 12} rx={0.8} fill="#5c3d1b" />)}
</g>
</>),
};
export function Icon({ id }: { id: IconId }) {
+66
View File
@@ -0,0 +1,66 @@
// Profundidade dos braços do personagem de frente para a câmera (função pura do estado do rig, sem React).
//
// O desenho (CharacterFigure.tsx) empilha as camadas assim:
// tronco → braços "side" → acessórios do peito (toalha, cachecol, crachá, apito) → braços "front" →
// parte da toalha apoiada no ombro → cabeça → braços "face".
// Regra: com o personagem de frente, braço e mão NUNCA somem atrás do tronco, da roupa, de acessório ou da barba.
// - "face": a mão sobe até a altura do pescoço/rosto, dentro da largura da cabeça (pensar, tapar a boca, mão na
// testa) — desenhado por cima da cabeça e da barba;
// - "front": a mão ou o antebraço entram na frente do peito (segurar objeto diante do corpo, cruzar os braços,
// apontar para o outro lado, mão na cintura) — por cima do tronco e dos acessórios do peito;
// - "side": o braço fica ao lado do corpo (caído, acenando para fora, apontando para o lado) — por cima do tronco,
// mas por baixo do pano apoiado no ombro/peito (o braço sai por baixo da toalha).
// Não há caso "atrás do tronco": nenhuma pose do rig leva a mão às costas.
import type { BodyParams } from "./rig";
export type ArmLayer = "side" | "front" | "face";
export type Point = { x: number; y: number };
/** Ponta de um segmento: ângulo de tela em graus (0 = para baixo). Igual ao `tip` do desenho. */
export const tipOf = (x: number, y: number, deg: number, len: number): Point => {
const r = (deg * Math.PI) / 180;
return { x: x - Math.sin(r) * len, y: y + Math.cos(r) * len };
};
/** Medidas do desenho (viewBox 200×440) que a regra usa — as mesmas de CharacterFigure.tsx. */
export const ARM = { shoulderX: 54, upper: 56, wrist: 43, hand: 28, torsoHalf: 56 } as const;
/** Ombro, cotovelo, pulso e centro da mão do braço `s` (1 = direita da tela, -1 = esquerda). `w` = largura do corpo. */
export function armGeometry(b: BodyParams, s: 1 | -1, w = 1) {
const hipY = 306 + b.crouch * 56;
const shY = hipY - 100;
const torsoTop = hipY - 114;
const l = s > 0 ? b.armR : b.armL;
const shoulder = { x: 100 + s * ARM.shoulderX * w, y: shY };
const upperDeg = -s * l.raise;
const elbow = tipOf(shoulder.x, shoulder.y, upperDeg, ARM.upper);
const foreDeg = upperDeg + s * l.bend;
const wrist = tipOf(elbow.x, elbow.y, foreDeg, ARM.wrist);
const hand = tipOf(elbow.x, elbow.y, foreDeg, ARM.wrist + ARM.hand);
return { shoulder, elbow, wrist, hand, upperDeg, foreDeg, torsoTop, hipY };
}
/**
* Camada do braço `s` no quadro. `holds` = segura objeto (sempre na frente do corpo, salvo na altura do rosto).
* O "peito" é o tronco sem as faixas laterais onde o braço caído naturalmente encosta.
*/
export function armLayer(b: BodyParams, s: 1 | -1, opts: { holds?: boolean; w?: number } = {}): ArmLayer {
const w = opts.w ?? 1;
const g = armGeometry(b, s, w);
const l = s > 0 ? b.armR : b.armL;
const half = ARM.torsoHalf * w;
// Altura do pescoço/rosto: acima do topo do tronco (+ folga da gola), dentro da largura da cabeça, ou braço dobrado ao queixo/boca.
const atFace = (p: Point) => p.y < g.torsoTop + 20 && Math.abs(p.x - 100) < 60;
if (atFace(g.hand) || atFace(g.wrist) || (l.raise < 20 && l.bend > 138)) return "face";
if (opts.holds) return "front";
// Cotovelo bem dobrado para dentro com o braço baixo (segurar, joinha, mão na cintura, braços cruzados): antebraço na frente.
if (l.raise < 90 && l.bend > 85) return "front";
const chest = { x0: 100 - half + 14, x1: 100 + half - 14, y0: g.torsoTop + 4, y1: g.hipY + 12 };
const inChest = (p: Point) => p.x > chest.x0 && p.x < chest.x1 && p.y > chest.y0 && p.y < chest.y1;
// Amostra o antebraço (cotovelo → mão): basta um trecho na frente do peito.
for (let i = 0; i <= 8; i++) {
const k = i / 8;
if (inChest({ x: g.elbow.x + (g.hand.x - g.elbow.x) * k, y: g.elbow.y + (g.hand.y - g.elbow.y) * k })) return "front";
}
return "side";
}
+87
View File
@@ -0,0 +1,87 @@
// Boca acompanhando a fala SEM perder a expressão. O formato vem das letras da palavra que está sendo dita
// (tempos de cada palavra da transcrição): "a" abre, "e/i" esticam, "o/u" arredondam, "m/b/p" fecham, "f/v"
// mostram os dentes; vogal dura mais que consoante e as letras vizinhas se misturam (coarticulação). Se houver
// o volume do áudio quadro a quadro (`env`), ele fecha a boca nas pausas e abre mais nas sílabas fortes.
// A expressão continua por cima: os cantos (sorriso/tristeza), as sobrancelhas e os olhos são dela.
import type { FaceParams } from "./rig";
export type Viseme = { open: number; wide: number; round: number; teeth: boolean };
export type SpokenWord = { text: string; startS: number; endS: number };
const CLOSED: Viseme = { open: 0, wide: 0, round: 0, teeth: false };
const V: Record<string, Viseme> = {
a: { open: 0.85, wide: 0.3, round: 0, teeth: false },
e: { open: 0.55, wide: 0.65, round: 0, teeth: true },
i: { open: 0.3, wide: 0.95, round: 0, teeth: true },
o: { open: 0.65, wide: 0, round: 0.75, teeth: false },
u: { open: 0.35, wide: 0, round: 1, teeth: false },
mbp: { open: 0, wide: 0.1, round: 0, teeth: false },
fv: { open: 0.12, wide: 0.2, round: 0, teeth: true },
cons: { open: 0.3, wide: 0.3, round: 0, teeth: true },
};
function visemeOf(ch: string): Viseme {
if ("aáàâã".includes(ch)) return V.a;
if ("eéê".includes(ch)) return V.e;
if ("iíy".includes(ch)) return V.i;
if ("oóôõ".includes(ch)) return V.o;
if ("uúü".includes(ch)) return V.u;
if ("mbp".includes(ch)) return V.mbp;
if ("fv".includes(ch)) return V.fv;
return V.cons;
}
const isVowel = (ch: string) => /[aáàâãeéêiíyoóôõuúü]/.test(ch);
function mix(a: Viseme, b: Viseme, k: number): Viseme {
return { open: a.open + (b.open - a.open) * k, wide: a.wide + (b.wide - a.wide) * k, round: a.round + (b.round - a.round) * k, teeth: k < 0.5 ? a.teeth : b.teeth };
}
/** Formato da boca no instante `t` (segundos do trecho) para as palavras dadas; fechada fora das palavras. */
export function visemeAt(words: SpokenWord[], t: number, env?: { values: number[]; fps: number }): Viseme {
const w = words.find((x) => t >= x.startS && t < x.endS);
if (!w) {
// Fim de palavra: fecha em ~60 ms em vez de bater a boca.
const prev = [...words].reverse().find((x) => x.endS <= t);
return prev && t - prev.endS < 0.06 ? mix(V.cons, CLOSED, (t - prev.endS) / 0.06) : CLOSED;
}
const letters = [...w.text.toLowerCase().replace(/(ch|lh|nh|qu)/g, "c").replace(/[^a-záàâãéêíóôõúüçy]/g, "")];
if (!letters.length) return CLOSED;
// Vogal pesa o dobro da consoante no tempo da palavra.
const weights = letters.map((ch) => (isVowel(ch) ? 1.7 : 0.8));
const total = weights.reduce((a, b) => a + b, 0);
let pos = ((t - w.startS) / Math.max(0.04, w.endS - w.startS)) * total;
let i = 0;
while (i < letters.length - 1 && pos > weights[i]) { pos -= weights[i]; i++; }
const frac = Math.min(1, pos / weights[i]);
const cur = visemeOf(letters[i]);
const next = i + 1 < letters.length ? visemeOf(letters[i + 1]) : CLOSED;
// Coarticulação: a 2ª metade da letra já caminha para a próxima.
let v = frac > 0.5 ? mix(cur, next, (frac - 0.5) * 0.9) : cur;
if (env?.values.length) {
const a = env.values[Math.min(env.values.length - 1, Math.max(0, Math.floor(t * env.fps)))] ?? 0;
const k = Math.max(0, Math.min(1.15, (a - 0.03) / 0.3));
v = { ...v, open: v.open * (0.25 + 0.75 * Math.min(1, k)) * (k < 0.05 ? 0.2 : 1) };
}
return v;
}
/** Ênfase (0–1) no instante: o volume perto do pico levanta um pouco as sobrancelhas. */
export function emphasisAt(t: number, env?: { values: number[]; fps: number }): number {
if (!env?.values.length) return 0;
const a = env.values[Math.min(env.values.length - 1, Math.max(0, Math.floor(t * env.fps)))] ?? 0;
return Math.max(0, Math.min(1, (a - 0.45) / 0.4));
}
/** Põe a fala na boca mantendo a expressão (cantos, sobrancelhas, olhos). `k` = quanto da fala entra (0–1). */
export function speak(face: FaceParams, v: Viseme, k = 1, emphasis = 0): FaceParams {
const open = Math.max(face.mouthOpen * 0.35, v.open * 0.9);
return {
...face,
mouthOpen: face.mouthOpen + (open - face.mouthOpen) * k,
mouthWidth: face.mouthWidth * (1 + (v.wide * 0.22 - v.round * 0.45) * k),
mouthRound: face.mouthRound + (v.round - face.mouthRound) * k,
teeth: k > 0.5 ? v.teeth && v.open > 0.1 : face.teeth,
browL: { ...face.browL, y: face.browL.y - emphasis * 3 * k },
browR: { ...face.browR, y: face.browR.y - emphasis * 3 * k },
};
}
+222
View File
@@ -0,0 +1,222 @@
// Movimento do personagem: uma LINHA DO TEMPO de ações que se combinam (não animações prontas). Cada ação tem
// início (segundos `at`, fração do trecho `atP` ou a palavra da narração `cue`) e duração; o estado em cada
// quadro sai de aplicar as ações em ordem sobre a expressão/pose de base, mais a "vida" (piscar, respirar).
// Ações permanentes mudam o estado dali em diante (express, pose, walk, sit, fall, turn, look); as momentâneas
// voltam ao fim (nod, shake_head, tremble, bounce, wave, jump, talk, emote).
import { emphasisAt, speak, visemeAt, type SpokenWord } from "./lipsync";
import { blendBody, blendFace, bodyOf, faceOf, withBody, withFace, type BodyParams, type BodyPatch, type FaceParams, type FacePatch } from "./rig";
export const ACTIONS = ["express", "pose", "walk", "run", "enter", "exit", "jump", "nod", "shake_head", "tremble", "bounce", "fall",
"sit", "stand_up", "turn", "talk", "look", "emote", "wave", "hammer"] as const;
export type ActionKind = (typeof ACTIONS)[number];
export type Action = {
do: ActionKind;
/** Início: segundos, fração do trecho (0–1) ou a 1ª palavra da narração que começa com `cue`. */
at?: number; atP?: number; cue?: string;
dur?: number;
/** talk: termina no fim desta palavra da narração (a fala vai de `cue` até `cueEnd`). */
cueEnd?: string;
expression?: string; face?: FacePatch;
pose?: string; body?: BodyPatch;
/** walk/run/enter: x de destino (fração). */
to?: number;
/** look: para onde; fall: para que lado. */
dir?: "left" | "right" | "up" | "down";
/** nod/shake_head/bounce/wave: repetições. jump: altura (fração da altura do quadro). */
times?: number; height?: number;
/** emote: símbolo sobre a cabeça ("!", "?", "…", "♥", "zzz", "💢"). talk: o texto falado (sem tempos de palavra, é
* repartido pela duração). */
text?: string;
};
export type ActorInput = {
x: number; expression?: string; pose?: string; face?: FacePatch; body?: BodyPatch; flip?: boolean; timeline?: Action[];
};
export type ActorState = {
face: FaceParams; body: BodyParams;
x: number; dy: number; dx: number; rot: number; sx: number; sy: number; flip: boolean;
emote: { text: string; k: number } | null;
};
const DEFAULT_DUR: Record<ActionKind, number> = {
express: 0.25, pose: 0.35, walk: 1.6, run: 0.9, enter: 1.2, exit: 1.2, jump: 0.8, nod: 0.7, shake_head: 0.8, tremble: 1, bounce: 0.8,
fall: 0.6, sit: 0.5, stand_up: 0.5, turn: 0.3, talk: 1.5, look: 0.3, emote: 1.2, wave: 1.2, hammer: 2.4,
};
const clamp01 = (v: number) => Math.max(0, Math.min(1, v));
const ease = (p: number) => (p < 0.5 ? 2 * p * p : 1 - (-2 * p + 2) ** 2 / 2);
/** Passa um pouco do alvo e volta (dá vida às poses). */
const easeBack = (p: number) => { const c = 1.4; return 1 + (c + 1) * (p - 1) ** 3 + c * (p - 1) ** 2; };
const norm = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]/g, "");
/** Início da ação em segundos (cue = palavra falada; sem a palavra, cai para atP/at/0). */
export function startOf(a: Action, durationS: number, words: { text: string; startS: number }[] = []): number {
if (a.cue) {
const c = norm(a.cue);
const w = words.find((x) => norm(x.text).startsWith(c));
if (w) return w.startS;
}
if (a.atP !== undefined) return a.atP * durationS;
return a.at ?? 0;
}
/** Piscar em intervalos variados (2,4–4,6 s), determinístico pela semente. */
function blinkAt(t: number, seed: number): number {
let s = 0.6 + (seed % 7) * 0.13;
let k = 1;
while (s < t + 0.2) {
const d = t - s;
if (d >= 0 && d < 0.13) k = Math.min(k, Math.abs(d - 0.065) / 0.065);
s += 2.4 + ((Math.sin(s * 12.9898 + seed) + 1) / 2) * 2.2;
}
return k;
}
/** Fala do trecho: palavras com tempo (narração) e, se houver, o volume do áudio quadro a quadro. */
export type Speech = { words: SpokenWord[]; env?: { values: number[]; fps: number } };
/** Fim da fala: o fim da palavra `cueEnd` (depois do início), senão início + dur. */
function endOf(a: Action, s: number, words: SpokenWord[]): number | null {
if (!a.cueEnd) return null;
const c = norm(a.cueEnd);
const w = words.find((x) => x.startS >= s - 0.01 && norm(x.text).startsWith(c));
return w ? w.endS : null;
}
export function evaluate(actor: ActorInput, t: number, durationS: number, seed = 1, speech: Speech = { words: [] }): ActorState {
const words = speech.words;
const st: ActorState = {
face: faceOf(actor.expression, actor.face), body: bodyOf(actor.pose, actor.body),
x: actor.x, dy: 0, dx: 0, rot: 0, sx: 1, sy: 1, flip: !!actor.flip, emote: null,
};
const timeline = (actor.timeline ?? []).map((a) => ({ a, s: startOf(a, durationS, words) })).sort((p, q) => p.s - q.s);
for (const { a, s } of timeline) {
if (t < s) break;
const end = a.do === "talk" ? endOf(a, s, words) : null;
const d = Math.max(0.05, end !== null ? end - s : a.dur ?? DEFAULT_DUR[a.do]);
const p = clamp01((t - s) / d);
const active = t - s < d;
const env = active ? Math.min(1, (t - s) / 0.15, (s + d - t) / 0.15) : 0; // entra e sai suave (momentâneas)
switch (a.do) {
case "express": {
const target = a.expression ? faceOf(a.expression, a.face) : withFace(st.face, a.face);
st.face = blendFace(st.face, target, ease(p));
break;
}
case "pose": {
const target = a.pose ? bodyOf(a.pose, a.body) : withBody(st.body, a.body);
st.body = blendBody(st.body, target, clamp01(easeBack(p)));
break;
}
case "walk": case "run": case "enter": case "exit": {
const from = a.do === "enter" ? (a.to ?? st.x) < 0.5 ? -0.25 : 1.25 : st.x;
const to = a.do === "exit" ? (st.x < 0.5 ? -0.3 : 1.3) : a.to ?? st.x;
const run = a.do === "run";
st.x = from + (to - from) * (run ? p : ease(p));
if (to !== from) st.flip = to < from;
if (active) {
const phase = (t - s) * Math.PI * 2 * (run ? 3.2 : 2.1);
const amp = run ? 1.6 : 1;
const sw = Math.sin(phase);
st.body = withBody(st.body, {
armL: { raise: 8 + sw * 20 * amp, bend: run ? 85 : 15 }, armR: { raise: 8 - sw * 20 * amp, bend: run ? 85 : 15 },
legL: { raise: 3 + Math.max(0, sw) * 6, bend: Math.max(0, sw) * 38 * amp }, legR: { raise: 3 + Math.max(0, -sw) * 6, bend: Math.max(0, -sw) * 38 * amp },
lean: (to < from ? -1 : 1) * (run ? 8 : 3),
});
st.dy -= Math.abs(Math.sin(phase)) * (run ? 0.012 : 0.006);
}
break;
}
case "jump": {
if (!active) break;
const h = a.height ?? 0.08;
if (p < 0.15) { st.sy *= 1 - 0.1 * (p / 0.15); st.sx *= 1 + 0.06 * (p / 0.15); st.body = withBody(st.body, { crouch: 0.35 * (p / 0.15) }); }
else if (p < 0.85) {
const q = (p - 0.15) / 0.7;
st.dy -= h * 4 * q * (1 - q);
st.sy *= 1.07; st.sx *= 0.95;
st.body = withBody(st.body, { arms: { raise: 120, bend: -10 }, legs: { raise: 6, bend: 30 } });
} else { const q = (p - 0.85) / 0.15; st.sy *= 1 - 0.08 * (1 - q); st.sx *= 1 + 0.05 * (1 - q); }
break;
}
case "nod": st.body = withBody(st.body, { headNod: st.body.headNod + Math.sin(p * Math.PI * 2 * (a.times ?? 2)) * 0.6 * env }); break;
case "shake_head": st.body = withBody(st.body, { headTurn: st.body.headTurn + Math.sin(p * Math.PI * 2 * (a.times ?? 2)) * 0.7 * env }); break;
case "tremble": if (active) { st.dx += Math.sin(t * 77.7) * 0.004 * env; st.dy += Math.cos(t * 91.3) * 0.002 * env; } break;
case "bounce": st.dy -= Math.abs(Math.sin(p * Math.PI * (a.times ?? 2))) * 0.02 * env; break;
case "fall": {
const side = a.dir === "right" ? 1 : -1;
st.rot = side * 88 * ease(p);
st.dy += 0.02 * ease(p);
st.face = blendFace(st.face, faceOf("shocked"), Math.min(1, p * 3));
break;
}
case "sit": st.body = blendBody(st.body, withBody(st.body, { crouch: 1, arms: { raise: 14, bend: 40 } }), ease(p)); break;
case "stand_up": st.body = blendBody(st.body, withBody(st.body, { crouch: 0 }), ease(p)); break;
case "turn": {
const flipped = !st.flip;
if (p >= 0.5) st.flip = flipped;
if (active) st.sx *= Math.max(0.15, Math.abs(Math.cos(p * Math.PI)));
break;
}
case "talk": {
if (!active) break;
// Palavras da narração dentro da fala; sem elas, o texto da ação repartido pela duração (vogal pesa mais).
let spoken = words.filter((w) => w.endS > s && w.startS < s + d);
if (!spoken.length && a.text) {
const list = a.text.split(/\s+/).filter(Boolean);
const total = list.reduce((n, w) => n + w.length + 1, 0);
let c = s;
spoken = list.map((w) => { const len = (d * (w.length + 1)) / total; const out = { text: w, startS: c, endS: c + len * 0.88 }; c += len; return out; });
}
if (spoken.length) {
st.face = speak(st.face, visemeAt(spoken, t, speech.env), Math.min(1, (t - s) / 0.08, (s + d - t) / 0.08 + 0.2), emphasisAt(t, speech.env));
} else {
const flap = Math.abs(Math.sin((t - s) * Math.PI * 2 * 4.3 + seed)) * (0.6 + 0.4 * Math.sin((t - s) * 9.1 + seed));
st.face = { ...st.face, mouthOpen: Math.max(st.face.mouthOpen, (0.12 + 0.5 * flap) * env), teeth: st.face.teeth || flap > 0.6 };
}
// Quem fala mexe a cabeça de leve e acompanha as sílabas fortes.
st.body = withBody(st.body, { headTilt: st.body.headTilt + Math.sin((t - s) * 5.3) * 2 * env, headNod: st.body.headNod + emphasisAt(t, speech.env) * 0.25 });
break;
}
case "look": {
const gx = a.dir === "left" ? -0.9 : a.dir === "right" ? 0.9 : 0;
const gy = a.dir === "up" ? -0.8 : a.dir === "down" ? 0.8 : 0;
const k = ease(p);
st.face = { ...st.face, gazeX: st.face.gazeX + (gx - st.face.gazeX) * k, gazeY: st.face.gazeY + (gy - st.face.gazeY) * k };
st.body = withBody(st.body, { headTurn: st.body.headTurn + (gx * 0.5 - st.body.headTurn) * k, headNod: st.body.headNod + (gy * -0.4 - st.body.headNod) * k });
break;
}
case "emote": if (active) st.emote = { text: a.text ?? "!", k: env }; break;
// Martelar: braço direito sobe e desce batendo (`times` golpes), cabeça acompanha cada batida.
case "hammer": if (active) {
const beat = Math.abs(Math.sin(p * Math.PI * (a.times ?? 5)));
st.body = withBody(st.body, { armR: { raise: 40 + beat * 95 * Math.min(1, env * 1.5), bend: 60 + beat * 40 }, headNod: st.body.headNod + (1 - beat) * 0.15 * env });
break;
}
case "wave": if (active) st.body = withBody(st.body, { armR: { raise: 140 * Math.min(1, env * 1.5), bend: -25 + Math.sin(p * Math.PI * 2 * (a.times ?? 3)) * 30 } }); break;
}
}
// Vida: piscar (a não ser de olhos quase fechados), respirar e um balanço leve de cabeça.
const blink = blinkAt(t, seed);
if (blink < 1) st.face = { ...st.face, eyeL: st.face.eyeL * Math.max(0.08, blink), eyeR: st.face.eyeR * Math.max(0.08, blink) };
st.body = withBody(st.body, { headTilt: st.body.headTilt + Math.sin(t * 0.9 + seed) * 1.2 });
return st;
}
/** Confere uma linha do tempo (lista de problemas; vazia = ok). */
export function validateTimeline(timeline: unknown): string[] {
if (timeline === undefined) return [];
if (!Array.isArray(timeline) || timeline.length > 40) return ["timeline: lista de até 40 ações"];
const errors: string[] = [];
timeline.forEach((a: Partial<Action>, i) => {
if (!a || !ACTIONS.includes(a.do as ActionKind)) errors.push(`timeline[${i}].do: ${ACTIONS.join(", ")}`);
for (const k of ["at", "atP", "dur", "to", "times", "height"] as const) {
if (a[k] !== undefined && (typeof a[k] !== "number" || !Number.isFinite(a[k]))) errors.push(`timeline[${i}].${k}: número`);
}
if (a.atP !== undefined && !(a.atP >= 0 && a.atP <= 1)) errors.push(`timeline[${i}].atP entre 0 e 1`);
if (a.dur !== undefined && !(a.dur > 0 && a.dur <= 30)) errors.push(`timeline[${i}].dur entre 0 e 30 s`);
});
return errors;
}
+343 -33
View File
@@ -1,9 +1,13 @@
// Camadas por cima da cena: etiqueta, onomatopeia, contador, ondas de som, X vermelho, painel do topo (HUD) e a
// legenda palavra por palavra (cada palavra entra pequena e cresce; palavra-chave em amarelo, perigo em vermelho).
// Camadas por cima da cena: etiqueta, onomatopeia, ondas de som, X vermelho, painel do topo (HUD), cartão de nome,
// cartelas de dado (número grande, lista com caixas, tabela, barra de progresso, grade de quadradinhos) e a legenda
// palavra por palavra (cada palavra entra pequena e cresce; palavra-chave maior e em amarelo, perigo em vermelho).
//
// Tudo é função pura do quadro (mola da Remotion + tempo do spec): o mesmo quadro sai sempre igual.
// Tamanhos em `u(n)` = n% da largura de um quadro vertical 9:16 (num quadro mais largo, limita pela altura).
import React from "react";
import { spring } from "remotion";
import { COLORS, FONT_CAPTION, FONT_LABEL, TONE_BG, TONE_FG } from "./theme";
import type { ShotSpec, TextItem, Tone, Word } from "./spec";
import { COLORS, FONT_CAPTION, FONT_LABEL, FONT_TEXT, TONE_BG, TONE_FG } from "./theme";
import { numberOf, type Hud as HudSpec, type TextItem, type TextRow, type Tone, type Word } from "./spec";
/** 0 → 1 com mola, a partir de `startS` (antes disso, 0). */
export function pop(frame: number, fps: number, startS = 0, stiffness = 220): number {
@@ -16,6 +20,32 @@ export function shake(frame: number, amp = 3): { x: number; y: number } {
return { x: Math.sin(frame * 12.9898) * amp, y: Math.cos(frame * 78.233) * amp * 0.7 };
}
/** 0 → 1 sem mola (desacelera no fim), de `startS` a `startS + durS`: barra enchendo, número contando. */
export function ease(frame: number, fps: number, startS: number, durS: number): number {
const p = Math.max(0, Math.min(1, (frame / fps - startS) / Math.max(0.01, durS)));
return 1 - (1 - p) ** 3;
}
/** Medida proporcional ao quadro: n% da largura de um vertical 9:16. */
export const u = (n: number) => `calc(${n.toFixed(3)} * min(1cqw, 0.5625cqh))`;
/** Cores do grafismo (cartelas, HUD, cartão de nome). */
export const UI = {
ink: "#151a31",
box: "rgba(15,18,30,0.94)",
boxEdge: "rgba(150,160,210,0.16)",
cell: "#252c48",
cream: "#f3efe6",
yellow: "#fcc430",
red: "#ea4752",
redSoft: "#f4646d",
green: "#2f9a55",
muted: "#c3c8dd",
dim: "#7f87a8",
track: "#2a3050",
};
const TONE_TEXT: Record<Tone, string> = { danger: UI.red, info: UI.yellow, ok: "#45c97a" };
const at = (x: number, y: number): React.CSSProperties => ({ position: "absolute", left: `${x * 100}%`, top: `${y * 100}%` });
export function TagLabel({ text, tone = "info", size = 3.6 }: { text: string; tone?: Tone; size?: number }) {
@@ -28,24 +58,244 @@ export function TagLabel({ text, tone = "info", size = 3.6 }: { text: string; to
);
}
export function TextLayer({ t, frame, fps }: { t: TextItem; frame: number; fps: number }) {
const k = pop(frame, fps, t.atS ?? 0);
if (k <= 0.001) return null;
const base = { ...at(t.x, t.y), transform: `translate(-50%, -50%) rotate(${t.rotate ?? 0}deg) scale(${0.4 + 0.6 * k})`, opacity: Math.min(1, k * 1.4) };
if (t.kind === "tag") return <div style={base}><TagLabel text={t.text} tone={t.tone} /></div>;
if (t.kind === "counter") {
/**
* Cartão de nome do personagem: cartão creme arredondado, nome grande em letra condensada escura e 1–2 linhas
* menores (função, dado). Sem posição nem animação: quem usa posiciona e faz a entrada.
*/
export function NameCard({ name, lines = [], size = 1 }: { name: string; lines?: string[]; size?: number }) {
const s = size;
return (
<div style={{ ...base, textAlign: "center", border: "0.35cqw solid #fff", borderRadius: "1.4cqw", padding: "0.8cqw 2.6cqw",
background: "rgba(10,12,28,0.85)" }}>
<div style={{ fontFamily: FONT_LABEL, fontSize: "2.6cqw", color: "#c9cbe0", letterSpacing: "0.08em" }}>{t.text.toUpperCase()}</div>
<div style={{ fontFamily: FONT_CAPTION, fontSize: "8cqw", color: "#fff", lineHeight: 1 }}>{t.value ?? ""}</div>
<div style={{ display: "inline-block", background: UI.cream, borderRadius: u(2.4 * s), padding: `${u(2.2 * s)} ${u(3.4 * s)} ${u(2.5 * s)}`,
boxShadow: `0 ${u(0.9 * s)} 0 rgba(8,10,22,0.34)`, textAlign: "left", whiteSpace: "nowrap" }}>
<div style={{ fontFamily: FONT_CAPTION, fontSize: u(6 * s), color: UI.ink, lineHeight: 1.12, letterSpacing: "0.005em" }}>{name.toUpperCase()}</div>
{lines.filter((l) => l.trim()).slice(0, 3).map((l, i) => (
<div key={i} style={{ fontFamily: FONT_TEXT, fontSize: u(3.3 * s), color: "#1c2138", lineHeight: 1.55, letterSpacing: "0.035em",
marginTop: i === 0 ? u(0.3 * s) : 0 }}>
{l.toUpperCase()}
</div>
))}
</div>
);
}
const s = t.kind === "onomatopoeia" ? shake(frame, 4) : { x: 0, y: 0 };
/** Conta o número do texto de 0 até o valor ("R$ 134.273", "-R$ 47.312.904", "297"), mantendo prefixo e sufixo. */
export function countUp(value: string, p: number): string {
const m = /^(\D*?)(\d{1,3}(?:\.\d{3})+|\d+)(,\d+)?(\D*)$/.exec(value.trim());
if (!m || p >= 1) return value;
const target = Number(m[2].replace(/\./g, ""));
if (target < 10) return value;
const n = String(Math.round(target * Math.max(0, p)));
const digits = m[2].includes(".") ? n.replace(/\B(?=(\d{3})+(?!\d))/g, ".") : n;
return `${m[1]}${digits}${m[3] ?? ""}${m[4]}`;
}
/** Caixa escura arredondada das cartelas flutuantes. */
function Box({ s, children, style }: { s: number; children: React.ReactNode; style?: React.CSSProperties }) {
return (
<div style={{ background: UI.box, borderRadius: u(3 * s), border: `${u(0.22 * s)} solid ${UI.boxEdge}`,
boxShadow: `0 ${u(0.8 * s)} 0 rgba(0,0,0,0.3)`, ...style }}>
{children}
</div>
);
}
/** Fundo escuro de tela inteira (cartela "panel"), com leve luz no centro como a referência. */
function PanelBackdrop({ k }: { k: number }) {
return (
<div style={{ position: "absolute", inset: "-4%", opacity: Math.min(1, k * 2.2),
background: "radial-gradient(ellipse 62% 42% at 50% 46%, #1d2342 0%, #151a31 55%, #0e1222 100%)" }} />
);
}
const label = (size: number, color = UI.muted, spacing = 0.16): React.CSSProperties => ({
fontFamily: FONT_TEXT, fontSize: u(size), color, letterSpacing: `${spacing}em`, lineHeight: 1.1, whiteSpace: "nowrap",
});
function StatCard({ t, s, frame, fps }: { t: TextItem; s: number; frame: number; fps: number }) {
const atS = t.atS ?? 0;
const value = countUp(String(t.value ?? ""), ease(frame, fps, atS + 0.1, 0.9));
const inner = (
<div style={{ textAlign: "center" }}>
{t.text.trim() && <div style={{ ...label(4.4 * s), marginBottom: u(1.2 * s), paddingLeft: "0.16em" }}>{t.text.toUpperCase()}</div>}
<div style={{ fontFamily: FONT_CAPTION, fontSize: u(15.5 * s), lineHeight: 1.08, whiteSpace: "nowrap",
color: t.tone ? TONE_TEXT[t.tone] : "#ffffff", textShadow: `0 ${u(0.6 * s)} 0 rgba(0,0,0,0.3)` }}>{value.toUpperCase()}</div>
</div>
);
return t.panel ? inner : <Box s={s} style={{ padding: `${u(2.6 * s)} ${u(5 * s)} ${u(2 * s)}` }}>{inner}</Box>;
}
function CounterCard({ t, s, frame, fps }: { t: TextItem; s: number; frame: number; fps: number }) {
const value = countUp(String(t.value ?? ""), ease(frame, fps, (t.atS ?? 0) + 0.1, 0.8));
return (
<Box s={s} style={{ padding: `${u(2.2 * s)} ${u(4.6 * s)} ${u(1.4 * s)}`, textAlign: "center", borderRadius: u(2.8 * s) }}>
<div style={{ ...label(3.5 * s, UI.muted, 0.12), paddingLeft: "0.12em" }}>{t.text.toUpperCase()}</div>
<div style={{ fontFamily: FONT_CAPTION, fontSize: u(11 * s), color: t.tone ? TONE_TEXT[t.tone] : "#ffffff", lineHeight: 1.12 }}>{value}</div>
</Box>
);
}
/** Caixa de seleção: vazia (contorno), marcada (verde enche da esquerda e o ✓ se desenha) ou riscada (vermelha com X). */
function CheckBox({ state, m, s }: { state: TextRow["state"]; m: number; s: number }) {
const side = u(8.2 * s);
const fill = state === "crossed" ? UI.red : UI.green;
const marked = state === "checked" || state === "crossed";
const draw = Math.max(0, Math.min(1, (m - 0.45) / 0.55));
return (
<div style={{ position: "relative", width: side, height: side, flex: "none", borderRadius: u(1.6 * s), overflow: "hidden",
boxSizing: "border-box", border: `${u(0.7 * s)} solid ${marked && m > 0 ? fill : state === "empty" ? "#4d5476" : "#6d7598"}` }}>
{marked && m > 0 && <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${Math.min(1, m * 1.8) * 100}%`, background: fill }} />}
{marked && draw > 0 && (
<svg viewBox="0 0 100 100" style={{ position: "absolute", inset: "-12%", width: "124%", height: "124%" }}>
{state === "checked"
? <path d="M27 52 L44 68 L74 34" fill="none" stroke="#fff" strokeWidth={12} strokeLinecap="round" strokeLinejoin="round"
strokeDasharray={80} strokeDashoffset={80 * (1 - draw)} />
: <g stroke="#fff" strokeWidth={12} strokeLinecap="round">
<line x1={34} y1={34} x2={34 + 32 * Math.min(1, draw * 2)} y2={34 + 32 * Math.min(1, draw * 2)} />
{draw > 0.5 && <line x1={66} y1={34} x2={66 - 32 * (draw - 0.5) * 2} y2={34 + 32 * (draw - 0.5) * 2} />}
</g>}
</svg>
)}
</div>
);
}
function ChecklistCard({ t, s, frame, fps }: { t: TextItem; s: number; frame: number; fps: number }) {
const atS = t.atS ?? 0;
const step = t.stepS ?? 0.5;
const items = t.items ?? [];
let order = 0;
return (
<Box s={s} style={{ padding: `${u(5 * s)} ${u(7 * s)} ${u(5 * s)} ${u(6.4 * s)}`, minWidth: u((t.panel ? 84 : 30) * s), boxSizing: "border-box",
...(t.panel ? { background: "rgba(9,11,22,0.6)", boxShadow: "none" } : {}) }}>
{t.text.trim() && <div style={{ ...label(3.8 * s), marginBottom: u(3 * s) }}>{t.text.toUpperCase()}</div>}
{items.map((it, i) => {
const kIn = pop(frame, fps, atS + i * 0.07, 260);
const marked = it.state === "checked" || it.state === "crossed";
// Marcadas e riscadas em sequência, na ordem da lista.
const m = marked ? ease(frame, fps, atS + 0.45 + step * order++, 0.38) : 0;
const color = it.state === "crossed" && m > 0.5 ? UI.redSoft : marked && m > 0.5 ? "#ffffff" : it.state === "empty" ? UI.dim : UI.muted;
return (
<div key={i} style={{ display: "flex", alignItems: "center", gap: u(4 * s), marginTop: i ? u(3.3 * s) : 0,
opacity: Math.min(1, kIn * 1.6), transform: `translateX(${(1 - kIn) * -6}%)` }}>
<CheckBox state={it.state ?? "empty"} m={m} s={s} />
<span style={{ ...label(6.1 * s, color, 0.05) }}>{it.text.toUpperCase()}</span>
</div>
);
})}
</Box>
);
}
function TableCard({ t, s, frame, fps }: { t: TextItem; s: number; frame: number; fps: number }) {
const atS = t.atS ?? 0;
const items = t.items ?? [];
const hl = t.highlight;
const hlK = hl === undefined ? 0 : pop(frame, fps, atS + 0.35 + items.length * 0.1, 200);
const hlColor = t.tone === "ok" ? UI.green : t.tone === "info" ? UI.yellow : UI.red;
return (
<Box s={s} style={{ padding: `${u(3.8 * s)} ${u(3.6 * s)}`, width: u(80 * s), boxSizing: "border-box" }}>
{t.text.trim() && <div style={{ ...label(3.8 * s), marginBottom: u(2.2 * s), paddingLeft: u(1.6 * s) }}>{t.text.toUpperCase()}</div>}
{items.map((it, i) => {
const kIn = pop(frame, fps, atS + 0.1 + i * 0.1, 260);
const on = i === hl;
const fg = on && hlK > 0.5 ? (t.tone === "info" ? UI.ink : "#ffffff") : "#ffffff";
return (
<div key={i} style={{ position: "relative", display: "flex", alignItems: "center", gap: u(2.6 * s), padding: `${u(1.5 * s)} ${u(2.2 * s)}`,
borderTop: i ? `${u(0.2 * s)} solid rgba(255,255,255,0.07)` : "none", opacity: Math.min(1, kIn * 1.6),
transform: `translateY(${(1 - kIn) * 25}%) scale(${on ? 1 + 0.04 * hlK : 1})` }}>
{on && <div style={{ position: "absolute", inset: `${u(-0.3 * s)} ${u(-1 * s)}`, borderRadius: u(1.4 * s), background: hlColor, opacity: hlK,
boxShadow: `0 ${u(0.5 * s)} 0 rgba(0,0,0,0.3)` }} />}
<span style={{ position: "relative", fontFamily: FONT_CAPTION, fontSize: u(4.6 * s), color: on && hlK > 0.5 ? fg : UI.dim, width: u(4.4 * s), lineHeight: 1.15 }}>{i + 1}</span>
<span style={{ position: "relative", ...label(5 * s, fg, 0.04), flex: 1, overflow: "hidden", textOverflow: "ellipsis" }}>{it.text.toUpperCase()}</span>
{it.value !== undefined && <span style={{ position: "relative", fontFamily: FONT_CAPTION, fontSize: u(5.2 * s), color: fg, lineHeight: 1.15 }}>{it.value.toUpperCase()}</span>}
</div>
);
})}
</Box>
);
}
function ProgressCard({ t, s, frame, fps }: { t: TextItem; s: number; frame: number; fps: number }) {
const target = Math.max(0, Math.min(100, numberOf(t.value)));
const f = ease(frame, fps, (t.atS ?? 0) + 0.25, 1.1);
const pct = Math.round(target * f);
const color = t.tone ? TONE_TEXT[t.tone] : UI.yellow;
return (
<Box s={s} style={{ padding: `${u(2.6 * s)} ${u(3.6 * s)} ${u(3 * s)}`, width: u(82 * s), boxSizing: "border-box" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
<span style={{ ...label(4 * s, "#ffffff", 0.12) }}>{t.text.toUpperCase()}</span>
<span style={{ fontFamily: FONT_CAPTION, fontSize: u(5.6 * s), color, lineHeight: 1.1 }}>{pct}%</span>
</div>
<div style={{ marginTop: u(1.6 * s), height: u(2.6 * s), borderRadius: u(1.3 * s), background: UI.track, overflow: "hidden" }}>
<div style={{ height: "100%", width: `${target * f}%`, borderRadius: u(1.3 * s), background: color,
boxShadow: `inset 0 ${u(0.6 * s)} 0 rgba(255,255,255,0.28)` }} />
</div>
</Box>
);
}
function GridCard({ t, s, frame, fps }: { t: TextItem; s: number; frame: number; fps: number }) {
const atS = t.atS ?? 0;
const total = Math.max(1, Math.min(40, Math.round(t.total ?? 1)));
const filled = Math.max(0, Math.min(total, Math.round(numberOf(t.value) || 0)));
const cols = total <= 6 ? total : total <= 24 ? 6 : 8;
const side = 7.4 * s;
return (
<Box s={s} style={{ padding: `${u(3.4 * s)} ${u(4 * s)} ${u(3.2 * s)}` }}>
<div style={{ fontFamily: FONT_CAPTION, fontSize: u(6.4 * s), color: "#ffffff", lineHeight: 1.15, marginBottom: u(2.2 * s), whiteSpace: "nowrap" }}>{t.text.toUpperCase()}</div>
<div style={{ display: "grid", gridTemplateColumns: `repeat(${cols}, ${u(side)})`, gap: u(1.3 * s) }}>
{Array.from({ length: total }, (_, i) => {
const k = i < filled ? pop(frame, fps, atS + 0.35 + i * 0.14, 260) : 0;
return (
<div key={i} style={{ position: "relative", width: u(side), height: u(side), boxSizing: "border-box", borderRadius: u(1 * s),
border: `${u(0.45 * s)} solid #3a4166` }}>
{k > 0.001 && (
<div style={{ position: "absolute", inset: u(-0.45 * s), borderRadius: u(1 * s), background: UI.cream, transform: `scale(${0.4 + 0.6 * k})`,
opacity: Math.min(1, k * 1.8), display: "flex", alignItems: "center", justifyContent: "center",
fontFamily: FONT_CAPTION, fontSize: u(4.4 * s), color: UI.ink, lineHeight: 1 }}>{i + 1}</div>
)}
</div>
);
})}
</div>
<div style={{ ...label(3.6 * s, UI.yellow, 0.12), marginTop: u(2.4 * s) }}>{filled} DE {total}</div>
</Box>
);
}
const CARDS = { stat: StatCard, counter: CounterCard, checklist: ChecklistCard, table: TableCard, progress: ProgressCard, grid: GridCard } as const;
export function TextLayer({ t, frame, fps }: { t: TextItem; frame: number; fps: number }) {
const k = pop(frame, fps, t.atS ?? 0);
if (k <= 0.001) return null;
const s = t.size ?? 1;
if (t.kind === "namecard") {
// Entra deslizando do lado de fora do quadro, com mola.
const dir = t.x < 0.5 ? -1 : 1;
return (
<div style={{ ...at(t.x, t.y), transform: `translate(-50%, -50%) translateX(${dir * (1 - k) * 18}%) scale(${0.82 + 0.18 * k})`,
opacity: Math.min(1, k * 1.6) }}>
<NameCard name={t.text} lines={t.lines} size={s} />
</div>
);
}
if (t.kind in CARDS) {
const Card = CARDS[t.kind as keyof typeof CARDS];
return (
<>
{t.panel && <PanelBackdrop k={k} />}
<div style={{ ...at(t.x, t.y), transform: `translate(-50%, -50%) translateY(${(1 - k) * 6}%) scale(${0.8 + 0.2 * k})`, opacity: Math.min(1, k * 1.6) }}>
<Card t={t} s={s} frame={frame} fps={fps} />
</div>
</>
);
}
const base = { ...at(t.x, t.y), transform: `translate(-50%, -50%) rotate(${t.rotate ?? 0}deg) scale(${0.4 + 0.6 * k})`, opacity: Math.min(1, k * 1.4) };
if (t.kind === "tag") return <div style={base}><TagLabel text={t.text} tone={t.tone} /></div>;
const sh = t.kind === "onomatopoeia" ? shake(frame, 4) : { x: 0, y: 0 };
const color = t.tone === "danger" ? COLORS.danger : t.kind === "big" ? "#ffffff" : COLORS.key;
return (
<div style={{ ...base, transform: `${base.transform} translate(${s.x}px, ${s.y}px)`, fontFamily: FONT_CAPTION, color,
<div style={{ ...base, transform: `${base.transform} translate(${sh.x}px, ${sh.y}px)`, fontFamily: FONT_CAPTION, color,
fontSize: t.kind === "big" ? "12cqw" : "9cqw", whiteSpace: "nowrap", WebkitTextStroke: "0.35cqw #121326",
paintOrder: "stroke fill", textShadow: "0 0.6cqw 0 rgba(0,0,0,0.35)" }}>
{t.text.toUpperCase()}
@@ -77,21 +327,61 @@ export function CrossOut({ k }: { k: number }) {
);
}
export function Hud({ hud, frame, fps }: { hud: NonNullable<ShotSpec["hud"]>; frame: number; fps: number }) {
let clock = hud.clock;
if (clock && /^\d{1,2}:\d{2}$/.test(clock) && hud.clockMinutesPerSecond) {
/** Hora do HUD andando: "10:06" + minutos por segundo de trecho. */
export function hudClock(clock: string | undefined, t: number, minutesPerSecond?: number): string | undefined {
if (!clock || !/^\d{1,2}:\d{2}$/.test(clock) || !minutesPerSecond) return clock;
const [h, m] = clock.split(":").map(Number);
const total = (h * 60 + m + Math.floor((frame / fps) * hud.clockMinutesPerSecond)) % (24 * 60);
clock = `${String(Math.floor(total / 60)).padStart(2, "0")}:${String(total % 60).padStart(2, "0")}`;
const total = (h * 60 + m + Math.floor(t * minutesPerSecond)) % (24 * 60);
return `${String(Math.floor(total / 60)).padStart(2, "0")}:${String(total % 60).padStart(2, "0")}`;
}
/** Valor do HUD zerado ou negativo ("R$ 0,00", "-12") pede vermelho. */
export function hudValueTone(value: string, tone?: Tone): Tone | undefined {
if (tone) return tone;
const v = value.trim();
if (/^[^\d]*-/.test(v)) return "danger";
const digits = v.replace(/[^\d]/g, "");
return digits && Number(digits) === 0 ? "danger" : undefined;
}
/**
* Painel do topo (fixo, sem animação de entrada: continua igual de um trecho para o outro). Esquerda: bloco amarelo
* (`badge`) + hora com ponto vermelho sobre fundo escuro e, embaixo, faixa clara com o lugar. Direita, opcional:
* rótulo pequeno + valor grande e faixa amarela com a nota.
*/
export function Hud({ hud, frame, fps }: { hud: HudSpec; frame: number; fps: number }) {
const clock = hudClock(hud.clock, frame / fps, hud.clockMinutesPerSecond);
const place = hud.place ?? hud.label;
const row = u(8);
const big: React.CSSProperties = { fontFamily: FONT_CAPTION, fontSize: u(5.8), lineHeight: 1, whiteSpace: "nowrap", paddingTop: u(0.3) };
const strip: React.CSSProperties = { ...label(2.5, UI.ink, 0.07), height: u(4.2), display: "flex", alignItems: "center", padding: `0 ${u(2.2)}` };
const shadow = `0 ${u(0.55)} 0 rgba(6,8,18,0.6)`;
const tone = hud.value ? hudValueTone(hud.value, hud.valueTone) : undefined;
return (
<div style={{ position: "absolute", top: "5.5%", left: 0, right: 0, display: "flex", justifyContent: "center", alignItems: "center",
gap: "1.4cqw", fontFamily: FONT_LABEL }}>
<span style={{ background: COLORS.danger, color: "#fff", fontSize: "3.4cqw", padding: "0.2em 0.5em 0.1em", borderRadius: "0.25em" }}>⚡ {hud.badge.toUpperCase()}</span>
<span style={{ color: "#fff", fontSize: "4.2cqw" }}>{hud.label.toUpperCase()}</span>
{clock && <span style={{ background: "#0d0f1f", color: COLORS.key, fontSize: "3.4cqw", padding: "0.2em 0.45em 0.1em", borderRadius: "0.25em",
border: "0.25cqw solid #3a3f6b" }}>{clock}</span>}
<>
<div style={{ position: "absolute", left: u(4), top: u(4.5), display: "inline-flex", flexDirection: "column", alignItems: "stretch", boxShadow: shadow }}>
<div style={{ display: "flex", height: row, background: clock ? "#11141f" : undefined }}>
<div style={{ ...big, background: UI.yellow, color: UI.ink, display: "flex", alignItems: "center", padding: `0 ${u(2.2)}` }}>{hud.badge.toUpperCase()}</div>
{clock && (
<div style={{ ...big, color: "#ffffff", display: "flex", alignItems: "center", gap: u(1.5), padding: `0 ${u(2.4)} 0 ${u(2.2)}` }}>
<span style={{ width: u(1.6), height: u(1.6), borderRadius: "50%", background: UI.red, marginTop: u(-0.3) }} />
{clock}
</div>
)}
</div>
{place && <div style={{ ...strip, background: UI.cream }}>{place.toUpperCase()}</div>}
</div>
{hud.value && (
<div style={{ position: "absolute", right: u(4), top: u(4.5), display: "inline-flex", flexDirection: "column", alignItems: "flex-end" }}>
<div style={{ display: "flex", height: row, boxShadow: hud.note ? "none" : shadow }}>
{hud.valueLabel && <div style={{ ...label(2.5, UI.muted, 0.1), background: UI.cell, display: "flex", alignItems: "center", padding: `0 ${u(1.5)}` }}>{hud.valueLabel.toUpperCase()}</div>}
<div style={{ ...big, background: "#11141f", color: tone === "danger" ? UI.redSoft : tone ? TONE_TEXT[tone] : "#ffffff", display: "flex", alignItems: "center",
padding: `0 ${u(2.2)}` }}>{hud.value.toUpperCase()}</div>
</div>
{hud.note && <div style={{ ...strip, background: UI.yellow, boxShadow: shadow }}>{hud.note.toUpperCase()}</div>}
</div>
)}
</>
);
}
@@ -107,22 +397,29 @@ export function captionChunks(words: Word[]): Word[][] {
return chunks;
}
export function Captions({ words, frame, fps, y = 0.665 }: { words: Word[]; frame: number; fps: number; y?: number }) {
/**
* Legenda: 2–3 palavras grandes em letra condensada branca, contorno e sombra escuros (deslocada para baixo e à
* esquerda, como a referência); palavra-chave maior e amarela, perigo vermelho.
*/
export function Captions({ words, frame, fps, y = 0.8 }: { words: Word[]; frame: number; fps: number; y?: number }) {
const t = frame / fps;
const chunks = captionChunks(words);
const chunk = chunks.find((c, i) => t >= c[0].startS && (i === chunks.length - 1 || t < chunks[i + 1][0].startS));
if (!chunk) return null;
const last = chunk[chunk.length - 1];
if (t > last.endS + 0.6) return null;
const ink = "#0f1226";
return (
<div style={{ position: "absolute", left: "6%", right: "6%", top: `${y * 100}%`, transform: "translateY(-50%)", display: "flex",
flexWrap: "wrap", justifyContent: "center", alignItems: "baseline", columnGap: "2.2cqw", fontFamily: FONT_CAPTION, lineHeight: 1.05 }}>
<div style={{ position: "absolute", left: "5%", right: "5%", top: `${y * 100}%`, transform: "translateY(-50%)", display: "flex",
flexWrap: "wrap", justifyContent: "center", alignItems: "baseline", columnGap: u(2.4), fontFamily: FONT_CAPTION, lineHeight: 1.08 }}>
{chunk.filter((w) => t >= w.startS).map((w, i) => {
const k = pop(frame, fps, w.startS, 320);
const color = w.tone === "danger" ? COLORS.danger : w.tone === "key" ? COLORS.key : "#ffffff";
const strong = w.tone === "key" || w.tone === "danger";
const color = w.tone === "danger" ? COLORS.danger : w.tone === "key" ? UI.yellow : "#ffffff";
return (
<span key={i} style={{ fontSize: "8.4cqw", color, transform: `scale(${0.55 + 0.45 * k})`, display: "inline-block",
textShadow: "0 0.5cqw 0 rgba(0,0,0,0.55), 0 0 1.4cqw rgba(0,0,0,0.5)" }}>
<span key={i} style={{ fontSize: u(strong ? 12.2 : 9.6), color, transform: `scale(${0.55 + 0.45 * k})`, transformOrigin: "50% 80%", display: "inline-block",
WebkitTextStroke: `${u(strong ? 1.1 : 0.9)} ${ink}`, paintOrder: "stroke fill",
textShadow: `${u(-0.7)} ${u(0.9)} 0 ${ink}, ${u(-0.35)} ${u(0.45)} 0 ${ink}, 0 0 ${u(2)} rgba(0,0,0,0.35)` }}>
{w.text.toUpperCase().replace(/[.,;:]$/, "")}
</span>
);
@@ -130,3 +427,16 @@ export function Captions({ words, frame, fps, y = 0.665 }: { words: Word[]; fram
</div>
);
}
/** Textura de papel/granulado por cima de tudo: tira a cara de "vetor de computador" (acabamento de ilustração). */
export function Grain({ opacity = 0.11, seed = 3 }: { opacity?: number; seed?: number }) {
return (
<svg width="100%" height="100%" style={{ position: "absolute", inset: 0, mixBlendMode: "overlay", opacity, pointerEvents: "none" }}>
<filter id={`grain${seed}`}>
<feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves={2} seed={seed} stitchTiles="stitch" />
<feColorMatrix type="saturate" values="0" />
</filter>
<rect width="100%" height="100%" filter={`url(#grain${seed})`} />
</svg>
);
}
+512 -92
View File
@@ -1,142 +1,562 @@
// Lugares montados por PEÇAS (não há cenário pronto): paleta + céu/hora + chão + peças posicionadas por
// profundidade (z: 0 = frente, 1 = fundo). Parque de dia, cemitério na névoa, quarto à noite, bunker com foco
// de luz… tudo sai da mesma gramática. Espaço de desenho 1080×1920; chão começa em `horizon` (fração da altura).
//
// Regras de acabamento (valem para toda peça, ver elements/paint.ts): sombreado em 2 tons com a luz vindo da
// esquerda; 3 planos com perspectiva atmosférica (o fundo puxa para a cor do céu/parede, a frente escurece);
// sombra de contato no chão sob cada objeto. Tudo por mistura de cor — nada de blur por quadro.
import React from "react";
import { rng } from "./random";
import type { ShotSpec } from "./spec";
import { makePaint, mix, palette, type Pal, type PaletteId } from "./elements/paint";
import { NATURE, type Draw } from "./elements/nature";
import { BUILT, FRONT_PART } from "./elements/built";
import { INDOOR } from "./elements/indoor";
export const PALETTES = ["night", "sepia", "day", "dusk", "gray"] as const;
export type PaletteId = (typeof PALETTES)[number];
export { PALETTES, palette, type PaletteId } from "./elements/paint";
export const GROUNDS = ["grass", "street", "dirt", "floor", "sand", "water", "none"] as const;
export const ELEMENTS = ["tree", "deadtree", "pine", "bush", "rock", "mountain", "cloud", "bench", "lamp", "gravestone", "cross", "fence",
"house", "building", "car", "sign", "door", "window", "table", "bed", "shelf", "crate", "tent", "fire"] as const;
"house", "building", "car", "sign", "door", "window", "table", "bed", "shelf", "crate", "tent", "fire",
"ark", "ark_frame", "scaffold", "planks", "rainbow", "waves", "palm", "outcrop",
"cabinet", "locker", "frame", "pendant", "desklamp", "desk", "clothesline", "wall", "facade", "shopfront"] as const;
/** Tempo por cima da cena (chuva caindo; tempestade = chuva forte + relâmpago + céu mais escuro). */
export const WEATHERS = ["none", "rain", "storm"] as const;
export type ElementKind = (typeof ELEMENTS)[number];
/** Fonte de luz posicionada (`spec.lightSource`): luminária, janela ou sol. */
export const LIGHT_SOURCES = ["lamp", "window", "sun"] as const;
export type Place = {
ground: (typeof GROUNDS)[number];
/** Interno: parede no lugar do céu (quarto, bunker, loja). */
indoor?: boolean;
/** Linha do horizonte (fração da altura; padrão 0,56). */
/** Linha do horizonte / pé da parede (fração da altura; padrão 0,56 fora e 0,62 dentro). */
horizon?: number;
fog?: boolean;
elements: { kind: ElementKind; x: number; z?: number; scale?: number; flip?: boolean; color?: string }[];
weather?: (typeof WEATHERS)[number];
/** Água cobrindo o lugar: altura da superfície (fração da altura do quadro, 0 = topo) do início ao fim do trecho.
* Ex.: { from: 0.8, to: 0.5 } = a água sobe. O que não boia fica embaixo dela. */
flood?: { from: number; to: number };
elements: {
kind: ElementKind; x: number; z?: number; scale?: number; flip?: boolean; color?: string;
/** Sobe a peça (fração da altura do quadro): arca em cima do monte. */
lift?: number;
/** Boia na água (com `flood`, acompanha a superfície e balança). */
float?: boolean;
/** Tem gente DENTRO (arca, carro): a parte da frente da peça é desenhada por cima dos personagens. */
occupied?: boolean;
}[];
};
type Pal = { sky: [string, string]; wall: string; ground: Record<string, string>; far: string; near: string; ink: string; leaf: string; trunk: string; stone: string; light: string };
const P: Record<PaletteId, Pal> = {
night: { sky: ["#0b0e22", "#1c2147"], wall: "#2a2f4a", far: "#2a2d57", near: "#3b3f74", ink: "#0c0d1a", leaf: "#24445a", trunk: "#2b2338", stone: "#5a5f86", light: "#ffc94a",
ground: { grass: "#1d2e3a", street: "#1a1d38", dirt: "#2a2433", floor: "#22243a", sand: "#4a4560", water: "#152a4a" } },
sepia: { sky: ["#c9ad83", "#e8d6ae"], wall: "#7d6a55", far: "#a88f6e", near: "#6e5843", ink: "#2a2018", leaf: "#7b7a45", trunk: "#5a4330", stone: "#9b9387", light: "#ffd98a",
ground: { grass: "#8b8a52", street: "#6a5a4a", dirt: "#7a5a3c", floor: "#5e4c3c", sand: "#d2b886", water: "#6f8a8a" } },
day: { sky: ["#5aa9e6", "#cfeaf8"], wall: "#e9dcc5", far: "#9cc3d9", near: "#d98a5c", ink: "#22252e", leaf: "#4caf50", trunk: "#7a5232", stone: "#a9adb5", light: "#fff3b0",
ground: { grass: "#78c25a", street: "#8a8f99", dirt: "#b88a5a", floor: "#c9a77c", sand: "#f0d79a", water: "#3f9ad8" } },
dusk: { sky: ["#2a2c5c", "#e8946a"], wall: "#4a3a52", far: "#4c3f6e", near: "#6a4a62", ink: "#140f1c", leaf: "#2f4a3f", trunk: "#3a2a2a", stone: "#7a7090", light: "#ffcf7a",
ground: { grass: "#3a4a3a", street: "#3a3348", dirt: "#4a3530", floor: "#3c3040", sand: "#a87d6a", water: "#4a5a8a" } },
gray: { sky: ["#6f7680", "#b4b9bf"], wall: "#565b63", far: "#8a9098", near: "#5c6168", ink: "#1b1d21", leaf: "#5a6b55", trunk: "#4a4038", stone: "#9aa0a8", light: "#f2e6c8",
ground: { grass: "#5f6e55", street: "#4a4f57", dirt: "#5e5246", floor: "#45484f", sand: "#a8a08a", water: "#5a6f80" } },
};
export const palette = (id: PaletteId | undefined): Pal => P[id ?? "night"] ?? P.night;
const W = 1080;
const H = 1920;
const DRAW: Record<string, Draw> = { ...NATURE, ...BUILT, ...INDOOR };
function mix(a: string, b: string, k: number): string {
const pa = parseInt(a.slice(1), 16);
const pb = parseInt(b.slice(1), 16);
const ch = (s: number) => Math.round(((pa >> s) & 255) * (1 - k) + ((pb >> s) & 255) * k);
return `#${[16, 8, 0].map((s) => ch(s).toString(16).padStart(2, "0")).join("")}`;
/** Peças presas na parede do fundo quando o lugar é interno (o z delas é ignorado). */
const WALL_MOUNTED = new Set<ElementKind>(["window", "frame", "door"]);
/** Peças penduradas no teto: a origem é o topo do quadro. */
const CEILING = new Set<ElementKind>(["pendant"]);
/** Objetos de mesa: sobem sozinhos para cima da mesa/escrivaninha mais próxima (se não tiver `lift`). */
const ON_TOP = new Set<ElementKind>(["desklamp"]);
/** Altura do tampo (unidades da peça) das superfícies que recebem objetos de mesa. */
const SURFACE_TOP: Partial<Record<ElementKind, number>> = { desk: 330, table: 304 };
/** Só as peças assimétricas espelham; nas simétricas o `flip` trocaria só o lado da sombra (a luz é sempre da esquerda). */
const FLIPPABLE = new Set<ElementKind>(["deadtree", "palm", "car", "bed", "desklamp", "waves", "clothesline", "outcrop"]);
/** Meia largura da base de cada peça (unidades da peça) para a sombra de contato; 0 = sem sombra. */
const FOOT: Partial<Record<ElementKind, number>> = {
tree: 130, deadtree: 90, pine: 190, bush: 220, rock: 130, bench: 270, lamp: 60, gravestone: 125, cross: 60, fence: 470,
house: 420, building: 280, car: 390, sign: 40, table: 290, bed: 400, shelf: 230, crate: 170, tent: 350, fire: 130,
ark: 380, ark_frame: 380, scaffold: 140, planks: 185, palm: 80, outcrop: 340, cabinet: 185, locker: 330, desk: 340,
wall: 730, facade: 560, shopfront: 460, desklamp: 90, clothesline: 0,
};
const isNight = (id: PaletteId | undefined) => (id ?? "night") === "night";
/** Zoom do fundo pelo enquadramento: em meio corpo/de perto a câmera está mais perto, o fundo cresce junto. */
function backgroundZoom(spec: ShotSpec): number {
const framings = (spec.actors ?? []).flatMap((a) => (a.kind === "person" && a.framing ? [a.framing] : []));
if (framings.includes("close")) return 1.32;
if (framings.includes("medium")) return 1.16;
return 1;
}
/** Uma peça desenhada com a base em (0,0), altura de referência ~300 px. */
function Element({ kind, pal, color, seed }: { kind: ElementKind; pal: Pal; color?: string; seed: number }) {
const r = rng(seed);
switch (kind) {
case "tree": return <g><rect x={-14} y={-150} width={28} height={150} fill={pal.trunk} /><circle cx={0} cy={-210} r={95} fill={color ?? pal.leaf} /><circle cx={-60} cy={-170} r={60} fill={color ?? pal.leaf} /><circle cx={62} cy={-175} r={62} fill={color ?? pal.leaf} /></g>;
case "pine": return <g><rect x={-12} y={-60} width={24} height={60} fill={pal.trunk} /><polygon points="0,-330 -90,-60 90,-60" fill={color ?? pal.leaf} /></g>;
case "deadtree": return <g stroke={color ?? pal.trunk} strokeLinecap="round" fill="none"><path d="M0 0 L0 -220" strokeWidth={26} /><path d="M0 -120 L-70 -200 M-40 -160 L-80 -150 M0 -170 L60 -250 M30 -210 L80 -215 M0 -220 L-20 -280" strokeWidth={12} /></g>;
case "bush": return <g fill={color ?? pal.leaf}><circle cx={-40} cy={-35} r={42} /><circle cx={10} cy={-50} r={52} /><circle cx={55} cy={-30} r={38} /></g>;
case "rock": return <path d="M-70 0 Q-80 -50 -30 -70 Q20 -90 60 -50 Q85 -20 70 0 Z" fill={color ?? pal.stone} />;
case "mountain": return <g><polygon points="-520,0 0,-520 520,0" fill={color ?? pal.far} /><polygon points="-110,-410 0,-520 110,-410 50,-430 0,-400 -50,-430" fill="#ffffff" opacity={0.6} /></g>;
case "cloud": return <g fill={color ?? "#ffffff"} opacity={0.85}><ellipse cx={0} cy={-40} rx={110} ry={40} /><circle cx={-40} cy={-70} r={45} /><circle cx={30} cy={-80} r={55} /></g>;
case "bench": return <g fill={color ?? "#8a5a3a"}><rect x={-110} y={-70} width={220} height={16} rx={4} /><rect x={-110} y={-120} width={220} height={14} rx={4} /><rect x={-95} y={-70} width={12} height={70} fill={pal.ink} /><rect x={83} y={-70} width={12} height={70} fill={pal.ink} /></g>;
case "lamp": return <g><rect x={-7} y={-420} width={14} height={420} fill={pal.ink} /><rect x={-36} y={-440} width={72} height={26} rx={8} fill={pal.ink} /><ellipse cx={0} cy={-408} rx={26} ry={8} fill={pal.light} /><path d="M-24 -408 L-140 0 L140 0 L24 -408 Z" fill={pal.light} opacity={0.08} /></g>;
case "gravestone": return <g><path d="M-55 0 L-55 -130 Q-55 -185 0 -185 Q55 -185 55 -130 L55 0 Z" fill={color ?? pal.stone} /><rect x={-28} y={-120} width={56} height={6} rx={3} fill={pal.ink} opacity={0.35} /><rect x={-22} y={-100} width={44} height={6} rx={3} fill={pal.ink} opacity={0.35} /></g>;
case "cross": return <g fill={color ?? pal.stone}><rect x={-12} y={-200} width={24} height={200} /><rect x={-60} y={-160} width={120} height={22} /></g>;
case "fence": return <g fill={color ?? pal.ink}>{Array.from({ length: 9 }, (_, i) => <rect key={i} x={-200 + i * 50} y={-130} width={14} height={130} />)}<rect x={-210} y={-110} width={430} height={10} /><rect x={-210} y={-50} width={430} height={10} /></g>;
case "house": return <g><polygon points="-150,-180 0,-290 150,-180" fill={pal.ink} opacity={0.6} /><rect x={-140} y={-180} width={280} height={180} fill={color ?? pal.near} /><rect x={-110} y={-140} width={50} height={50} rx={4} fill={pal.light} opacity={r() > 0.5 ? 1 : 0.15} /><rect x={60} y={-140} width={50} height={50} rx={4} fill={pal.light} opacity={r() > 0.5 ? 1 : 0.15} /><rect x={-25} y={-100} width={50} height={100} fill={pal.ink} opacity={0.7} /></g>;
case "building": {
const floors = 4 + Math.floor(r() * 4);
return <g><rect x={-120} y={-floors * 80} width={240} height={floors * 80} fill={color ?? pal.far} />{Array.from({ length: floors * 3 }, (_, i) => <rect key={i} x={-95 + (i % 3) * 70} y={-floors * 80 + 20 + Math.floor(i / 3) * 80} width={44} height={40} fill={pal.light} opacity={r() > 0.7 ? 0.9 : 0.12} />)}</g>;
type El = Place["elements"][number] & { i: number; z: number };
type Placed = { e: El; x: number; y: number; s: number; zEff: number; flip: boolean };
type Layout = { horizon: number; indoor: boolean; zoom: number; items: Placed[] };
/** Onde cada peça fica (base, escala, profundidade efetiva). A camada de luz usa a mesma conta. */
export function layoutPlace(spec: ShotSpec): Layout {
const place = spec.place!;
const indoor = !!place.indoor;
const horizon = (place.horizon ?? (indoor ? 0.62 : 0.56)) * H;
const near = indoor ? H * 0.8 : H * 0.72;
const items: Placed[] = place.elements.map((raw, i) => {
const e: El = { ...raw, i, z: raw.z ?? 0.3 };
const wall = indoor && WALL_MOUNTED.has(e.kind);
const zEff = wall ? 1 : e.z;
const depth = 1 - zEff * (indoor ? 0.35 : 0.62);
const s = (e.scale ?? 1) * depth * 1.15;
let y: number;
if (CEILING.has(e.kind)) y = 0;
else if (e.kind === "cloud") y = horizon * (0.15 + 0.5 * e.z);
else y = horizon + (1 - zEff) * (near - horizon);
y -= (e.lift ?? 0) * H;
return { e, x: e.x * W, y, s, zEff, flip: !!e.flip && FLIPPABLE.has(e.kind) };
});
// Objeto de mesa perto de uma mesa (mesma profundidade, dentro do tampo) vai para cima dela.
for (const it of items) {
if (!ON_TOP.has(it.e.kind) || it.e.lift !== undefined) continue;
const surface = items.find((o) => SURFACE_TOP[o.e.kind] && Math.abs(o.e.z - it.e.z) <= 0.25 && Math.abs(o.x - it.x) < (FOOT[o.e.kind] ?? 0) * o.s);
if (!surface) continue;
it.y = surface.y - SURFACE_TOP[surface.e.kind]! * surface.s;
it.s = surface.s * (it.e.scale ?? 1) * 0.9;
it.zEff = surface.zEff - 0.001;
}
case "car": return <g><path d="M-150 -40 L-150 -90 Q-140 -110 -100 -112 L-60 -160 L70 -160 L110 -112 L150 -100 L150 -40 Z" fill={color ?? "#c8443a"} /><rect x={-50} y={-150} width={50} height={36} fill="#cfe3f3" opacity={0.85} /><rect x={8} y={-150} width={52} height={36} fill="#cfe3f3" opacity={0.85} /><circle cx={-90} cy={-35} r={32} fill={pal.ink} /><circle cx={95} cy={-35} r={32} fill={pal.ink} /></g>;
case "sign": return <g><rect x={-6} y={-220} width={12} height={220} fill={pal.ink} /><rect x={-90} y={-260} width={180} height={70} rx={8} fill={color ?? "#2f6d3a"} stroke="#ffffff" strokeWidth={5} /></g>;
case "door": return <g><rect x={-80} y={-330} width={160} height={330} rx={4} fill={color ?? "#4a2f22"} /><rect x={-60} y={-305} width={120} height={130} rx={3} fill="#000000" opacity={0.15} /><rect x={-60} y={-155} width={120} height={130} rx={3} fill="#000000" opacity={0.15} /><circle cx={52} cy={-165} r={9} fill="#e6c27a" /></g>;
case "window": return <g><rect x={-120} y={-260} width={240} height={200} rx={6} fill={pal.ink} /><rect x={-108} y={-248} width={216} height={176} fill={color ?? mix(pal.sky[0], pal.sky[1], 0.5)} /><rect x={-4} y={-248} width={8} height={176} fill={pal.ink} /><rect x={-108} y={-164} width={216} height={8} fill={pal.ink} /></g>;
case "table": return <g fill={color ?? "#7a5232"}><rect x={-140} y={-130} width={280} height={20} rx={4} /><rect x={-120} y={-110} width={18} height={110} /><rect x={102} y={-110} width={18} height={110} /></g>;
case "bed": return <g><rect x={-170} y={-90} width={340} height={60} rx={10} fill={color ?? "#5a6aa8"} /><rect x={-170} y={-150} width={24} height={150} fill={pal.trunk} /><rect x={-140} y={-120} width={90} height={34} rx={12} fill="#eeeeee" /><rect x={146} y={-110} width={24} height={110} fill={pal.trunk} /></g>;
case "shelf": return <g><rect x={-120} y={-360} width={240} height={360} fill={color ?? pal.trunk} />{[0, 1, 2, 3].map((i) => <g key={i}><rect x={-108} y={-340 + i * 88} width={216} height={70} fill="#000000" opacity={0.25} />{[0, 1, 2, 3, 4].map((j) => <rect key={j} x={-100 + j * 42} y={-330 + i * 88 + (r() * 14)} width={30} height={56 - (r() * 14)} rx={3} fill={["#e8463d", "#f2c230", "#4fb0e8", "#5cc48a", "#e8e8ee"][(i + j) % 5]} />)}</g>)}</g>;
case "crate": return <g><rect x={-70} y={-140} width={140} height={140} fill={color ?? "#a0743f"} /><path d="M-70 -140 L70 0 M70 -140 L-70 0" stroke="#6e4e28" strokeWidth={10} /><rect x={-70} y={-140} width={140} height={140} fill="none" stroke="#6e4e28" strokeWidth={10} /></g>;
case "tent": return <g><polygon points="-170,0 0,-220 170,0" fill={color ?? "#d9773a"} /><polygon points="-40,0 0,-120 40,0" fill={pal.ink} opacity={0.6} /></g>;
case "fire": return <g><rect x={-60} y={-18} width={120} height={18} rx={6} fill={pal.trunk} /><path d="M-40 -18 Q-50 -80 -10 -120 Q-5 -80 20 -70 Q30 -110 10 -150 Q70 -100 45 -18 Z" fill="#ff8a2a" /><path d="M-15 -18 Q-20 -60 5 -80 Q10 -50 25 -45 Q30 -30 20 -18 Z" fill="#ffd34a" /></g>;
items.sort((a, b) => b.zEff - a.zEff || a.e.i - b.e.i);
return { horizon, indoor, zoom: backgroundZoom(spec), items };
}
/** Sol/lua no céu (sempre do lado esquerdo: é de lá que vem a luz das peças). */
export function sunOf(id: PaletteId | undefined, horizon: number): { x: number; y: number; r: number } | null {
switch (id ?? "night") {
case "day": return { x: W * 0.2, y: H * 0.2, r: 66 };
case "sepia": return { x: W * 0.2, y: H * 0.19, r: 70 };
case "dusk": return { x: W * 0.2, y: horizon - H * 0.13, r: 96 };
case "night": return { x: W * 0.22, y: H * 0.15, r: 44 };
default: return null;
}
}
export function PlaceBackground({ spec, frame }: { spec: ShotSpec; frame: number }) {
/** Altura da superfície da água no instante (fração da altura; null = sem enchente). */
export function floodLevel(place: Place | undefined, progress: number): number | null {
if (!place?.flood) return null;
const p = Math.max(0, Math.min(1, progress));
const k = p < 0.5 ? 2 * p * p : 1 - (-2 * p + 2) ** 2 / 2;
return place.flood.from + (place.flood.to - place.flood.from) * k;
}
/** Uma peça no lugar: sombra de contato + desenho com a tinta da profundidade dela. */
function PlacedElement({ it, pal, spec, hazeColor, y, rot = 0, part }: { it: Placed; pal: Pal; spec: ShotSpec; hazeColor: string; y?: number; rot?: number; part?: "front" }) {
const { e } = it;
const place = spec.place!;
const indoor = !!place.indoor;
const z = it.zEff;
const sky = e.kind === "cloud" || e.kind === "rainbow";
const haze = sky ? 0.12 : indoor ? z * 0.22 : Math.min(0.85, Math.pow(z, 1.8) * 0.66 + (place.fog ? 0.04 + z * 0.16 : 0));
const front = !sky && z < 0.25 ? (0.25 - z) * 0.5 : 0;
const p = makePaint(pal, rng(spec.seed + e.i * 17), { haze, hazeColor, front, indoor, night: isNight(spec.palette) });
const draw = part === "front" ? FRONT_PART[e.kind] : DRAW[e.kind];
if (!draw) return null;
const foot = (CEILING.has(e.kind) || (indoor && WALL_MOUNTED.has(e.kind)) || e.float || (e.lift ?? 0) > 0.02) ? 0 : FOOT[e.kind] ?? 0;
const s = it.s;
return (
<g transform={`translate(${it.x} ${y ?? it.y}) rotate(${rot}) scale(${it.flip ? -s : s} ${s})`}>
{foot > 0 && part !== "front" && <ellipse cx={foot * 0.1} cy={4} rx={foot * 1.12} ry={Math.min(46, Math.max(16, foot * 0.11))} fill="url(#cShadow)" opacity={1 - z * 0.5} />}
{draw(p, e.color)}
</g>
);
}
/** Céu com degradê rico, sol/lua com halo (ou parede do interior). Não muda com o quadro. */
function SkyLayer({ spec, horizon }: { spec: ShotSpec; horizon: number }) {
const pal = palette(spec.palette);
const place = spec.place!;
if (place.indoor) {
const wallTop = mix(pal.wall, pal.ink, 0.42);
return <g>
<defs>
<linearGradient id="placeWall" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor={wallTop} /><stop offset="0.45" stopColor={mix(pal.wall, pal.ink, 0.12)} /><stop offset="1" stopColor={pal.wall} />
</linearGradient>
<linearGradient id="placeCorner" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stopColor={pal.shade} stopOpacity={0.4} /><stop offset="0.16" stopColor={pal.shade} stopOpacity={0} />
<stop offset="0.84" stopColor={pal.shade} stopOpacity={0} /><stop offset="1" stopColor={pal.shade} stopOpacity={0.45} />
</linearGradient>
</defs>
<rect width={W} height={H} fill="url(#placeWall)" />
</g>;
}
const sun = sunOf(spec.palette, horizon);
const night = isNight(spec.palette);
return <g>
<defs>
<linearGradient id="placeSky" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="0" y2={horizon}>
<stop offset="0" stopColor={pal.sky[0]} /><stop offset="0.55" stopColor={pal.sky[1]} /><stop offset="1" stopColor={pal.sky[2]} />
</linearGradient>
{sun && <radialGradient id="placeHalo" gradientUnits="userSpaceOnUse" cx={sun.x} cy={sun.y} r={sun.r * 4.2}>
<stop offset="0" stopColor={pal.halo} stopOpacity={night ? 0.35 : 0.75} /><stop offset="0.35" stopColor={pal.halo} stopOpacity={night ? 0.12 : 0.3} />
<stop offset="1" stopColor={pal.halo} stopOpacity={0} />
</radialGradient>}
</defs>
<rect width={W} height={H} fill="url(#placeSky)" />
{sun && <>
<circle cx={sun.x} cy={sun.y} r={sun.r * 4.2} fill="url(#placeHalo)" />
<circle cx={sun.x} cy={sun.y} r={sun.r} fill={pal.sun} />
{night
? <><circle cx={sun.x + 12} cy={sun.y - 8} r={9} fill={mix(pal.sun, "#b0a890", 0.4)} /><circle cx={sun.x - 14} cy={sun.y + 12} r={6} fill={mix(pal.sun, "#b0a890", 0.4)} /></>
: <circle cx={sun.x - sun.r * 0.25} cy={sun.y - sun.r * 0.25} r={sun.r * 0.55} fill="#ffffff" opacity={0.35} />}
</>}
</g>;
}
/** Chão (degradê + textura) e, ao fundo, a silhueta distante (morros ou cidade). */
function GroundLayer({ spec, horizon, hazeColor }: { spec: ShotSpec; horizon: number; hazeColor: string }) {
const place = spec.place!;
const pal = palette(spec.palette);
const horizon = (place.horizon ?? 0.56) * H;
const rand = rng(spec.seed + 29);
const out: React.ReactNode[] = [];
const g = place.ground === "none" ? null : pal.ground[place.ground];
const span = H - horizon;
if (place.indoor) {
// Parede: lambri (meia-parede) ou listras, conforme a semente; rodapé no pé da parede.
const wall = pal.wall;
if (spec.seed % 2 === 0) {
const top = horizon - H * 0.17;
out.push(<rect key="dado" x={0} y={top} width={W} height={horizon - top} fill={mix(wall, pal.ink, 0.16)} />);
out.push(<path key="dadoP" d={Array.from({ length: 8 }, (_, i) => `M${i * 150 + 40} ${top + 30} L${i * 150 + 40} ${horizon - 40} L${i * 150 + 150} ${horizon - 40}`).join(" ")}
stroke={mix(wall, pal.ink, 0.3)} strokeWidth={6} fill="none" />);
out.push(<rect key="rail" x={0} y={top - 16} width={W} height={18} fill={mix(wall, pal.light, 0.22)} />);
out.push(<rect key="railS" x={0} y={top + 2} width={W} height={6} fill={mix(wall, pal.ink, 0.35)} />);
} else {
out.push(<path key="stripes" d={Array.from({ length: 12 }, (_, i) => `M${i * 96 + 30} 0 L${i * 96 + 30} ${horizon}`).join(" ")} stroke={mix(wall, pal.ink, 0.1)} strokeWidth={26} />);
}
out.push(<rect key="corner" x={0} y={0} width={W} height={horizon} fill="url(#placeCorner)" />);
} else if (place.ground === "grass" || place.ground === "dirt" || place.ground === "sand") {
// Morros distantes em 2 camadas, bem apagados (plano de fundo).
const ridge = (h: number, amp: number, seed: number) => {
const r = rng(seed);
let d = `M0 ${horizon + 2} L0 ${horizon - h}`;
for (let x = 0; x <= W + 180; x += 180) d += ` Q${x + 90} ${horizon - h - amp * (0.4 + r())} ${x + 180} ${horizon - h + (r() - 0.5) * amp * 0.5}`;
return d + ` L${W} ${horizon + 2} Z`;
};
out.push(<path key="r1" d={ridge(H * 0.075, H * 0.05, spec.seed + 3)} fill={mix(pal.far, hazeColor, 0.55)} />);
out.push(<path key="r2" d={ridge(H * 0.03, H * 0.03, spec.seed + 7)} fill={mix(g ?? pal.far, hazeColor, 0.45)} />);
} else if (place.ground === "street") {
// Cidade ao longe: blocos apagados com algumas janelas.
let x = -20;
const blocks: React.ReactNode[] = [];
while (x < W) {
const w = 90 + rand() * 120;
const h = H * (0.05 + rand() * 0.09);
blocks.push(<rect key={x} x={x} y={horizon - h} width={w} height={h + 2} fill={mix(pal.far, hazeColor, 0.5 + rand() * 0.15)} />);
x += w - 6;
}
out.push(<g key="city">{blocks}</g>);
}
if (g) {
out.push(<rect key="ground" x={0} y={horizon} width={W} height={span} fill="url(#placeGround)" />);
if (place.ground === "floor") {
// Tábuas em perspectiva: linhas que fogem para o ponto de fuga, juntas desencontradas, tom alternado.
const vpY = horizon - H * 0.3;
const k = (H - vpY) / (horizon - vpY);
const at = (xh: number, y: number) => W / 2 + (xh - W / 2) * ((y - vpY) / (horizon - vpY));
const n = 16;
const step = W / 9;
let seams = "";
for (let i = -n; i <= n; i++) {
const xh = W / 2 + i * step * 0.5;
if (Math.abs(i) % 2 === 1) {
const x2 = W / 2 + (i + 1) * step * 0.5;
out.push(<polygon key={`pl${i}`} points={`${xh},${horizon} ${x2},${horizon} ${W / 2 + (x2 - W / 2) * k},${H} ${W / 2 + (xh - W / 2) * k},${H}`} fill={mix(g, pal.ink, 0.06)} />);
}
seams += `M${xh} ${horizon} L${W / 2 + (xh - W / 2) * k} ${H} `;
for (let j = 0; j < 3; j++) {
const y = horizon + span * Math.pow(rand(), 1.4);
const xa = at(xh, y);
const xb = at(xh + step * 0.5, y);
seams += `M${xa} ${y} L${xb} ${y} `;
}
}
out.push(<path key="seams" d={seams} stroke={mix(g, pal.ink, 0.32)} strokeWidth={4} fill="none" />);
out.push(<rect key="base" x={0} y={horizon - 34} width={W} height={36} fill={mix(pal.wall, pal.ink, 0.38)} />);
out.push(<rect key="baseT" x={0} y={horizon - 34} width={W} height={7} fill={mix(pal.wall, pal.light, 0.15)} />);
out.push(<rect key="ao" x={0} y={horizon} width={W} height={26} fill={pal.ink} opacity={0.18} />);
} else if (place.ground === "street") {
const walk = horizon + span * 0.16;
const walkC = mix(mix("#d2c8b4", g, 0.3), hazeColor, 0.15);
out.push(<rect key="walk" x={0} y={horizon} width={W} height={walk - horizon} fill={walkC} />);
out.push(<path key="tiles" d={Array.from({ length: 14 }, (_, i) => { const x = -120 + i * 110; return `M${x} ${horizon} L${W / 2 + (x - W / 2) * 1.25} ${walk}`; }).join(" ") + ` M0 ${(horizon + walk) / 2} L${W} ${(horizon + walk) / 2}`}
stroke={mix(walkC, pal.ink, 0.18)} strokeWidth={3} fill="none" />);
out.push(<rect key="curb" x={0} y={walk} width={W} height={18} fill={mix(walkC, pal.light, 0.25)} />);
out.push(<rect key="curbS" x={0} y={walk + 18} width={W} height={20} fill={mix(g, pal.ink, 0.35)} />);
const lane = walk + (H - walk) * 0.42;
out.push(<path key="lane" d={Array.from({ length: 7 }, (_, i) => `M${i * 190 - 60} ${lane} l120 0`).join(" ")} stroke="#f2ecd8" strokeWidth={12} opacity={0.55} />);
} else if (place.ground === "grass" || place.ground === "dirt" || place.ground === "sand") {
// Faixas na perspectiva + tufos/pedrinhas/ondulações, maiores perto da câmera.
for (let b = 1; b < 6; b++) {
const y0 = horizon + span * Math.pow(b / 6, 1.7);
const y1 = horizon + span * Math.pow((b + 0.45) / 6, 1.7);
out.push(<rect key={`band${b}`} x={0} y={y0} width={W} height={y1 - y0} fill={b % 2 ? mix(g, pal.light, 0.06) : mix(g, pal.ink, 0.05)} opacity={0.45} />);
}
let marks = "";
for (let i = 0; i < 46; i++) {
const t = Math.pow(rand(), 0.8);
const y = horizon + span * t;
const x = rand() * W;
const s = 6 + t * 26;
if (place.ground === "grass") marks += `M${x - s} ${y} L${x - s * 0.3} ${y - s * 1.4} L${x} ${y} L${x + s * 0.4} ${y - s * 1.6} L${x + s} ${y} `;
else if (place.ground === "sand") marks += `M${x - s * 3} ${y} Q${x} ${y - s * 0.6} ${x + s * 3} ${y} `;
else marks += `M${x - s * 0.6} ${y} a${s * 0.6} ${s * 0.28} 0 1 0 ${s * 1.2} 0 a${s * 0.6} ${s * 0.28} 0 1 0 ${-s * 1.2} 0 `;
}
out.push(<path key="marks" d={marks} fill={place.ground === "dirt" ? mix(g, pal.ink, 0.14) : "none"}
stroke={place.ground === "grass" ? mix(g, pal.ink, 0.25) : place.ground === "sand" ? mix(g, pal.light, 0.35) : "none"} strokeWidth={place.ground === "sand" ? 5 : 4} strokeLinejoin="round" />);
}
}
return <g>{out}</g>;
}
export function PlaceBackground({ spec, frame, progress = 0 }: { spec: ShotSpec; frame: number; progress?: number }) {
const place = spec.place!;
const pal = palette(spec.palette);
const layout = React.useMemo(() => layoutPlace(spec), [spec]);
const { horizon, zoom } = layout;
const hazeColor = place.indoor ? pal.wall : mix(mix(pal.sky[2], pal.sky[1], 0.25), "#c8ccd6", place.fog ? 0.45 : 0);
const level = floodLevel(place, progress);
const waterY = level === null ? null : level * H;
const storm = place.weather === "storm";
const ground = place.ground === "none" ? null : pal.ground[place.ground];
const elements = [...place.elements].map((e, i) => ({ ...e, i, z: e.z ?? 0.3 })).sort((a, b) => b.z - a.z);
// Tudo que não muda com o quadro é desenhado uma vez só (céu, chão, peças paradas).
const sky = React.useMemo(() => <SkyLayer spec={spec} horizon={horizon} />, [spec, horizon]);
const floating = (it: Placed) => !!it.e.float && waterY !== null;
const staticBack = React.useMemo(() => (
<g>
<GroundLayer spec={spec} horizon={horizon} hazeColor={hazeColor} />
{layout.items.filter((it) => !(it.e.float && place.flood)).map((it) => <PlacedElement key={it.e.i} it={it} pal={pal} spec={spec} hazeColor={hazeColor} />)}
</g>
), [spec, layout]); // eslint-disable-line react-hooks/exhaustive-deps
const rand = rng(spec.seed + 13);
const stars = !place.indoor && (spec.palette ?? "night") === "night"
const stars = !place.indoor && isNight(spec.palette)
? Array.from({ length: 60 }, () => ({ x: rand() * W, y: rand() * horizon * 0.8, r: 1 + rand() * 2, p: rand() * 6 })) : [];
const zoomT = zoom === 1 ? undefined : `translate(${W / 2} ${horizon}) scale(${zoom}) translate(${-W / 2} ${-horizon})`;
return (
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice">
<defs>
<linearGradient id="placeSky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor={pal.sky[0]} /><stop offset="1" stopColor={pal.sky[1]} /></linearGradient>
<linearGradient id="placeFog" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#ffffff" stopOpacity={0} /><stop offset="1" stopColor="#d8dce6" stopOpacity={0.35} /></linearGradient>
<linearGradient id="placeFog" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#ffffff" stopOpacity={0} />
<stop offset="0.3" stopColor="#d8dce6" stopOpacity={0.3} /><stop offset="1" stopColor="#d8dce6" stopOpacity={0.06} /></linearGradient>
<radialGradient id="cShadow"><stop offset="0" stopColor={pal.ink} stopOpacity={0.5} /><stop offset="0.6" stopColor={pal.ink} stopOpacity={0.28} /><stop offset="1" stopColor={pal.ink} stopOpacity={0} /></radialGradient>
{ground && <linearGradient id="placeGround" x1="0" y1="0" x2="0" y2="1">
{place.indoor
? <><stop offset="0" stopColor={mix(ground, pal.ink, 0.3)} /><stop offset="0.18" stopColor={ground} /><stop offset="1" stopColor={mix(ground, pal.ink, 0.32)} /></>
: <><stop offset="0" stopColor={mix(ground, hazeColor, 0.35)} /><stop offset="0.3" stopColor={ground} /><stop offset="1" stopColor={mix(ground, pal.ink, 0.22)} /></>}
</linearGradient>}
<linearGradient id="placeWater" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor={mix(pal.ground.water, "#ffffff", 0.12)} /><stop offset="1" stopColor={mix(pal.ground.water, pal.ink, 0.35)} /></linearGradient>
</defs>
<rect width={W} height={H} fill={place.indoor ? pal.wall : "url(#placeSky)"} />
{sky}
{stars.map((s, i) => <circle key={i} cx={s.x} cy={s.y} r={s.r} fill="#fff" opacity={0.3 + 0.3 * Math.sin(frame / 12 + s.p)} />)}
{!place.indoor && (spec.palette ?? "night") === "night" && <circle cx={W * 0.78} cy={H * 0.12} r={40} fill="#f4ecc8" />}
{!place.indoor && (spec.palette === "day" || spec.palette === "sepia") && <circle cx={W * 0.8} cy={H * 0.1} r={60} fill={pal.light} opacity={0.9} />}
{place.indoor && <rect x={0} y={horizon - 18} width={W} height={18} fill={pal.ink} opacity={0.25} />}
{ground && <rect x={0} y={horizon} width={W} height={H - horizon} fill={ground} />}
{place.ground === "street" && Array.from({ length: 8 }, (_, i) => <rect key={i} x={i * 150 - 40} y={horizon + (H - horizon) * 0.32} width={90} height={9} rx={4} fill="#ffffff" opacity={0.25} />)}
{elements.map((e) => {
// Profundidade: mais ao fundo = mais perto do horizonte, menor e mais apagado (névoa/atmosfera).
const baseY = e.kind === "cloud" ? horizon * (0.15 + 0.5 * e.z) : horizon + (1 - e.z) * (H * 0.72 - horizon);
const scale = (e.scale ?? 1) * (1 - e.z * 0.62) * 1.15;
const fade = e.kind === "cloud" ? 0 : e.z * (place.fog ? 0.7 : 0.35);
return (
<g key={e.i} transform={`translate(${e.x * W} ${baseY}) scale(${e.flip ? -scale : scale} ${scale})`} opacity={1 - fade * 0.3}>
<Element kind={e.kind} pal={pal} color={e.color ?? (fade > 0.05 && e.kind !== "fire" ? undefined : undefined)} seed={spec.seed + e.i * 17} />
<g transform={zoomT}>
{staticBack}
{waterY !== null && (
<g>
<rect x={0} y={waterY} width={W} height={H - waterY} fill="url(#placeWater)" />
<path d={`M0 ${waterY} ${Array.from({ length: 10 }, (_, i) => `Q${i * 108 + 54} ${waterY - 22 + Math.sin(frame / 9 + i) * 8} ${(i + 1) * 108} ${waterY}`).join(" ")}`}
stroke="#ffffff" strokeWidth={7} fill="none" opacity={0.55} />
</g>
);
})}
{place.fog && <rect x={0} y={horizon - H * 0.15} width={W} height={H * 0.5} fill="url(#placeFog)" />}
)}
{place.ground === "water" && waterY === null && Array.from({ length: 6 }, (_, i) => (
<path key={`w${i}`} d={`M${((i * 197 + frame * 2) % (W + 200)) - 100} ${horizon + 60 + i * ((H - horizon) / 6)} q30 -16 60 0 q30 16 60 0`} stroke="#ffffff" strokeWidth={5} fill="none" opacity={0.35} />
))}
{layout.items.filter(floating).map((it) => (
// Boia: a quilha fica um pouco abaixo da superfície e a peça balança com a água.
<PlacedElement key={it.e.i} it={it} pal={pal} spec={spec} hazeColor={hazeColor}
y={waterY! + H * 0.035 + Math.sin(frame / 14 + it.e.i) * 9} rot={Math.sin(frame / 22 + it.e.i) * (storm ? 3.5 : 1.6)} />
))}
{waterY !== null && <rect x={0} y={waterY + H * 0.03} width={W} height={H} fill={pal.ground.water} opacity={0.35} />}
</g>
{place.fog && <rect x={0} y={horizon - H * 0.18} width={W} height={H - horizon + H * 0.18} fill="url(#placeFog)" />}
</svg>
);
}
/** Foco de luz vindo do teto (bunker, interrogatório) ou vinheta de anoitecer, por cima de tudo. */
export function LightLayer({ light, palette: id }: { light: ShotSpec["light"]; palette?: PaletteId }) {
if (!light || light === "none") return null;
const pal = palette(id);
if (light === "vignette") {
return <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at 50% 45%, rgba(0,0,0,0) 45%, rgba(0,0,0,0.55) 100%)" }} />;
type LightSpot = { kind: "lamp" | "window" | "sun" | "glow"; x: number; y: number; w?: number; h?: number; spread?: number; fixture?: boolean };
/** Fonte de luz do trecho: a escolhida no spec, ou deduzida das peças (luminária > janela > sol). */
export function resolveLight(spec: ShotSpec | undefined, light: ShotSpec["light"]): LightSpot | null {
if (light === "none") return null;
const src = spec?.lightSource;
if (src) {
const dy = src.kind === "lamp" ? 0.2 : src.kind === "window" ? 0.32 : 0.2;
return { kind: src.kind, x: src.x * W, y: (src.y ?? dy) * H, w: W * 0.3, h: H * 0.18 };
}
const place = spec?.scene.kind === "place" ? spec.place : undefined;
const layout = place ? layoutPlace(spec!) : null;
const toScreen = (x: number, y: number) => layout && layout.zoom !== 1
? { x: W / 2 + (x - W / 2) * layout.zoom, y: layout.horizon + (y - layout.horizon) * layout.zoom } : { x, y };
const pendant = layout?.items.find((it) => it.e.kind === "pendant");
if (pendant && (light === "spot" || light === undefined)) {
const z = layout!.zoom;
const b = toScreen(pendant.x, pendant.y + 376 * pendant.s);
return { kind: "lamp", x: b.x, y: b.y, spread: 130 * pendant.s * z };
}
// Luminária de mesa acesa: brilho quente em volta da cúpula, o resto do lugar no escuro.
const desk = layout?.items.find((it) => it.e.kind === "desklamp");
if (desk && light === undefined) {
const k = desk.flip ? -1 : 1;
const a = toScreen(desk.x + k * 40 * desk.s, desk.y - 130 * desk.s);
return { kind: "glow", x: a.x, y: a.y, spread: 420 * desk.s * layout!.zoom };
}
if (light === "spot") return { kind: "lamp", x: W / 2, y: H * 0.045, spread: W * 0.07, fixture: true };
if (light !== undefined || !place || !layout) return null;
if (place.indoor) {
const win = layout.items.find((it) => it.e.kind === "window");
if (!win) return null;
const a = toScreen(win.x - 186 * win.s, win.y - 616 * win.s);
const b = toScreen(win.x + 186 * win.s, win.y - 244 * win.s);
return { kind: "window", x: (a.x + b.x) / 2, y: (a.y + b.y) / 2, w: b.x - a.x, h: b.y - a.y };
}
const sun = sunOf(spec!.palette, layout.horizon);
if (!sun || isNight(spec!.palette)) return null;
return { kind: "sun", x: sun.x, y: sun.y };
}
/**
* Luz por cima de tudo (inclusive dos personagens). Fonte POSICIONADA: luminária (cone + poça no chão), janela
* (raios em diagonal + manchas no piso) ou sol (brilho quente). Contraste quente (luz) × frio (sombra).
* `light: "vignette"` escurece as bordas; `"none"` desliga; sem `light`, a fonte sai das peças do lugar.
*/
export function LightLayer({ light, palette: id, spec }: { light: ShotSpec["light"]; palette?: PaletteId; spec?: ShotSpec }) {
const pal = palette(id ?? spec?.palette);
const src = resolveLight(spec, light);
const vignette = light === "vignette";
if (!src && !vignette) return null;
const indoor = !!spec?.place?.indoor;
const horizon = spec?.place ? (spec.place.horizon ?? (indoor ? 0.62 : 0.56)) * H : H * 0.6;
const night = isNight(id ?? spec?.palette);
const warm = night && src?.kind === "window" ? "#a8c0ff" : pal.light;
const layers: React.ReactNode[] = [];
const defs: React.ReactNode[] = [];
if (src?.kind === "lamp") {
const floorY = indoor || !spec?.place ? Math.max(src.y + H * 0.3, horizon + (H - horizon) * 0.55) : H * 0.84;
const sw = src.spread ?? W * 0.08;
const spread = (floorY - src.y) * 0.42 + sw;
defs.push(<linearGradient key="c" id="lgCone" gradientUnits="userSpaceOnUse" x1="0" y1={src.y} x2="0" y2={floorY}>
<stop offset="0" stopColor={warm} stopOpacity={0.42} /><stop offset="1" stopColor={warm} stopOpacity={0.06} /></linearGradient>);
defs.push(<radialGradient key="p" id="lgPool"><stop offset="0" stopColor={warm} stopOpacity={0.4} /><stop offset="1" stopColor={warm} stopOpacity={0} /></radialGradient>);
defs.push(<radialGradient key="d" id="lgDark" gradientUnits="userSpaceOnUse" cx={src.x} cy={(src.y + floorY) / 2} r={H * 0.62}>
<stop offset="0.3" stopColor={pal.shade} stopOpacity={0} /><stop offset="1" stopColor={pal.shade} stopOpacity={0.62} /></radialGradient>);
layers.push(<rect key="dark" width={W} height={H} fill="url(#lgDark)" />);
layers.push(<polygon key="cone" points={`${src.x - sw * 0.92},${src.y} ${src.x + sw * 0.92},${src.y} ${src.x + spread},${floorY} ${src.x - spread},${floorY}`} fill="url(#lgCone)" />);
layers.push(<ellipse key="pool" cx={src.x} cy={floorY} rx={spread * 1.15} ry={spread * 0.2} fill="url(#lgPool)" />);
if (src.fixture) {
layers.push(<path key="fx" d={`M${src.x - sw} ${src.y} Q${src.x - sw * 0.9} ${src.y - 60} ${src.x} ${src.y - 64} Q${src.x + sw * 0.9} ${src.y - 60} ${src.x + sw} ${src.y} Z`} fill={mix(pal.ink, "#4a5270", 0.5)} />);
layers.push(<ellipse key="fxl" cx={src.x} cy={src.y} rx={sw} ry={12} fill={warm} />);
}
} else if (src?.kind === "window") {
const ww = src.w ?? W * 0.3;
const wh = src.h ?? H * 0.18;
const x0 = src.x - ww / 2;
const y0 = src.y - wh / 2;
const dir = src.x < W / 2 ? 1 : -1;
const vx = dir * W * 0.78;
const vy = H * 0.55;
const pane = (a: number, b: number) => {
// Retângulo da vidraça arrastado na direção dos raios (contorno convexo).
const xa = x0 + ww * a;
const xb = x0 + ww * b;
const [l, r] = dir > 0 ? [xa, xb] : [xb, xa];
return `${l},${y0} ${r},${y0} ${r + vx},${y0 + vy} ${r + vx},${y0 + wh + vy} ${l + vx},${y0 + wh + vy} ${l},${y0 + wh}`;
};
defs.push(<linearGradient key="b" id="lgBeam" gradientUnits="userSpaceOnUse" x1={src.x} y1={src.y} x2={src.x + vx} y2={src.y + vy}>
<stop offset="0" stopColor={warm} stopOpacity={night ? 0.16 : 0.34} /><stop offset="1" stopColor={warm} stopOpacity={0} /></linearGradient>);
defs.push(<radialGradient key="g" id="lgGlow" gradientUnits="userSpaceOnUse" cx={src.x} cy={src.y} r={W * 0.75}>
<stop offset="0" stopColor={warm} stopOpacity={night ? 0.12 : 0.24} /><stop offset="1" stopColor={warm} stopOpacity={0} /></radialGradient>);
defs.push(<linearGradient key="k" id="lgCool" x1={dir > 0 ? 1 : 0} y1="0" x2={dir > 0 ? 0 : 1} y2="0">
<stop offset="0" stopColor={pal.shade} stopOpacity={0.4} /><stop offset="0.6" stopColor={pal.shade} stopOpacity={0} /></linearGradient>);
layers.push(<rect key="cool" width={W} height={H} fill="url(#lgCool)" />);
layers.push(<rect key="glow" width={W} height={H} fill="url(#lgGlow)" />);
layers.push(<polygon key="b1" points={pane(0, 0.47)} fill="url(#lgBeam)" />);
layers.push(<polygon key="b2" points={pane(0.53, 1)} fill="url(#lgBeam)" />);
// Manchas da janela no piso, inclinadas no sentido dos raios.
const fy = horizon + (H - horizon) * 0.3;
const fh = (H - horizon) * 0.2;
const cx = src.x + dir * W * 0.38;
const sk = dir * fh * 0.9;
for (const [a, b] of [[-0.62, -0.03], [0.03, 0.62]]) {
const xa = cx + ww * a;
const xb = cx + ww * b;
layers.push(<polygon key={`f${a}`} points={`${xa},${fy} ${xb},${fy} ${xb + sk},${fy + fh} ${xa + sk},${fy + fh}`} fill={warm} opacity={night ? 0.08 : 0.2} />);
}
} else if (src?.kind === "glow") {
const r = Math.max(W * 0.35, src.spread ?? W * 0.4);
defs.push(<radialGradient key="g" id="lgGlow" gradientUnits="userSpaceOnUse" cx={src.x} cy={src.y} r={r}>
<stop offset="0" stopColor={warm} stopOpacity={0.38} /><stop offset="1" stopColor={warm} stopOpacity={0} /></radialGradient>);
defs.push(<radialGradient key="d" id="lgDark" gradientUnits="userSpaceOnUse" cx={src.x} cy={src.y} r={H * 0.7}>
<stop offset="0.25" stopColor={pal.shade} stopOpacity={0} /><stop offset="1" stopColor={pal.shade} stopOpacity={0.6} /></radialGradient>);
layers.push(<rect key="dark" width={W} height={H} fill="url(#lgDark)" />);
layers.push(<rect key="glow" width={W} height={H} fill="url(#lgGlow)" />);
} else if (src?.kind === "sun") {
defs.push(<radialGradient key="s" id="lgSun" gradientUnits="userSpaceOnUse" cx={src.x} cy={src.y} r={W * 1.05}>
<stop offset="0" stopColor={warm} stopOpacity={0.26} /><stop offset="0.5" stopColor={warm} stopOpacity={0.06} /><stop offset="1" stopColor={warm} stopOpacity={0} /></radialGradient>);
defs.push(<linearGradient key="k" id="lgCool" x1="1" y1="1" x2="0.3" y2="0.4">
<stop offset="0" stopColor={pal.shade} stopOpacity={0.3} /><stop offset="1" stopColor={pal.shade} stopOpacity={0} /></linearGradient>);
layers.push(<rect key="cool" width={W} height={H} fill="url(#lgCool)" />);
layers.push(<rect key="sun" width={W} height={H} fill="url(#lgSun)" />);
}
if (vignette) {
defs.push(<radialGradient key="v" id="lgVig" cx="0.5" cy="0.45" r="0.75"><stop offset="0.55" stopColor="#000" stopOpacity={0} /><stop offset="1" stopColor="#000" stopOpacity={0.55} /></radialGradient>);
layers.push(<rect key="vig" width={W} height={H} fill="url(#lgVig)" />);
}
return (
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ position: "absolute", inset: 0 }}>
<defs>
<linearGradient id="spot" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor={pal.light} stopOpacity={0.32} /><stop offset="1" stopColor={pal.light} stopOpacity={0.05} /></linearGradient>
<radialGradient id="spotDark" cx="0.5" cy="0.55" r="0.65"><stop offset="0.35" stopColor="#000" stopOpacity={0} /><stop offset="1" stopColor="#000" stopOpacity={0.6} /></radialGradient>
</defs>
<rect width={W} height={H} fill="url(#spotDark)" />
<polygon points={`${W * 0.44},${H * 0.03} ${W * 0.56},${H * 0.03} ${W * 0.86},${H * 0.75} ${W * 0.14},${H * 0.75}`} fill="url(#spot)" />
<rect x={W * 0.42} y={H * 0.025} width={W * 0.16} height={14} rx={6} fill="#d9d9d9" />
<ellipse cx={W / 2} cy={H * 0.75} rx={W * 0.36} ry={34} fill={pal.light} opacity={0.12} />
<defs>{defs}</defs>
{layers}
</svg>
);
}
/** Chuva por cima de tudo (inclusive dos personagens); tempestade escurece, chove mais e relampeja. */
export function WeatherLayer({ spec, frame }: { spec: ShotSpec; frame: number }) {
const weather = spec.place?.weather ?? "none";
if (weather === "none") return null;
const storm = weather === "storm";
const rand = rng(spec.seed + 101);
const drops = Array.from({ length: storm ? 230 : 130 }, () => ({ x: rand() * (W + 300), y: rand() * H, v: 38 + rand() * 26, l: 40 + rand() * 50 }));
// Relâmpago: um clarão curto a cada 2,5 s, com fase que depende da semente.
const cycle = 75;
const ph = (frame + (spec.seed % cycle)) % cycle;
const flash = storm && ph < 5 ? (ph < 2 ? 0.55 : 0.25) : 0;
return (
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ position: "absolute", inset: 0 }}>
{storm && <rect width={W} height={H} fill="#0a1020" opacity={0.22} />}
<g stroke="#d6e4f5" strokeWidth={storm ? 3.4 : 2.6} strokeLinecap="round" opacity={storm ? 0.6 : 0.5}>
{drops.map((d, i) => {
const y = ((d.y + frame * d.v) % (H + 120)) - 60;
const x = ((((d.x - frame * d.v * 0.22) % (W + 300)) + W + 300) % (W + 300)) - 150;
return <line key={i} x1={x} y1={y} x2={x - d.l * 0.22} y2={y + d.l} />;
})}
</g>
{flash > 0 && <>
<rect width={W} height={H} fill="#eaf2ff" opacity={flash} />
<path d={`M${W * 0.7} 0 L${W * 0.64} ${H * 0.14} L${W * 0.69} ${H * 0.14} L${W * 0.6} ${H * 0.3}`} stroke="#ffffff" strokeWidth={9} fill="none" strokeLinejoin="round" />
</>}
</svg>
);
}
/**
* Por cima dos personagens: a parte da frente das peças ocupadas (casco da arca, lataria do carro), na mesma
* posição da peça no fundo — quem está "dentro" aparece da cintura para cima.
*/
export function PlaceForeground({ spec, frame, progress = 0 }: { spec: ShotSpec; frame: number; progress?: number }) {
const place = spec.place;
const layout = React.useMemo(() => (place ? layoutPlace(spec) : null), [spec, place]);
if (!place || !layout || !place.elements.some((e) => e.occupied && FRONT_PART[e.kind])) return null;
const pal = palette(spec.palette);
const hazeColor = place.indoor ? pal.wall : mix(mix(pal.sky[2], pal.sky[1], 0.25), "#c8ccd6", place.fog ? 0.45 : 0);
const level = floodLevel(place, progress);
const waterY = level === null ? null : level * H;
const storm = place.weather === "storm";
const { horizon, zoom } = layout;
const zoomT = zoom === 1 ? undefined : `translate(${W / 2} ${horizon}) scale(${zoom}) translate(${-W / 2} ${-horizon})`;
return (
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ position: "absolute", inset: 0 }}>
<g transform={zoomT}>
{layout.items.filter((it) => it.e.occupied && FRONT_PART[it.e.kind]).map((it) => {
const floating = !!it.e.float && waterY !== null;
return <PlacedElement key={it.e.i} it={it} pal={pal} spec={spec} hazeColor={hazeColor} part="front"
y={floating ? waterY! + H * 0.035 + Math.sin(frame / 14 + it.e.i) * 9 : undefined}
rot={floating ? Math.sin(frame / 22 + it.e.i) * (storm ? 3.5 : 1.6) : 0} />;
})}
{waterY !== null && place.elements.some((e) => e.occupied && e.float) && <rect x={0} y={waterY + H * 0.03} width={W} height={H} fill={pal.ground.water} opacity={0.35} />}
</g>
</svg>
);
}
+167
View File
@@ -0,0 +1,167 @@
// Rig do personagem: o rosto e o corpo são PARÂMETROS contínuos, não desenhos prontos. Uma expressão ou uma
// pose é só um conjunto de valores; dá para misturar (blend), ajustar um valor ("sorriso 0,3 a mais") e criar
// novas sem mexer no desenho. Ângulos em graus; "para fora" positivo nos dois lados (o desenho espelha).
export type FaceParams = {
/** Sobrancelha: y (px; negativo sobe) e tilt (graus; positivo = ponta de dentro sobe, como triste/preocupado). */
browL: { y: number; tilt: number };
browR: { y: number; tilt: number };
/** Abertura dos olhos (0 fechado · 1 normal · 1,35 arregalado). */
eyeL: number;
eyeR: number;
/** Tamanho da pupila (0,4 pavor · 1 normal · 1,3 encantado). */
pupil: number;
/** Direção do olhar (-1…1). */
gazeX: number;
gazeY: number;
/** Boca: abertura 0…1, sorriso -1 (triste) … 1 (feliz), largura 0,5…1,4, dentes à mostra. */
mouthOpen: number;
smile: number;
mouthWidth: number;
/** Arredondamento dos lábios (0 normal … 1 bico de "o/u"): vem da fala (lipsync.ts). */
mouthRound: number;
/** Pálpebra de cima somada à de base do personagem (−0,5 arregala … 0,6 quase fecha). */
lid: number;
teeth: boolean;
/** Extras: rubor 0…1, gota de suor, lágrimas, veia de raiva. */
blush: number;
sweat: boolean;
tears: boolean;
anger: boolean;
};
export type Limb = {
/** Abertura a partir do corpo (0 = para baixo; 90 = horizontal para fora; 180 = para cima). */
raise: number;
/** Dobra do cotovelo/joelho (positivo = antebraço/canela para dentro, na frente do corpo). */
bend: number;
};
export type BodyParams = {
/** Inclinação do tronco (graus; positivo = para a direita de quem olha). */
lean: number;
/** Cabeça: inclinação (graus), virada (-1…1, finge 3/4) e aceno (-1 olha para cima … 1 para baixo). */
headTilt: number;
headTurn: number;
headNod: number;
armL: Limb;
armR: Limb;
legL: Limb;
legR: Limb;
/** Agachar/sentar: 0 em pé … 1 sentado (quadril desce, coxa encurta em perspectiva). */
crouch: number;
};
export const NEUTRAL_FACE: FaceParams = {
browL: { y: 0, tilt: 0 }, browR: { y: 0, tilt: 0 }, eyeL: 1, eyeR: 1, pupil: 1, gazeX: 0, gazeY: 0,
mouthOpen: 0, smile: 0.1, mouthWidth: 1, mouthRound: 0, lid: 0, teeth: false, blush: 0, sweat: false, tears: false, anger: false,
};
export const NEUTRAL_BODY: BodyParams = {
lean: 0, headTilt: 0, headTurn: 0, headNod: 0,
armL: { raise: 8, bend: 6 }, armR: { raise: 8, bend: 6 }, legL: { raise: 2, bend: 0 }, legR: { raise: 2, bend: 0 }, crouch: 0,
};
type FacePatch = Partial<Omit<FaceParams, "browL" | "browR">> & { browL?: Partial<FaceParams["browL"]>; browR?: Partial<FaceParams["browR"]>; brows?: Partial<FaceParams["browL"]>; eyes?: number };
type BodyPatch = Partial<Omit<BodyParams, "armL" | "armR" | "legL" | "legR">> & { armL?: Partial<Limb>; armR?: Partial<Limb>; legL?: Partial<Limb>; legR?: Partial<Limb>; arms?: Partial<Limb>; legs?: Partial<Limb> };
/** Aplica um ajuste parcial (aceita `brows`/`eyes`/`arms`/`legs` para os dois lados de uma vez). */
export function withFace(base: FaceParams, p: FacePatch = {}): FaceParams {
const { brows, eyes, browL, browR, ...rest } = p;
return {
...base, ...rest,
browL: { ...base.browL, ...brows, ...browL }, browR: { ...base.browR, ...brows, ...browR },
eyeL: rest.eyeL ?? eyes ?? base.eyeL, eyeR: rest.eyeR ?? eyes ?? base.eyeR,
};
}
export function withBody(base: BodyParams, p: BodyPatch = {}): BodyParams {
const { arms, legs, armL, armR, legL, legR, ...rest } = p;
return {
...base, ...rest,
armL: { ...base.armL, ...arms, ...armL }, armR: { ...base.armR, ...arms, ...armR },
legL: { ...base.legL, ...legs, ...legL }, legR: { ...base.legR, ...legs, ...legR },
};
}
/** Expressões prontas = atalhos de parâmetros (dá para ajustar qualquer valor por cima com `face`). */
export const EXPRESSION_PRESETS = {
neutral: {},
smile: { smile: 0.7, eyes: 0.9 },
happy: { smile: 0.9, mouthOpen: 0.3, teeth: true, eyes: 0.85, brows: { y: -3 } },
laugh: { smile: 1, mouthOpen: 0.75, teeth: true, eyes: 0.18, brows: { y: -5 }, blush: 0.4 },
proud: { smile: 0.6, lid: 0.35, brows: { y: -2 } },
sad: { smile: -0.7, brows: { tilt: 16 }, eyes: 0.8, gazeY: 0.5 },
cry: { smile: -0.9, mouthOpen: 0.35, brows: { tilt: 20 }, eyes: 0.4, tears: true },
worried: { smile: -0.3, brows: { tilt: 14, y: -2 }, eyes: 1.05, sweat: true },
angry: { smile: -0.4, brows: { tilt: -18, y: 3 }, lid: 0.25, mouthWidth: 0.9 },
furious: { smile: -0.6, mouthOpen: 0.6, teeth: true, brows: { tilt: -24, y: 4 }, lid: 0.3, anger: true },
surprised: { mouthOpen: 0.6, mouthWidth: 0.55, smile: 0, brows: { y: -8 }, eyes: 1.25, pupil: 0.8, lid: -0.5 },
scared: { mouthOpen: 0.5, mouthWidth: 0.9, smile: -0.5, teeth: true, brows: { tilt: 18, y: -6 }, eyes: 1.3, pupil: 0.55, sweat: true, lid: -0.5 },
shocked: { mouthOpen: 0.95, mouthWidth: 0.6, smile: 0, brows: { y: -10 }, eyes: 1.35, pupil: 0.45, lid: -0.5 },
suspicious: { smile: -0.1, mouthWidth: 0.8, browL: { y: -6, tilt: 0 }, browR: { y: 4, tilt: -10 }, lid: 0.45, gazeX: 0.6 },
smirk: { smile: 0.45, mouthWidth: 0.8, browL: { y: -5 }, lid: 0.3, gazeX: -0.3 },
confused: { smile: -0.2, mouthWidth: 0.75, browL: { y: -7 }, browR: { tilt: -8 }, gazeY: -0.6, gazeX: 0.4 },
disgusted: { smile: -0.7, mouthWidth: 1.1, brows: { tilt: -10, y: 2 }, lid: 0.35 },
sleepy: { lid: 0.6, brows: { y: 3 }, mouthOpen: 0.1, smile: 0 },
determined: { smile: 0.1, mouthWidth: 0.85, brows: { tilt: -10, y: 2 }, lid: 0.2 },
embarrassed: { smile: 0.3, blush: 1, gazeY: 0.6, gazeX: -0.4, eyes: 0.8, sweat: true },
} satisfies Record<string, FacePatch>;
/** Poses prontas = atalhos de ângulos (ajustáveis por cima com `body`). */
export const POSE_PRESETS = {
stand: {},
point: { armR: { raise: 46, bend: -128 } },
wave: { armR: { raise: 140, bend: -25 } },
hold: { armR: { raise: 34, bend: 106 } },
arms_up: { arms: { raise: 158, bend: -10 } },
celebrate: { arms: { raise: 146, bend: -26 }, headNod: -0.35 },
shrug: { arms: { raise: 38, bend: 100 }, headTilt: 7 },
think: { armR: { raise: -24, bend: 138 }, headTilt: -5 },
hands_on_hips: { arms: { raise: 42, bend: 105 } },
cross_arms: { arms: { raise: 24, bend: 128 } },
facepalm: { armR: { raise: 125, bend: -103 }, headNod: 0.5, headTilt: 8 },
cover_mouth: { armR: { raise: -34, bend: 130 } },
defend: { arms: { raise: 62, bend: 118 }, lean: -4 },
reach: { armR: { raise: 68, bend: -15 }, lean: 6 },
sit: { crouch: 1, arms: { raise: 14, bend: 40 } },
kneel: { crouch: 0.6, arms: { raise: 10, bend: 20 } },
lean_in: { lean: 8, headTilt: 6 },
// Duas mãos segurando um objeto largo (livro, tábua) pelas bordas, na frente do peito.
hold_both: { arms: { raise: 42, bend: 104 } },
// Joinha: cotovelo dobrado, mão na altura do peito/ombro (a forma da mão vem do desenho: `thumbs_up`).
thumbs_up: { armR: { raise: 22, bend: 148 } },
} satisfies Record<string, BodyPatch>;
export type ExpressionName = keyof typeof EXPRESSION_PRESETS;
export type PoseName = keyof typeof POSE_PRESETS;
export const EXPRESSION_NAMES = Object.keys(EXPRESSION_PRESETS) as ExpressionName[];
export const POSE_NAMES = Object.keys(POSE_PRESETS) as PoseName[];
export const faceOf = (name: string | undefined, patch?: FacePatch): FaceParams =>
withFace(withFace(NEUTRAL_FACE, (EXPRESSION_PRESETS as Record<string, FacePatch>)[name ?? "neutral"] ?? {}), patch);
export const bodyOf = (name: string | undefined, patch?: BodyPatch): BodyParams =>
withBody(withBody(NEUTRAL_BODY, (POSE_PRESETS as Record<string, BodyPatch>)[name ?? "stand"] ?? {}), patch);
const lerp = (a: number, b: number, k: number) => a + (b - a) * k;
const limb = (a: Limb, b: Limb, k: number): Limb => ({ raise: lerp(a.raise, b.raise, k), bend: lerp(a.bend, b.bend, k) });
/** Mistura duas expressões (k = 0 → a, 1 → b). Os "liga/desliga" trocam na metade. */
export function blendFace(a: FaceParams, b: FaceParams, k: number): FaceParams {
const pick = <T,>(x: T, y: T) => (k < 0.5 ? x : y);
return {
browL: { y: lerp(a.browL.y, b.browL.y, k), tilt: lerp(a.browL.tilt, b.browL.tilt, k) },
browR: { y: lerp(a.browR.y, b.browR.y, k), tilt: lerp(a.browR.tilt, b.browR.tilt, k) },
eyeL: lerp(a.eyeL, b.eyeL, k), eyeR: lerp(a.eyeR, b.eyeR, k), pupil: lerp(a.pupil, b.pupil, k),
gazeX: lerp(a.gazeX, b.gazeX, k), gazeY: lerp(a.gazeY, b.gazeY, k),
mouthOpen: lerp(a.mouthOpen, b.mouthOpen, k), smile: lerp(a.smile, b.smile, k), mouthWidth: lerp(a.mouthWidth, b.mouthWidth, k), mouthRound: lerp(a.mouthRound, b.mouthRound, k), lid: lerp(a.lid, b.lid, k),
teeth: pick(a.teeth, b.teeth), blush: lerp(a.blush, b.blush, k), sweat: pick(a.sweat, b.sweat), tears: pick(a.tears, b.tears), anger: pick(a.anger, b.anger),
};
}
export function blendBody(a: BodyParams, b: BodyParams, k: number): BodyParams {
return {
lean: lerp(a.lean, b.lean, k), headTilt: lerp(a.headTilt, b.headTilt, k), headTurn: lerp(a.headTurn, b.headTurn, k), headNod: lerp(a.headNod, b.headNod, k),
armL: limb(a.armL, b.armL, k), armR: limb(a.armR, b.armR, k), legL: limb(a.legL, b.legL, k), legR: limb(a.legR, b.legR, k), crouch: lerp(a.crouch, b.crouch, k),
};
}
export type { FacePatch, BodyPatch };
+1 -1
View File
@@ -152,7 +152,7 @@ function Card({ spec }: SceneProps) {
export function SceneBackground(props: SceneProps) {
switch (props.spec.scene.kind) {
case "place": return <PlaceBackground spec={props.spec} frame={props.frame} />;
case "place": return <PlaceBackground spec={props.spec} frame={props.frame} progress={props.progress} />;
case "street": return <Street {...props} />;
case "house": return <HouseFront {...props} />;
case "blueprint": return <Blueprint />;
+158 -14
View File
@@ -3,7 +3,10 @@
// do quadro (0 = esquerda/topo, 1 = direita/base). Tempos em segundos, a partir do início do trecho.
import { EXPRESSIONS, POSES, validateLook, type CharacterLook, type Expression, type Pose } from "./character";
import { ELEMENTS, GROUNDS, PALETTES, type PaletteId, type Place } from "./places";
import { validateTimeline, type Action } from "./motion";
import type { BodyPatch, FacePatch } from "./rig";
import { ELEMENTS, GROUNDS, LIGHT_SOURCES, PALETTES, WEATHERS, type PaletteId, type Place } from "./places";
import { SPECIES, type Species } from "./animals";
/** "place" = lugar montado por peças (ver places.tsx); os demais são fundos prontos da 1ª versão. */
export const SCENES = ["place", "street", "house", "plain", "blueprint", "card"] as const;
@@ -11,7 +14,8 @@ export const LIGHTS = ["none", "spot", "vignette"] as const;
export type SceneKind = (typeof SCENES)[number];
export const TIMES = ["night", "dawn", "day"] as const;
export type TimeOfDay = (typeof TIMES)[number];
export const ICONS = ["house", "generator", "fuel", "battery", "phone", "door", "eye", "bulb", "solar", "warning", "money", "clock"] as const;
export const ICONS = ["house", "generator", "fuel", "battery", "phone", "door", "eye", "bulb", "solar", "warning", "money", "clock",
"olive", "hammer", "tablet", "book", "ruler"] as const;
export type IconId = (typeof ICONS)[number];
export const TONES = ["info", "danger", "ok"] as const;
export type Tone = (typeof TONES)[number];
@@ -27,6 +31,13 @@ export type Person = {
item?: IconId;
/** Olha para a esquerda (espelha o desenho). */
flip?: boolean;
/** Enquadramento: corpo inteiro (padrão), meio corpo ou de perto (rosto grande, como ilustração de destaque). */
framing?: "full" | "medium" | "close" | "insert";
/** Ajuste fino por cima da expressão/pose (ex.: { smile: 0.3, browL: { y: -6 } } ou { armR: { raise: 60 } }). */
face?: FacePatch;
body?: BodyPatch;
/** Movimento: ações com início (at/atP/cue) — andar, pular, falar, trocar de expressão… (motion.ts). */
timeline?: Action[];
/** Cor da roupa (hex). */
outfit?: string;
hair?: "short" | "bun" | "none";
@@ -39,7 +50,22 @@ export type Person = {
enterS?: number;
};
export type Crowd = { kind: "crowd"; count: number; y: number; enterS?: number };
export type Actor = Person | Crowd;
/**
* Animal (figura reaproveitável, animals.tsx). `count` > 1 = fila (um atrás do outro, `gap` entre eles); `pair` =
* casal lado a lado em cada lugar da fila. `walk` anda de x até `to` (aves com `fly` voam, subindo e descendo).
* Olha para a direita; anda para a esquerda = espelha sozinho. `carry: "olive"` = ramo no bico (aves).
*/
export type Animal = {
kind: "animal";
species: Species;
x: number; y: number; scale?: number; flip?: boolean; color?: string;
count?: number; gap?: number; pair?: boolean;
walk?: { to: number; startS?: number; dur?: number };
fly?: boolean;
carry?: "olive";
enterS?: number;
};
export type Actor = Person | Crowd | Animal;
export type Prop = {
icon: IconId;
@@ -54,16 +80,57 @@ export type Prop = {
crossed?: boolean;
};
/**
* Camadas de texto/grafismo por cima da cena (overlays.tsx). `text` é o rótulo de cada uma:
* - onomatopoeia | tag | big: o texto em si; counter: rótulo pequeno + `value` grande (caixa escura arredondada);
* - namecard: nome do personagem + `lines` (função, dado) num cartão claro;
* - stat: rótulo espaçado + `value` grande colorido por `tone` (danger vermelho, info amarelo, ok verde, sem = branco);
* - checklist: `items` com `state` (empty | checked | crossed) que vão se marcando em sequência (`stepS`);
* - table: `items` ({ text, value }) com a linha `highlight` destacada; `text` = título (pode ser "");
* - progress: rótulo + barra que enche até `value` (0–100) + porcentagem;
* - grid: `value` de `total` quadradinhos preenchidos (com o número) + "N DE M".
* `panel: true` = cartela sobre fundo escuro de tela inteira; sem ele, caixa escura flutuante sobre a cena.
*/
export const TEXT_KINDS = ["onomatopoeia", "tag", "counter", "big", "namecard", "stat", "checklist", "table", "progress", "grid"] as const;
export type TextKind = (typeof TEXT_KINDS)[number];
export const CHECK_STATES = ["empty", "checked", "crossed"] as const;
export type CheckState = (typeof CHECK_STATES)[number];
export type TextRow = { text: string; value?: string; state?: CheckState };
export type TextItem = {
kind: "onomatopoeia" | "tag" | "counter" | "big";
kind: TextKind;
text: string;
/** Só no "counter": o número grande embaixo do rótulo. */
value?: string;
/** counter/stat: o número grande; progress: 0–100; grid: quantos quadradinhos preenchidos. */
value?: string | number;
x: number; y: number;
atS?: number;
tone?: Tone;
/** Graus (onomatopeia costuma ir levemente girada). */
rotate?: number;
/** namecard: 1–2 linhas menores embaixo do nome (função, dado). */
lines?: string[];
/** checklist/table: as linhas. */
items?: TextRow[];
/** table: índice da linha destacada. */
highlight?: number;
/** grid: total de quadradinhos (1–40). */
total?: number;
/** checklist: segundos entre uma marcação e a próxima (padrão 0,5). */
stepS?: number;
/** Cartela sobre fundo escuro de tela inteira (senão, caixa flutuante sobre a cena). */
panel?: boolean;
/** Escala da cartela (padrão 1; 0,5 = lista pequena no canto). */
size?: number;
};
/**
* Painel do topo. Esquerda: `badge` (bloco amarelo, "DIA 3") + `clock` (hora, anda com `clockMinutesPerSecond`) e,
* embaixo, a faixa clara com `place` (ou `label`). Direita, opcional: `valueLabel` pequeno ("CAIXA") + `value` grande
* (`valueTone`; sem ele, zero/negativo fica vermelho) e a faixa amarela `note` ("ESTREIA EM 30 DIAS").
*/
export type Hud = {
badge: string; label: string; clock?: string; clockMinutesPerSecond?: number;
place?: string; value?: string; valueLabel?: string; valueTone?: Tone; note?: string;
};
export type Word = { text: string; startS: number; endS: number; tone?: "key" | "danger" };
@@ -78,16 +145,23 @@ export type ShotSpec = {
palette?: PaletteId;
/** Lugar montado por peças (scene.kind "place"). */
place?: Place;
/** Textura de papel por cima (0 desliga; padrão 0,11). */
grain?: number;
/** Luz por cima: foco do teto ("spot") ou vinheta. */
light?: (typeof LIGHTS)[number];
/** Fonte de luz posicionada (opcional): luminária (cone + poça no chão), janela (raios em diagonal) ou sol.
* x/y em fração do quadro. Sem ela, a luz sai das peças do lugar (luminária pendente > janela > sol). */
lightSource?: { kind: (typeof LIGHT_SOURCES)[number]; x: number; y?: number };
/** push = zoom no fim do trecho (1 = parado); panX = deslocamento horizontal da câmera (fração). */
camera?: { push?: number; panX?: number };
hud?: { badge: string; label: string; clock?: string; clockMinutesPerSecond?: number };
hud?: Hud;
actors?: Actor[];
props?: Prop[];
texts?: TextItem[];
/** Legenda palavra por palavra (tempos da narração). Vazio = sem legenda. */
/** Legenda palavra por palavra (tempos da narração). Vazio = sem legenda. A boca de quem "fala" usa os mesmos tempos. */
words?: Word[];
/** Volume do áudio do trecho quadro a quadro (0–1): fecha a boca nas pausas e abre nas sílabas fortes. */
audioEnv?: { fps: number; values: number[] };
card?: { title: string; subtitle?: string; footer?: string };
};
@@ -111,6 +185,12 @@ export function validateSpec(spec: unknown): string[] {
if (s.scene?.kind === "card" && !s.card?.title) errors.push("scene card precisa de card.title");
if (s.palette !== undefined && !PALETTES.includes(s.palette)) errors.push(`palette precisa ser um de: ${PALETTES.join(", ")}`);
if (s.light !== undefined && !LIGHTS.includes(s.light)) errors.push(`light precisa ser um de: ${LIGHTS.join(", ")}`);
if (s.lightSource !== undefined) {
const ls = s.lightSource;
if (!ls || !LIGHT_SOURCES.includes(ls.kind) || !frac(ls.x) || (ls.y !== undefined && !frac(ls.y))) {
errors.push(`lightSource: { kind (${LIGHT_SOURCES.join(", ")}), x, y? } em fração do quadro`);
}
}
if (s.scene?.kind === "place") {
const place = s.place;
if (!place || !GROUNDS.includes(place.ground) || !Array.isArray(place.elements)) errors.push(`place precisa de ground (${GROUNDS.join(", ")}) e elements`);
@@ -119,7 +199,10 @@ export function validateSpec(spec: unknown): string[] {
for (const [i, e] of place.elements.entries()) {
if (!ELEMENTS.includes(e.kind)) errors.push(`place.elements[${i}]: peça "${e.kind}" não existe (${ELEMENTS.join(", ")})`);
if (!frac(e.x) || (e.z !== undefined && !(e.z >= 0 && e.z <= 1))) errors.push(`place.elements[${i}]: x fora do quadro ou z fora de 0–1`);
if (e.lift !== undefined && !(finite(e.lift) && e.lift >= -0.5 && e.lift <= 1)) errors.push(`place.elements[${i}]: lift entre -0,5 e 1`);
}
if (place.weather !== undefined && !WEATHERS.includes(place.weather)) errors.push(`place.weather: ${WEATHERS.join(", ")}`);
if (place.flood !== undefined && !(place.flood && frac(place.flood.from) && frac(place.flood.to))) errors.push("place.flood: { from, to } em fração da altura");
}
}
for (const [i, a] of (s.actors ?? []).entries()) {
@@ -129,24 +212,85 @@ export function validateSpec(spec: unknown): string[] {
} else if (a.kind === "person" && a.expression !== undefined && !EXPRESSIONS.includes(a.expression)) errors.push(`actors[${i}]: expressão (${EXPRESSIONS.join(", ")})`);
else if (a.kind === "person" && a.pose !== undefined && !POSES.includes(a.pose)) errors.push(`actors[${i}]: pose (${POSES.join(", ")})`);
else if (a.kind === "person" && a.item !== undefined && !ICONS.includes(a.item)) errors.push(`actors[${i}]: item "${a.item}" não existe`);
else if (a.kind === "person") {
for (const e of validateTimeline(a.timeline)) errors.push(`actors[${i}].${e}`);
for (const [j, act] of (a.timeline ?? []).entries()) {
if (act.expression !== undefined && !EXPRESSIONS.includes(act.expression as Expression)) errors.push(`actors[${i}].timeline[${j}]: expressão "${act.expression}" não existe`);
if (act.pose !== undefined && !POSES.includes(act.pose as Pose)) errors.push(`actors[${i}].timeline[${j}]: pose "${act.pose}" não existe`);
}
}
else if (a.kind === "crowd" && (!finite(a.count) || a.count < 1 || a.count > 40 || !frac(a.y))) errors.push(`actors[${i}]: crowd inválida`);
else if (a.kind !== "person" && a.kind !== "crowd") errors.push(`actors[${i}]: kind inválido`);
else if (a.kind === "animal") {
if (!SPECIES.includes(a.species)) errors.push(`actors[${i}]: espécie "${a.species}" não existe (${SPECIES.join(", ")})`);
if (!frac(a.x) || !frac(a.y)) errors.push(`actors[${i}]: x/y fora do quadro`);
if (a.count !== undefined && !(Number.isInteger(a.count) && a.count >= 1 && a.count <= 12)) errors.push(`actors[${i}]: count entre 1 e 12`);
if (a.walk !== undefined && !(a.walk && frac(a.walk.to))) errors.push(`actors[${i}]: walk.to fora do quadro`);
if (a.carry !== undefined && a.carry !== "olive") errors.push(`actors[${i}]: carry só "olive"`);
}
else if (!["crowd", "person", "animal"].includes((a as { kind: string }).kind)) errors.push(`actors[${i}]: kind inválido`);
}
for (const [i, p] of (s.props ?? []).entries()) {
if (!ICONS.includes(p.icon)) errors.push(`props[${i}]: ícone "${p.icon}" não existe (${ICONS.join(", ")})`);
if (!frac(p.x) || !frac(p.y)) errors.push(`props[${i}]: x/y fora do quadro`);
if (p.tone !== undefined && !TONES.includes(p.tone)) errors.push(`props[${i}]: tone inválido`);
}
for (const [i, t] of (s.texts ?? []).entries()) {
if (!["onomatopoeia", "tag", "counter", "big"].includes(t.kind)) errors.push(`texts[${i}]: kind inválido`);
if (typeof t.text !== "string" || !t.text.trim()) errors.push(`texts[${i}]: texto vazio`);
if (!frac(t.x) || !frac(t.y)) errors.push(`texts[${i}]: x/y fora do quadro`);
}
if (s.hud !== undefined) errors.push(...validateHud(s.hud));
for (const [i, t] of (s.texts ?? []).entries()) errors.push(...validateText(t, i));
if (s.audioEnv !== undefined && (!finite(s.audioEnv.fps) || !Array.isArray(s.audioEnv.values) || s.audioEnv.values.length > 36000)) errors.push("audioEnv: { fps, values[] } (até 36 mil valores)");
for (const [i, w] of (s.words ?? []).entries()) {
if (typeof w.text !== "string" || !finite(w.startS) || !finite(w.endS) || w.endS < w.startS) errors.push(`words[${i}]: inválida`);
}
return errors;
}
const str = (v: unknown): v is string => typeof v === "string";
function validateHud(h: Hud): string[] {
const errors: string[] = [];
if (!h || typeof h !== "object") return ["hud precisa ser um objeto"];
if (!str(h.badge) || !str(h.label)) errors.push("hud: badge e label são texto");
for (const k of ["clock", "place", "value", "valueLabel", "note"] as const) if (h[k] !== undefined && !str(h[k])) errors.push(`hud.${k}: texto`);
if (h.clockMinutesPerSecond !== undefined && !finite(h.clockMinutesPerSecond)) errors.push("hud.clockMinutesPerSecond: número");
if (h.valueTone !== undefined && !TONES.includes(h.valueTone)) errors.push(`hud.valueTone: ${TONES.join(", ")}`);
return errors;
}
/** "97", 97 ou "97,5" → número (NaN se não for). */
export const numberOf = (v: unknown) => (typeof v === "number" ? v : typeof v === "string" && v.trim() ? Number(v.replace(/%$/, "").replace(",", ".")) : NaN);
const OPTIONAL_TEXT: TextKind[] = ["table", "stat", "checklist"];
function validateText(t: TextItem, i: number): string[] {
const errors: string[] = [];
const at = `texts[${i}]`;
if (!t || typeof t !== "object") return [`${at}: precisa ser um objeto`];
if (!TEXT_KINDS.includes(t.kind)) errors.push(`${at}: kind inválido (${TEXT_KINDS.join(", ")})`);
// Tabela e lista podem ir sem título e o stat sem rótulo (só o número); os demais precisam de texto.
if (!str(t.text) || (!t.text.trim() && !OPTIONAL_TEXT.includes(t.kind))) errors.push(`${at}: texto vazio`);
if (!frac(t.x) || !frac(t.y)) errors.push(`${at}: x/y fora do quadro`);
if (t.tone !== undefined && !TONES.includes(t.tone)) errors.push(`${at}: tone inválido`);
if (t.value !== undefined && !str(t.value) && !finite(t.value)) errors.push(`${at}: value é texto ou número`);
if (t.size !== undefined && !(finite(t.size) && t.size >= 0.3 && t.size <= 2)) errors.push(`${at}: size entre 0,3 e 2`);
if (t.lines !== undefined && !(Array.isArray(t.lines) && t.lines.length <= 3 && t.lines.every(str))) errors.push(`${at}: lines = até 3 textos`);
if (t.kind === "stat" && (t.value === undefined || !String(t.value).trim())) errors.push(`${at}: stat precisa de value`);
if (t.kind === "checklist" || t.kind === "table") {
if (!Array.isArray(t.items) || !t.items.length || t.items.length > 8) errors.push(`${at}: items com 1 a 8 linhas`);
else for (const [j, r] of t.items.entries()) {
if (!r || !str(r.text) || !r.text.trim()) errors.push(`${at}.items[${j}]: texto vazio`);
else if (r.state !== undefined && !CHECK_STATES.includes(r.state)) errors.push(`${at}.items[${j}]: state (${CHECK_STATES.join(", ")})`);
else if (r.value !== undefined && !str(r.value)) errors.push(`${at}.items[${j}]: value é texto`);
}
}
if (t.highlight !== undefined && !(Number.isInteger(t.highlight) && t.highlight >= 0 && t.highlight < (t.items?.length ?? 0))) errors.push(`${at}: highlight fora das linhas`);
if (t.stepS !== undefined && !(finite(t.stepS) && t.stepS >= 0 && t.stepS <= 5)) errors.push(`${at}: stepS entre 0 e 5`);
if (t.kind === "progress" && !(numberOf(t.value) >= 0 && numberOf(t.value) <= 100)) errors.push(`${at}: progress precisa de value entre 0 e 100`);
if (t.kind === "grid") {
const total = t.total ?? NaN;
if (!(Number.isInteger(total) && total >= 1 && total <= 40)) errors.push(`${at}: grid precisa de total inteiro entre 1 e 40`);
else if (!(Number.isInteger(numberOf(t.value)) && numberOf(t.value) >= 0 && numberOf(t.value) <= total)) errors.push(`${at}: grid precisa de value inteiro entre 0 e total`);
}
return errors;
}
/** Número de quadros do trecho (arredonda para cima: o vídeo nunca fica mais curto que o áudio). */
export const frameCount = (spec: Pick<ShotSpec, "durationS" | "fps">) => Math.max(1, Math.ceil(spec.durationS * spec.fps));
+7
View File
@@ -4,6 +4,12 @@ import { FONT_CAPTION, FONT_LABEL } from "./colors";
export * from "./colors";
/**
* Texto de apoio do grafismo (HUD, rótulos espaçados, listas, linhas do cartão de nome): Barlow Semi Condensed Bold
* (OFL-1.1, licença em assets/fonts/BarlowSemiCondensed-Bold.OFL.txt). Condensada e legível em tamanho pequeno.
*/
export const FONT_TEXT = "CartoonBarlow";
let loaded = false;
/** Carrega as fontes de assets/fonts antes do primeiro quadro (o render espera). */
export function loadFonts(): void {
@@ -13,6 +19,7 @@ export function loadFonts(): void {
const faces = [
new FontFace(FONT_CAPTION, `url(${staticFile("fonts/Anton-Regular.ttf")})`),
new FontFace(FONT_LABEL, `url(${staticFile("fonts/BebasNeue-Regular.ttf")})`),
new FontFace(FONT_TEXT, `url(${staticFile("fonts/BarlowSemiCondensed-Bold.ttf")})`),
];
Promise.all(faces.map((f) => f.load().then((ok) => document.fonts.add(ok))))
.then(() => continueRender(handle))
+35
View File
@@ -0,0 +1,35 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { GRIP, HAND_SHAPES, TWO_HANDED, handPlacement, wristForHold } from "../src/hands";
describe("biblioteca de mãos", () => {
it("o pulso acompanha o eixo do antebraço: a forma gira em torno do centro do pulso", () => {
for (const shape of HAND_SHAPES) {
for (const fore of [0, 45, 120, -60]) {
for (const s of [1, -1] as const) {
const p = handPlacement(shape, 30, 40, fore, s, 0.6);
// O centro do pulso do desenho cai exatamente no pulso da tela, em qualquer giro e espelho.
const w = p.map(p.def.wrist[0], p.def.wrist[1]);
assert.ok(Math.abs(w.x - 30) < 1e-9 && Math.abs(w.y - 40) < 1e-9, `${shape} ${fore} ${s}`);
}
}
}
});
it("formas em pé giram pela diferença entre o antebraço e o ângulo do desenho (espelhadas do outro lado)", () => {
assert.equal(handPlacement("thumbs_up", 0, 0, 135, 1, 1).rot, 0);
assert.equal(handPlacement("thumbs_up", 0, 0, -135, -1, 1).rot, 0);
assert.equal(handPlacement("grip", 0, 0, 75, 1, 1).rot, 30);
});
it("pegada de borda: o pulso calculado põe a borda do objeto no ponto pedido", () => {
const w = wristForHold("pinch_edge", 120, 80, 48, 1, 0.62);
const hold = handPlacement("pinch_edge", w.x, w.y, 48, 1, 0.62).hold!;
assert.ok(Math.abs(hold.x - 120) < 1e-9 && Math.abs(hold.y - 80) < 1e-9);
});
it("livro e tábua vão nas duas mãos; martelo, ramo e régua têm cabo em pé no punho", () => {
assert.ok(TWO_HANDED.includes("book") && TWO_HANDED.includes("tablet") && !TWO_HANDED.includes("hammer"));
for (const id of ["hammer", "olive", "ruler"] as const) assert.ok(GRIP[id], id);
});
});
+50
View File
@@ -0,0 +1,50 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { armGeometry, armLayer } from "../src/limbs";
import { ACTIONS, evaluate } from "../src/motion";
import { POSE_PRESETS, bodyOf } from "../src/rig";
const layers = (pose: string, patch?: Parameters<typeof bodyOf>[1], holds = false) => {
const b = bodyOf(pose, patch);
return [armLayer(b, -1), armLayer(b, 1, { holds })];
};
describe("profundidade dos braços (personagem de frente)", () => {
it("braço ao lado do corpo, acenando ou apontando para fora fica 'side'", () => {
for (const pose of ["stand", "wave", "arms_up", "celebrate", "point", "reach", "lean_in"]) assert.deepEqual(layers(pose), ["side", "side"], pose);
});
it("antebraço na frente do peito fica 'front': cruzar os braços, segurar, mão na cintura, apontar para o outro lado", () => {
assert.deepEqual(layers("cross_arms"), ["front", "front"]);
assert.deepEqual(layers("hands_on_hips"), ["front", "front"]);
assert.equal(layers("hold")[1], "front");
assert.equal(layers("point", { armR: { raise: 40, bend: 120 } })[1], "front");
});
it("mão na altura do pescoço/rosto fica 'face' (por cima da cabeça e da barba)", () => {
// Pensar (queixo), tapar a boca e mão na testa: a mão chega ao rosto.
for (const pose of ["think", "cover_mouth", "facepalm"]) assert.equal(layers(pose)[1], "face", pose);
assert.equal(layers("stand", { armR: { raise: 10, bend: 175 } })[1], "face");
// Mesmo segurando objeto: no rosto, a mão vai por cima da cabeça.
assert.equal(layers("cover_mouth", undefined, true)[1], "face");
});
it("objeto na mão deixa o braço na frente do corpo; o lado esquerdo espelha o direito", () => {
assert.equal(layers("stand", undefined, true)[1], "front");
const b = bodyOf("cross_arms");
const [l, r] = [armGeometry(b, -1), armGeometry(b, 1)];
assert.ok(Math.abs(l.hand.x - 100 + (r.hand.x - 100)) < 1e-9 && Math.abs(l.hand.y - r.hand.y) < 1e-9);
});
it("toda pose pronta e todo quadro de toda ação têm camada válida (função pura, sem relógio)", () => {
const valid = new Set(["side", "front", "face"]);
for (const pose of Object.keys(POSE_PRESETS)) for (const s of [-1, 1] as const) assert.ok(valid.has(armLayer(bodyOf(pose), s)), pose);
for (const action of ACTIONS) {
for (let t = 0; t <= 2; t += 0.25) {
const st = evaluate({ x: 0.5, timeline: [{ do: action, at: 0, dur: 2, text: "oi" }] }, t, 2, 1);
for (const s of [-1, 1] as const) assert.ok(valid.has(armLayer(st.body, s)), `${action} ${t}`);
}
}
assert.equal(armLayer(bodyOf("wave"), 1), armLayer(bodyOf("wave"), 1));
});
});
+79
View File
@@ -0,0 +1,79 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { visemeAt, speak } from "../src/lipsync";
import { evaluate, startOf, validateTimeline } from "../src/motion";
import { EXPRESSION_NAMES, blendFace, faceOf } from "../src/rig";
const words = [
{ text: "Mamãe", startS: 0.2, endS: 0.7 },
{ text: "não", startS: 0.8, endS: 1.2 },
{ text: "ouviu", startS: 1.3, endS: 1.8 },
];
describe("rig: expressões como parâmetros", () => {
it("toda expressão pronta vira parâmetros válidos e se mistura com outra", () => {
for (const name of EXPRESSION_NAMES) assert.ok(Number.isFinite(faceOf(name).smile), name);
const half = blendFace(faceOf("sad"), faceOf("happy"), 0.5);
assert.ok(half.smile > faceOf("sad").smile && half.smile < faceOf("happy").smile);
});
it("ajuste fino por cima de uma expressão", () => {
assert.equal(faceOf("neutral", { smile: 0.8, browL: { y: -6 } }).browL.y, -6);
});
});
describe("linha do tempo", () => {
it("cue = palavra falada; atP = fração do trecho", () => {
assert.equal(startOf({ do: "nod", cue: "nao" }, 4, words), 0.8);
assert.equal(startOf({ do: "nod", atP: 0.5 }, 4, words), 2);
assert.equal(startOf({ do: "nod", cue: "inexistente", at: 1 }, 4, words), 1);
});
it("andar chega ao destino e vira para o lado certo; é determinístico", () => {
const actor = { x: 0.7, timeline: [{ do: "walk" as const, at: 0, to: 0.3, dur: 1 }] };
const end = evaluate(actor, 2, 4);
assert.ok(Math.abs(end.x - 0.3) < 1e-9);
assert.equal(end.flip, true);
assert.deepEqual(evaluate(actor, 0.5, 4), evaluate(actor, 0.5, 4));
});
it("trocar expressão é suave e permanente", () => {
const actor = { x: 0.5, timeline: [{ do: "express" as const, at: 1, expression: "happy", dur: 0.4 }] };
const mid = evaluate(actor, 1.2, 4).face.smile;
assert.ok(mid > faceOf("neutral").smile && mid < faceOf("happy").smile);
assert.ok(Math.abs(evaluate(actor, 3, 4).face.smile - faceOf("happy").smile) < 1e-9);
});
it("pular sobe e volta ao chão", () => {
const actor = { x: 0.5, timeline: [{ do: "jump" as const, at: 0, dur: 1 }] };
assert.ok(evaluate(actor, 0.5, 4).dy < -0.05);
assert.equal(evaluate(actor, 2, 4).dy, 0);
});
it("valida a linha do tempo", () => {
assert.deepEqual(validateTimeline([{ do: "walk", to: 0.3 }]), []);
assert.match(validateTimeline([{ do: "voar" }]).join(), /do:/);
});
});
describe("fala: boca pelas letras, expressão mantida", () => {
it("m fecha, a abre, o arredonda; fora das palavras fica fechada", () => {
assert.equal(visemeAt(words, 0.21).open, 0); // "M" do começo
assert.ok(visemeAt([{ text: "aaa", startS: 0, endS: 1 }], 0.5).open > 0.7);
assert.ok(visemeAt([{ text: "oo", startS: 0, endS: 1 }], 0.5).round > 0.6);
assert.equal(visemeAt(words, 3).open, 0);
});
it("falando bravo continua bravo (sobrancelhas e cantos da boca)", () => {
const angry = faceOf("angry");
const talking = speak(angry, visemeAt([{ text: "aaa", startS: 0, endS: 1 }], 0.5));
assert.equal(talking.browL.tilt, angry.browL.tilt);
assert.equal(talking.smile, angry.smile);
assert.ok(talking.mouthOpen > 0.5);
});
it("a ação falar vai da palavra de início até o fim da palavra final", () => {
const actor = { x: 0.5, timeline: [{ do: "talk" as const, cue: "mamae", cueEnd: "ouviu" }] };
assert.ok(evaluate(actor, 0.45, 4, 1, { words }).face.mouthOpen > 0.2);
assert.ok(evaluate(actor, 2.5, 4, 1, { words }).face.mouthOpen < 0.05);
});
it("com o volume do áudio, a boca fecha na pausa", () => {
const env = { fps: 10, values: Array.from({ length: 20 }, (_, i) => (i === 5 ? 0 : 0.9)) };
const loud = visemeAt([{ text: "aaaaaaaaaa", startS: 0, endS: 2 }], 0.25, env).open;
const pause = visemeAt([{ text: "aaaaaaaaaa", startS: 0, endS: 2 }], 0.55, env).open;
assert.ok(loud > 0.5 && pause < 0.2);
});
});
+37
View File
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { SAMPLE } from "../src/sample";
import { layoutPlace, resolveLight } from "../src/places";
import { validateSpec, type ShotSpec } from "../src/spec";
const place = (elements: NonNullable<ShotSpec["place"]>["elements"], indoor = true): ShotSpec =>
({ ...SAMPLE, scene: { kind: "place" }, palette: "night", place: { ground: "floor", indoor, elements } }) as ShotSpec;
describe("lugar por peças: luz e regras de posição", () => {
it("lightSource é opcional e conferido; specs antigos continuam válidos", () => {
assert.deepEqual(validateSpec({ ...SAMPLE, lightSource: { kind: "window", x: 0.1, y: 0.3 } }), []);
assert.match(validateSpec({ ...SAMPLE, lightSource: { kind: "lanterna", x: 0.1 } }).join(), /lightSource/);
assert.match(validateSpec({ ...SAMPLE, lightSource: { kind: "lamp", x: 3 } }).join(), /lightSource/);
assert.deepEqual(validateSpec({ ...SAMPLE, light: "spot" }), []);
});
it("peças novas existem; janela/quadro grudam na parede e a luminária de mesa sobe na escrivaninha", () => {
const spec = place([{ kind: "window", x: 0.2, z: 0.1 }, { kind: "desk", x: 0.6, z: 0.4 }, { kind: "desklamp", x: 0.7, z: 0.4 }, { kind: "frame", x: 0.5 }]);
assert.deepEqual(validateSpec(spec), []);
const { items, horizon } = layoutPlace(spec);
const by = (k: string) => items.find((it) => it.e.kind === k)!;
assert.equal(by("window").y, horizon);
assert.equal(by("frame").zEff, 1);
assert.ok(by("desklamp").y < by("desk").y - 200, "a luminária fica em cima do tampo");
assert.ok(items.indexOf(by("desklamp")) > items.indexOf(by("desk")), "e é desenhada depois da mesa");
});
it("fonte de luz: explícita > pendente > janela; 'none' desliga", () => {
const spec = place([{ kind: "pendant", x: 0.5, z: 0.5 }, { kind: "window", x: 0.15 }]);
assert.equal(resolveLight(spec, undefined)?.kind, "lamp");
assert.equal(resolveLight(place([{ kind: "window", x: 0.15 }]), undefined)?.kind, "window");
assert.equal(resolveLight({ ...spec, lightSource: { kind: "sun", x: 0.2 } }, undefined)?.kind, "sun");
assert.equal(resolveLight(spec, "none"), null);
assert.equal(resolveLight(place([]), "spot")?.kind, "lamp");
});
});
+59 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { captionChunks } from "../src/overlays";
import { captionChunks, countUp, hudClock, hudValueTone } from "../src/overlays";
import { SAMPLE } from "../src/sample";
import { frameCount, validateSpec } from "../src/spec";
@@ -31,3 +31,61 @@ describe("spec do Cartoon", () => {
assert.deepEqual(chunks, ["Num apagão,", "a casa acesa", "chama atenção."]);
});
});
describe("grafismo do Cartoon: cartelas, cartão de nome e HUD", () => {
const ok = (texts: unknown[], extra: Record<string, unknown> = {}) => validateSpec({ ...SAMPLE, ...extra, texts });
const base = { x: 0.5, y: 0.4, atS: 0.2 };
it("aceita os kinds novos bem formados (e o stat/lista sem título)", () => {
assert.deepEqual(ok([
{ kind: "namecard", text: "Seu Amaro", lines: ["Roupeiro há 38 anos", "7 meses sem salário"], ...base },
{ kind: "stat", text: "No caixa", value: "R$ 0", tone: "danger", panel: true, ...base },
{ kind: "stat", text: "", value: 61, ...base },
{ kind: "counter", text: "Na fila", value: "297", ...base },
{ kind: "checklist", text: "", size: 0.5, items: [{ text: "Funcionários", state: "checked" }, { text: "Elenco", state: "crossed" }, { text: "Registro" }], ...base },
{ kind: "table", text: "", highlight: 1, items: [{ text: "Atlético", value: "31" }, { text: "Vila Nova", value: "4" }], ...base },
{ kind: "progress", text: "Talento", value: 97, ...base },
{ kind: "progress", text: "Talento", value: "97%", ...base },
{ kind: "grid", text: "Com contrato", value: 4, total: 18, ...base },
]), []);
});
it("recusa kind desconhecido, lista vazia, estado, destaque, porcentagem e grade inválidos", () => {
const errors = ok([
{ kind: "slide", text: "x", ...base },
{ kind: "checklist", text: "", items: [], ...base },
{ kind: "checklist", text: "", items: [{ text: "a", state: "talvez" }], ...base },
{ kind: "table", text: "", items: [{ text: "a", value: "1" }], highlight: 3, ...base },
{ kind: "progress", text: "Talento", value: 140, ...base },
{ kind: "grid", text: "Com contrato", value: 20, total: 18, ...base },
{ kind: "stat", text: "No caixa", ...base },
{ kind: "namecard", text: "", ...base },
{ kind: "grid", text: "g", value: 1, total: 4, size: 9, ...base },
]).join(" | ");
for (const re of [/texts\[0\]: kind/, /texts\[1\]: items/, /texts\[2\]\.items\[0\]: state/, /texts\[3\]: highlight/, /texts\[4\]: progress/,
/texts\[5\]: grid/, /texts\[6\]: stat precisa de value/, /texts\[7\]: texto vazio/, /texts\[8\]: size/]) assert.match(errors, re);
});
it("HUD: campos antigos continuam valendo; novos são opcionais e conferidos", () => {
assert.deepEqual(validateSpec({ ...SAMPLE, hud: { badge: "DIA 3", label: "Vila Nova" } }), []);
assert.deepEqual(validateSpec({ ...SAMPLE, hud: { badge: "Dia 1", label: "x", clock: "10:06", clockMinutesPerSecond: 1, place: "Vila Nova (MG)",
value: "R$ 0,00", valueLabel: "Caixa", valueTone: "danger", note: "Estreia em 30 dias" } }), []);
assert.match(validateSpec({ ...SAMPLE, hud: { badge: "Dia 1", label: "x", valueTone: "roxo" } }).join(), /hud.valueTone/);
assert.match(validateSpec({ ...SAMPLE, hud: { badge: 3, label: "x" } }).join(), /hud: badge/);
});
it("número contando, hora andando e cor do valor do HUD são funções puras", () => {
assert.equal(countUp("R$ 134.273", 0.5), "R$ 67.137");
assert.equal(countUp("R$ 134.273", 1), "R$ 134.273");
assert.equal(countUp("-R$ 47.312.904", 0), "-R$ 0");
assert.equal(countUp("R$ 0", 0.3), "R$ 0");
assert.equal(countUp("Vila Nova", 0.3), "Vila Nova");
assert.equal(hudClock("10:06", 2.5, 2), "10:11");
assert.equal(hudClock("23:59", 1, 2), "00:01");
assert.equal(hudClock("10:06", 9), "10:06");
assert.equal(hudValueTone("R$ 0,00"), "danger");
assert.equal(hudValueTone("-12"), "danger");
assert.equal(hudValueTone("R$ 800"), undefined);
assert.equal(hudValueTone("R$ 800", "info"), "info");
});
});
+51 -10
View File
@@ -2,7 +2,7 @@
Serviço local do CenaForge (`127.0.0.1:4520`, faixa 4500–4599) que assiste lives da **Twitch, YouTube e Kick**,
lê o **chat em tempo real**, transcreve a fala com o **Whisper** (serviço de voz, 4510), pede a uma **IA pela CLI**
(Codex/GPT por padrão, ou Claude) que confirme o momento e gera **cortes com legenda queimada**: verticais 1080×1920
(Codex/GPT por padrão, Claude ou Gemini) que confirme o momento e gera **cortes com legenda queimada**: verticais 1080×1920
(Shorts/Reels/TikTok, padrão) ou horizontais 1920×1080 (YouTube "tela grande", mostrando o próprio jogo).
O painel (`/clipper`) mostra a fila para aprovar. As contas que recebem os cortes de cada canal são ligadas na
página **Contas**, como as histórias.
@@ -60,14 +60,41 @@ chegar (`wall_end`), então a pausa do Streamlink ao filtrar anúncio da Twitch
teto de 45 s além dele (passou disso, mostra "aguardando o bloco"); "Agora na live" mostra a contagem para o próximo
resumo da varredura, com o intervalo vindo de `GET /v1/status` → `judge.options.scanIntervalS`.
**Parar é parar (18/11/2026).** `POST /v1/sessions/{id}/stop` à mão pausa o monitor da fonte
(`channels.monitor_paused_at` + `monitor_paused_session`): o monitor não abre sessão nova enquanto a live continuar
no ar. Religa com `PATCH /v1/channels/{id}` `{monitor: true}`, gravando pelo link (`POST /v1/sessions`) ou retomando
a sessão pelo painel. `{"pauseMonitor": false}` no corpo do stop mantém o monitor ligado. Queda de live (captura cai
sozinha) continua retomando **na mesma sessão** (`keep_live`), sem passar pela pausa.
**Idioma por fonte e por sessão.** `language` em `channels` e `sessions` (`pt-BR`, `en-US`, `es-419`; vazio = `CLIPPER_LANGUAGE`).
A sessão herda o da fonte; a transcrição manda esse idioma ao Whisper. **Fonte em inglês** (18/11/2026): os juízes
trabalham em inglês (prompts, glossário de chat e saída em inglês) e devolvem na mesma resposta um bloco `pt` para o
painel; a fala do corte é traduzida por frase (`clips.translation_json`) e `caption.translation` (só para testar) põe o
português embaixo da legenda. Regras completas: `doc/clipador/IDIOMAS.md`. Espanhol continua com a linha "Idioma de
saída: …" no contexto.
## Contexto do jogo
- Categoria da plataforma (Streamlink `--json`, `metadata.category`) no início e a cada 10 min (troca registrada em
`games_json`). Sem categoria (YouTube/VOD), o jogo vem da tela (`screen_game` da varredura). A IA também diz o que
vê na tela; divergência (categoria "ROB RUN", tela "GTA V") vai para o contexto dos juízes.
- **Detecção automática** (18/11/2026, `doc/clipador/DETECCAO-JOGO.md`): a cada ~3 min o Clipador cruza categoria da
plataforma (Streamlink `--json`), título, o que a IA lê na tela (`screen_game` + confiança + evidência, da varredura),
chat e fala (jogos cadastrados) e decide: `agreed` / `probable` / `conflict` / `unknown` (`sessions.game_status`,
pistas em `game_detect_json`). Categoria genérica (Just Chatting) não é jogo. Conflito (categoria "ROB RUN", tela
"GTA V") mantém o jogo e o painel pergunta. Jogo confirmado por você não muda sozinho (vira `suggestion`).
`POST /v1/sessions/{id}/game/detect` = "Detectar agora". Trocas ficam em `games_json`.
- **Perfil do jogo** pesquisado na web pela CLI (`codex --search`), guardado por jogo (tabela `games`): resumo,
mecânicas, o que rende corte, o que não rende, gírias, novidades, fontes. Medido: ~15–35 s por jogo.
- Correção manual: `PUT /v1/sessions/{id}/game` (trava a troca automática).
- **Dois idiomas** (v12, `doc/clipador/JOGOS.md`): a pesquisa é feita e guardada **em inglês** (`profile_ai_json`,
é o que vai nos prompts) e traduzida para **português** (`profile_json`, o que o painel mostra). Editar à mão
(`PUT /v1/games/{id}?lang=pt|en`) ou pedir à IA (`refine`, resposta em português) atualiza um e traduz o outro;
jogo antigo ganha a versão em inglês com `POST /v1/games/{id}/translate`.
- O perfil tem **missões** (só se a lista for pública; nunca inventadas) com **gatilhos de fim** e sinais gerais de
fim de missão (`end_triggers`). O contexto leva até 25 missões (~1500 caracteres) e manda terminar o corte de
missão logo depois do gatilho. **Outros nomes** (`aliases`): categoria "Grand Theft Auto VI" e tela "GTA 6" caem
no mesmo perfil.
- Cadastrar pelo painel: `POST /v1/games {name, notes?}` (pesquisa em segundo plano; 409 se já existe, inclusive por
outro nome) · apagar: `DELETE /v1/games/{id}`. **Sementes** em `app/seeds/games/*.json` (ex.: GTA VI) entram na
subida só se o jogo ainda não existe; nunca sobrescrevem a sua edição.
## Configuração do corte (layout, câmera, legenda)
@@ -348,14 +375,15 @@ Validação forte (`editor.validate_project`): limites de duração (3–180 s)
tentativa em 5 min.
- **API**: `GET /v1/sessions/{id}/face?from=&to=` (série, `signal`, picos, câmera, progresso) e `POST …/face/reset`.
## Juiz de IA (pela CLI, sem chave de API)
## Juiz de IA (pela CLI)
Usa as CLIs já logadas no PC — as mesmas da página Agente:
Usa as CLIs do PC — as mesmas da página Agente:
| Provedor | Comando | Modelo padrão | Lista de modelos |
|---|---|---|---|
| `codex` (padrão) | `codex exec --ephemeral --sandbox read-only --output-schema … -o … -` | `gpt-6-luna` (rápido e barato) | `~/.codex/models_cache.json` (só `visibility: list`) |
| `claude` | `claude -p --json-schema … --no-session-persistence` (imagens pela ferramenta Read; web por WebSearch) | `haiku` | `haiku`, `sonnet`, `opus` |
| `gemini` | `gemini -p … -o json --approval-mode plan --skip-trust -m …` (schema no prompt; imagens por `@arquivo`) | `gemini-3.5-flash` | `gemini-3.5-flash`, `gemini-3.1-flash-lite`, `gemini-2.5-pro` |
| `off` | — | — | só a heurística |
Codex: imagens com `-i` (uma por flag, antes de `-`), busca na web com `--search` (opção global, antes de `exec`).
@@ -364,6 +392,18 @@ Provedor, modelo do editor, **modelo do analista** (`analystModel`, vazio = o me
reiniciar. O `.env` só dá os valores iniciais. Medido (16/11/2026): `gpt-6-luna` respondeu em ~7 s por candidato.
Falha do juiz não perde o momento: o corte segue pela heurística e o erro fica em `judge.error`.
**Gemini, login/chave e IA reserva (18/11/2026)** — contrato em [`doc/ia.md`](../doc/ia.md). O painel
(Configurações → IA) grava `data/ai/settings.json` (IAs ligadas, `authMode` `oauth`/`apiKey`, `order`, `fallback`) e
`data/ai/vault.bin` (chaves, DPAPI do usuário); o Clipador só lê (`app/ai_settings.py`, relê pelo mtime) e monta o
`env` de cada chamada (a chave só vale para aquela chamada). Se a IA escolhida falhar por **indisponibilidade**
(cota, 429/529/503, login/chave, rede, CLI ausente, tempo esgotado — `judge.is_availability_error`), a próxima da
`order` ligada, com CLI e com chave tenta com o **modelo padrão dela**, e a que caiu fica em pausa `cooldownMin` (em
memória). Erro de conteúdo (JSON inválido, campo faltando) não troca. `judge.model` do corte = quem de fato
respondeu; `GET /v1/judge` traz `fallback.chain`, `pauses` e `unavailableReason`. Gemini: sem `--output-schema`, o
JSON é extraído da resposta; o corpo vai pelo stdin e o `-p` leva só a instrução curta e os `@frame-NN.jpg`; roda
numa pasta temporária FORA do repo (o `@arquivo` respeita o .gitignore, que ignora `data/`), com as imagens copiadas.
OAuth do Gemini para conta pessoal foi encerrado pelo Google: use chave de API do AI Studio.
## Instalação e subida
- `setup.bat` cria `clipper/.venv` (Python 3.12 via uv), instala `requirements.txt` (Streamlink 8.6.3) e gera
@@ -386,7 +426,7 @@ Precisa do FFmpeg com `libass` (legenda) — o build `essentials` do gyan.dev te
| `CLIPPER_SEGMENT_S` | 30 | tamanho do bloco gravado |
| `CLIPPER_POLL_S` | 60 | intervalo para checar se um canal monitorado entrou ao vivo |
| `CLIPPER_KEEP_HOURS` | 6 | apaga blocos mais velhos que isto se nenhum corte pendente precisar (0 = nunca) |
| `CLIPPER_LANGUAGE` | `pt-BR` | idioma da transcrição |
| `CLIPPER_LANGUAGE` | `pt-BR` | idioma padrão da transcrição e dos textos da IA (cada fonte/sessão pode ter o seu: `language`) |
| `CLIPPER_ENCODER` | `auto` | `auto` (NVENC se houver) · `libx264` · `h264_nvenc` |
| `CLIPPER_JUDGE_PROVIDER` / `_MODEL` / `_MIN_SCORE` | `codex` / (padrão) / 6 | valores iniciais do juiz |
| `CLIPPER_DATA_DIR` | `data/clipper` | banco, blocos gravados, modelos do rastreio e arquivos do juiz; para isolar uma instância de teste (relativo ao repo ou absoluto, **dentro** do repo) |
@@ -404,14 +444,15 @@ chave `clipper-<sessão>-<bloco>`; num banco novo as sessões recomeçam do 1 e
|---|---|
| `GET /health` | sem chave |
| `GET /v1/status` | ferramentas, voz, juiz, gravações ativas |
| `GET/PUT /v1/judge` | provedor, modelos (editor/analista), nota mínima, varredura, visão, câmera (+ lista de modelos) |
| `GET/PUT /v1/judge` | Equipe de IA (`roles`: varredura, analista, editor, juiz — provedor, modelo, esforço, liga/desliga, instruções do administrador; `roleDefaults` = instruções padrão), nota mínima, varredura, visão, câmera, `timelineJson` (+ lista de modelos) — doc/clipador/EQUIPE-IA.md |
| `GET /v1/judge/report?days=&session=` | medição: chamadas e tokens por papel/IA por hora de live, aprovação, decisões do juiz de contexto, concordância juiz × dono |
| `GET/PUT /v1/channels/{id}/settings` · `GET/PUT /v1/sessions/{id}/settings` | configuração do corte: `own`, `effective`, `defaults` (com `format`, `duration` e `hook`), `modes`, `fonts`, `fontFiles` (`{família: "assets/fonts/…ttf"}` das empacotadas, relativo à raiz do repositório), `hookStyles`, `hookAnims`, `aspects`, `frames` (`{vertical, horizontal: {width, height, canvasWidth, canvasHeight}}`, para o painel desenhar a prévia) e `captureQualities` (`[{id, label, maxHeight, gbPerHour, gbPerHourMax, hint}]`) |
| `GET /v1/sessions/{id}/frame?t=` · `POST …/preview` · `POST …/detect-cam[?ai=true]` | quadro para o editor, prévia do layout, achar webcam (local primeiro) |
| `GET /v1/sessions/{id}/face?from=&to=` · `POST …/face/reset` | série por segundo do rosto (cx/cy/size no quadro inteiro, expressões, `signal`) e picos; refazer o rastreio |
| `PUT /v1/sessions/{id}/game` · `GET /v1/games` · `POST /v1/games/{id}/research` · `PUT /v1/games/{id}` · `POST /v1/games/{id}/refine` · `DELETE /v1/games/{id}/notes/{n}` | jogo da sessão, perfis pesquisados, edição à mão e pedidos à IA |
| `GET /v1/emotes?channel=twitch-<login>` | emotes do canal, usos e peso aprendido |
| `GET/POST /v1/channels` · `PATCH/DELETE /v1/channels/{id}` · `POST /v1/channels/{id}/check` | canais (`monitor` grava sozinho ao entrar ao vivo; `authorized` = streamer autorizou) |
| `GET/POST /v1/sessions` · `GET/DELETE /v1/sessions/{id}` · `POST …/stop` | gravar live ou processar VOD pelo link; cada sessão traz `capture` (resolução, qps, codec e taxa gravados de fato; `null` = sessão antiga) |
| `GET/POST /v1/channels` · `PATCH/DELETE /v1/channels/{id}` · `POST /v1/channels/{id}/check` | canais (`monitor` grava sozinho ao entrar ao vivo; `authorized` = streamer autorizou; `language`; `monitorPausedAt`/`monitorPausedBySession` = monitor pausado porque você parou uma sessão; `PATCH {monitor: true}` religa) |
| `GET/POST /v1/sessions` · `GET/DELETE /v1/sessions/{id}` · `POST …/stop` `{pauseMonitor?: true}` | gravar live ou processar VOD pelo link (`language` opcional; herda o da fonte); parar à mão pausa o monitor da fonte; cada sessão traz `language` e `capture` (resolução, qps, codec e taxa gravados de fato; `null` = sessão antiga) |
| `GET /v1/sessions/{id}/timeline` | mensagens/s, razão do chat e volume por segundo |
| `POST /v1/sessions/{id}/clips` | **cortar agora**: `{lastS}` ou `{startS,endS}`; corte manual nunca é descartado pela IA |
| `GET /v1/clips?status=&session=` · `GET/PATCH /v1/clips/{id}` · `POST …/render` · `POST …/rejudge` | fila de cortes; cada corte traz `aspect` (`vertical` ou `horizontal`) = formato em que o arquivo foi renderizado |
+273
View File
@@ -0,0 +1,273 @@
"""Configuração das IAs (Claude, Codex, Gemini) compartilhada com o painel — contrato em `doc/ia.md`.
O painel (Configurações → IA) escreve dois arquivos em `data/ai/`; o Clipador só LÊ:
- `settings.json` (sem segredo): quais IAs estão ligadas, modo de login (`oauth`/`apiKey`), ordem da reserva e
pausa depois de uma falha de indisponibilidade. Relido quando o `mtime` muda; ausente/inválido = padrão.
- `vault.bin`: as chaves de API, JSON cifrado com a DPAPI do Windows (usuário atual, entropia própria).
Daqui sai o ambiente (`env`) de cada chamada de CLI: no modo chave, a variável da chave só vale para a chamada;
no modo login, a variável é removida para a CLI usar a sessão já logada. O login global de cada CLI não muda.
Nos testes, a pasta e o cifrador são injetados (`AiConfig(folder, cipher=...)`); a DPAPI real só existe no Windows.
"""
from __future__ import annotations
import copy
import json
import logging
import os
import sys
import threading
import time
from datetime import datetime
from pathlib import Path
from typing import Protocol
from .config import REPO_ROOT
log = logging.getLogger("cenaforge_clipper.ai_settings")
AI_PROVIDERS = ("claude", "codex", "gemini")
# Pasta padrão dos arquivos do painel. Os testes trocam (conftest) para não ler o data/ai real.
DEFAULT_AI_DIR = REPO_ROOT / "data" / "ai"
# Leitura de uso mais velha que isso não decide (o painel relê a cada 5 min).
USAGE_STALE_S = 30 * 60
AUTH_MODES = ("oauth", "apiKey")
DEFAULT_COOLDOWN_MIN = 15.0
DEFAULT_SETTINGS: dict = {
"version": 1,
"providers": {
"claude": {"enabled": True, "authMode": "oauth"},
"codex": {"enabled": True, "authMode": "oauth"},
"gemini": {"enabled": False, "authMode": "apiKey"},
},
"order": ["claude", "codex", "gemini"],
"fallback": {"enabled": True, "cooldownMin": DEFAULT_COOLDOWN_MIN},
}
# Variável de ambiente da chave de API de cada CLI (tabela "Ambiente de cada chamada" do doc/ia.md).
API_KEY_ENV = {"claude": "ANTHROPIC_API_KEY", "codex": "CODEX_API_KEY", "gemini": "GEMINI_API_KEY"}
GEMINI_OAUTH_ENV = "GOOGLE_GENAI_USE_GCA"
# Entropia do cofre de IA (a mesma que o painel usa ao cifrar). Não é senha: só separa este cofre dos outros.
_VAULT_ENTROPY = b"CenaForge.AI.vault.v1"
class AiVaultError(RuntimeError):
"""O cofre de IA não abriu (outro usuário/máquina, corrompido, ou DPAPI indisponível)."""
class Cipher(Protocol):
def unprotect(self, data: bytes) -> bytes: ...
class DpapiCipher:
"""DPAPI via ctypes (crypt32.dll), só a decifragem — quem cifra é o painel. Mesmo padrão de
`publisher/app/vault.py` (pacotes separados: o código é copiado, não importado)."""
CRYPTPROTECT_UI_FORBIDDEN = 0x01
def __init__(self, entropy: bytes = _VAULT_ENTROPY) -> None:
if sys.platform != "win32":
raise AiVaultError("O cofre de IA usa a DPAPI do Windows; este sistema não tem.")
import ctypes
from ctypes import wintypes
class DataBlob(ctypes.Structure):
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
self._entropy = entropy
self._ctypes = ctypes
self._blob = DataBlob
self._crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
self._kernel32.LocalFree.argtypes = [ctypes.c_void_p]
self._kernel32.LocalFree.restype = ctypes.c_void_p
fn = self._crypt32.CryptUnprotectData
fn.argtypes = [ctypes.POINTER(DataBlob), ctypes.c_void_p, ctypes.POINTER(DataBlob), ctypes.c_void_p,
ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(DataBlob)]
fn.restype = wintypes.BOOL
def _to_blob(self, data: bytes):
buffer = self._ctypes.create_string_buffer(data, len(data))
blob = self._blob(len(data), self._ctypes.cast(buffer, self._ctypes.POINTER(self._ctypes.c_char)))
return blob, buffer # o buffer precisa continuar vivo enquanto o blob for usado
def unprotect(self, data: bytes) -> bytes:
ctypes = self._ctypes
in_blob, _keep_in = self._to_blob(data)
entropy, _keep_entropy = self._to_blob(self._entropy)
out_blob = self._blob()
ok = self._crypt32.CryptUnprotectData(ctypes.byref(in_blob), None, ctypes.byref(entropy), None, None,
self.CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out_blob))
if not ok:
raise AiVaultError(f"A DPAPI do Windows não conseguiu abrir o cofre de IA (erro {ctypes.get_last_error()}). "
"O arquivo pode ser de outro usuário ou de outro computador.")
try:
return ctypes.string_at(out_blob.pbData, out_blob.cbData)
finally:
self._kernel32.LocalFree(out_blob.pbData)
def normalize_settings(raw: object) -> dict:
"""Valida o settings.json do painel campo a campo. O que faltar ou vier errado fica no padrão do doc."""
settings = copy.deepcopy(DEFAULT_SETTINGS)
if not isinstance(raw, dict):
return settings
providers = raw.get("providers")
if isinstance(providers, dict):
for name in AI_PROVIDERS:
item = providers.get(name)
if not isinstance(item, dict):
continue
if isinstance(item.get("enabled"), bool):
settings["providers"][name]["enabled"] = item["enabled"]
if item.get("authMode") in AUTH_MODES:
settings["providers"][name]["authMode"] = item["authMode"]
order = raw.get("order")
if isinstance(order, list):
known = [p for p in dict.fromkeys(order) if p in AI_PROVIDERS]
# Quem ficou de fora da lista vai para o fim, na ordem padrão (a lista sempre tem as três).
settings["order"] = known + [p for p in AI_PROVIDERS if p not in known]
fallback = raw.get("fallback")
if isinstance(fallback, dict):
if isinstance(fallback.get("enabled"), bool):
settings["fallback"]["enabled"] = fallback["enabled"]
cooldown = fallback.get("cooldownMin")
if isinstance(cooldown, (int, float)) and not isinstance(cooldown, bool) and cooldown >= 0:
settings["fallback"]["cooldownMin"] = float(cooldown)
return settings
def _mtime(path: Path) -> int | None:
try:
return path.stat().st_mtime_ns
except OSError:
return None
class AiConfig:
"""Leitura (com cache por mtime) do settings.json e do vault.bin do painel."""
def __init__(self, folder: Path | None = None, cipher: Cipher | None = None,
environ: dict[str, str] | None = None):
self.folder = Path(folder) if folder is not None else DEFAULT_AI_DIR
self._cipher = cipher
self._environ = environ # None = os.environ do momento da chamada
self._lock = threading.RLock()
self._settings_cache: tuple[int | None, dict] | None = None
self._keys_cache: tuple[int | None, dict[str, str]] | None = None
self.vault_error: str | None = None
@property
def settings_path(self) -> Path:
return self.folder / "settings.json"
@property
def vault_path(self) -> Path:
return self.folder / "vault.bin"
def settings(self) -> dict:
"""Configuração atual (cópia). Relê o arquivo só quando o mtime muda."""
with self._lock:
stamp = _mtime(self.settings_path)
if self._settings_cache is None or self._settings_cache[0] != stamp:
raw: object = None
if stamp is not None:
try:
raw = json.loads(self.settings_path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
log.warning("data/ai/settings.json inválido (%s); usando o padrão", exc)
self._settings_cache = (stamp, normalize_settings(raw))
return copy.deepcopy(self._settings_cache[1])
def provider(self, name: str) -> dict:
return self.settings()["providers"].get(name, {"enabled": False, "authMode": "oauth"})
@property
def usage_path(self) -> Path:
return self.folder / "usage.json"
def over_limit(self, provider: str, now: float | None = None) -> str | None:
"""Motivo para a IA sair da frente pelo USO (None = livre), lido de data/ai/usage.json, que o painel grava
a cada 5 min (Claude pelo /usage, Codex pelo app-server; ver doc/ia.md). Mesma regra do painel
(`overLimit` em lib/ai.ts): bateu o limite, ou uma janela ainda valendo em `limitPercent` ou mais.
Leitura com mais de 30 min, arquivo ausente ou inválido: não decide nada."""
now = time.time() if now is None else now
try:
data = json.loads(self.usage_path.read_text(encoding="utf-8"))
usage = data["providers"][provider]
at = datetime.fromisoformat(str(usage["at"]).replace("Z", "+00:00")).timestamp()
except (OSError, ValueError, KeyError, TypeError):
return None
if now - at > USAGE_STALE_S:
return None
live = []
for window in usage.get("windows") or []:
resets = window.get("resetsAt")
try:
if resets and datetime.fromisoformat(str(resets).replace("Z", "+00:00")).timestamp() <= now:
continue
live.append((str(window.get("label", "janela")), float(window.get("usedPercent", 0))))
except (ValueError, TypeError):
continue
hit = [label for label, used in live if used >= 100]
if usage.get("blocked") and hit:
return f"bateu o limite ({', '.join(hit)})"
try:
limit = float(data.get("limitPercent", 90))
except (TypeError, ValueError):
limit = 90.0
hot = sorted((w for w in live if w[1] >= limit), key=lambda w: -w[1])
return f"{hot[0][0]} em {round(hot[0][1])}% (limite {round(limit)}%)" if hot else None
def api_keys(self) -> dict[str, str]:
"""Chaves do cofre (só as que existem). Cofre ausente = {}; cofre que não abre = {} e `vault_error`."""
with self._lock:
stamp = _mtime(self.vault_path)
if self._keys_cache is None or self._keys_cache[0] != stamp:
self._keys_cache = (stamp, self._read_vault() if stamp is not None else {})
if stamp is None:
self.vault_error = None
return dict(self._keys_cache[1])
def _read_vault(self) -> dict[str, str]:
try:
raw = self.vault_path.read_bytes()
if not raw:
self.vault_error = None
return {}
cipher = self._cipher or DpapiCipher()
data = json.loads(cipher.unprotect(raw).decode("utf-8"))
except Exception as exc: # noqa: BLE001 - cofre ilegível não derruba o juiz: segue sem chaves
self.vault_error = str(exc)[:200] or "cofre de IA ilegível"
log.warning("não abri data/ai/vault.bin: %s", self.vault_error)
return {}
self.vault_error = None
if not isinstance(data, dict):
return {}
return {k: v.strip() for k, v in data.items() if k in AI_PROVIDERS and isinstance(v, str) and v.strip()}
def has_key(self, provider: str) -> bool:
return bool(self.api_keys().get(provider))
def provider_env(self, provider: str) -> dict[str, str]:
"""Ambiente da chamada da CLI de `provider`, conforme o modo de login (tabela do doc/ia.md)."""
env = dict(os.environ if self._environ is None else self._environ)
key_var = API_KEY_ENV.get(provider)
if not key_var:
return env
mode = self.provider(provider).get("authMode", "oauth")
if mode == "apiKey":
key = self.api_keys().get(provider)
if key:
env[key_var] = key
else:
env.pop(key_var, None)
if provider == "gemini":
env.pop(GEMINI_OAUTH_ENV, None)
else:
env.pop(key_var, None)
if provider == "gemini":
env[GEMINI_OAUTH_ENV] = "true"
return env
+104 -22
View File
@@ -1,8 +1,11 @@
"""Leitura do chat ao vivo, em tempo real, para medir a reação do público.
- Twitch: IRC anônimo (irc.chat.twitch.tv:6697, apelido `justinfanNNNN`): só leitura, sem conta nem token.
- Kick: websocket público do Pusher usado pelo site (`chatrooms.<id>.v2`). Não é API oficial: pode mudar
sem aviso e o Cloudflare às vezes bloqueia a consulta do id da sala.
- Kick: o mesmo tempo real que o site usa (não é API oficial: pode mudar sem aviso). Desde 11/2026 a Kick
escolhe o provedor por canal (`POST web.kick.com/api/v1/realtime/channels/<id>/chat/connection`): hoje responde
**Centrifugo** (token de convidado em `/v1/realtime/auth/connection`, sem login) e o Pusher com a chave fixa antiga
passou a recusar ("App key not in this cluster"). O canal continua `chatrooms.<sala>.v2` e a mensagem tem o mesmo
formato. O Cloudflare às vezes bloqueia a consulta do id da sala.
- YouTube: ler o chat exige a API do YouTube (cota) — ainda não suportado; a sessão segue pelo áudio.
Cada leitor roda numa thread, reconecta sozinho e entrega lotes de (instante, usuário, texto) com o relógio
@@ -19,6 +22,7 @@ import socket
import ssl
import threading
import time
import uuid
from typing import Callable
import httpx
@@ -31,7 +35,25 @@ OnMessages = Callable[[list[tuple[float, str, str, list[str]]]], None]
_PRIVMSG = re.compile(r"^(?:@(\S+) )?:([^!\s]+)!\S+ PRIVMSG #\S+ :(.*)$")
_ROOM_ID = re.compile(r"(?:^@|;)room-id=(\d+)")
KICK_PUSHER = "wss://ws-us2.pusher.com/app/32cbd69e4b950bf97679?protocol=7&client=js&version=8.4.0&flash=false"
KICK_API = "https://web.kick.com/api/v1/realtime"
KICK_HEADERS = {"User-Agent": "Mozilla/5.0", "Accept": "application/json", "Origin": "https://kick.com"}
# Pedido do site ao escolher o provedor (os dois que ele aceita). Medido 18/11/2026: a resposta é Centrifugo.
KICK_CAPABILITIES = {"accepted_providers": [{"provider": "pusher"}, {"provider": "centrifugo"}]}
KICK_CENTRIFUGO_DEFAULT = "wss://realtime.us-west-2.platform.kick.com/connection/websocket"
_KICK_EMOTE = re.compile(r"\[emote:\d+:([^\]]+)\]")
def kick_message(event: str, payload: object) -> tuple[str, str, list[str]] | None:
"""Mensagem de chat da Kick → (usuário, texto, emotes), ou None se o evento não é mensagem. O `data` vem como
texto JSON (Pusher e Centrifugo). Emotes chegam como [emote:123:NOME]: fica só o nome, que carrega a reação."""
if not str(event).endswith("ChatMessageEvent"):
return None
data = json.loads(payload) if isinstance(payload, str) else (payload or {})
if not isinstance(data, dict):
return None
content = str(data.get("content") or "")
user = str((data.get("sender") or {}).get("username") or "")
return user, _KICK_EMOTE.sub(r"\1", content)[:300], _KICK_EMOTE.findall(content)
class ChatReader:
@@ -114,20 +136,84 @@ class ChatReader:
if time.monotonic() - last_data > 360: # a Twitch manda PING a cada ~5 min
raise ConnectionError("sem dados há 6 min")
# ---------- Kick (Pusher, não oficial) ----------
# ---------- Kick (tempo real do site, não oficial) ----------
def _run_kick(self) -> None:
from websockets.sync.client import connect # import tardio: só quem usa Kick precisa
response = httpx.get(
f"https://kick.com/api/v2/channels/{self.channel}",
headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json"},
timeout=20,
follow_redirects=True,
)
response = httpx.get(f"https://kick.com/api/v2/channels/{self.channel}", headers=KICK_HEADERS, timeout=20,
follow_redirects=True)
if response.status_code != 200:
raise ConnectionError(f"kick.com respondeu {response.status_code} ao buscar a sala do chat")
room = response.json()["chatroom"]["id"]
with connect(KICK_PUSHER, open_timeout=20) as ws:
channel = response.json()
room, channel_id = channel["chatroom"]["id"], channel["id"]
client_id = str(uuid.uuid4())
provider = self._kick_provider(channel_id, client_id)
if provider.get("provider") == "pusher":
self._run_kick_pusher(room, provider)
else:
self._run_kick_centrifugo(room, client_id, (provider.get("credentials") or {}).get("url") or KICK_CENTRIFUGO_DEFAULT)
def _kick_provider(self, channel_id: int, client_id: str) -> dict:
"""Provedor de tempo real que a Kick indica para o chat deste canal ({provider, credentials}). Falha na consulta
→ Centrifugo no endereço padrão (o que a Kick respondeu em todos os canais testados)."""
try:
r = httpx.post(f"{KICK_API}/channels/{channel_id}/chat/connection", headers=KICK_HEADERS, timeout=20,
json={"client": {"id": client_id, "type": "web"}, "capabilities": KICK_CAPABILITIES})
r.raise_for_status()
connections = (r.json().get("data") or {}).get("connections") or []
return connections[0] if connections else {"provider": "centrifugo"}
except (httpx.HTTPError, ValueError, KeyError, IndexError) as exc:
log.info("chat kick/%s: provedor não informado (%s); usando Centrifugo", self.channel, exc)
return {"provider": "centrifugo"}
def _run_kick_centrifugo(self, room: int, client_id: str, url: str) -> None:
"""Centrifugo (protocolo JSON): token de convidado → connect → subscribe `chatrooms.<sala>.v2`. O servidor manda
`{}` como ping (responde `{}`); o token expira (~45 min) e o servidor fecha: o laço reconecta com token novo."""
from websockets.sync.client import connect # import tardio: só quem usa Kick precisa
r = httpx.post(f"{KICK_API}/auth/connection", headers=KICK_HEADERS, json={"client_id": client_id}, timeout=20)
r.raise_for_status()
token = (r.json().get("data") or {}).get("token")
if not token:
raise ConnectionError("Kick não devolveu o token do chat")
with connect(url, open_timeout=20, additional_headers={"Origin": "https://kick.com", "User-Agent": "Mozilla/5.0"}) as ws:
ws.send(json.dumps({"connect": {"token": token, "name": "js"}, "id": 1}))
ws.send(json.dumps({"subscribe": {"channel": f"chatrooms.{room}.v2"}, "id": 2}))
batch, last_flush = [], time.monotonic()
while not self._stop.is_set():
try:
raw = ws.recv(timeout=1.0)
except TimeoutError:
raw = None
for part in (raw or "").split("\n"):
part = part.strip()
if not part:
continue
if part == "{}":
ws.send("{}") # ping do Centrifugo
continue
msg = json.loads(part)
if msg.get("error"):
raise ConnectionError(f"Kick (Centrifugo): {msg['error']}")
if msg.get("id") == 2 and "subscribe" in msg:
self.status = "connected"
pub = (msg.get("push") or {}).get("pub") or {}
data = pub.get("data") or {}
item = kick_message(data.get("event", ""), data.get("data")) if isinstance(data, dict) else None
if item:
batch.append((time.time(), *item))
if time.monotonic() - last_flush >= 1.0:
self._deliver(batch)
batch, last_flush = [], time.monotonic()
def _run_kick_pusher(self, room: int, provider: dict) -> None:
"""Pusher com a chave e o cluster que a Kick informar (a chave fixa antiga parou de valer em 11/2026)."""
from websockets.sync.client import connect
creds = provider.get("credentials") or {}
key, cluster = creds.get("appKey") or creds.get("key"), creds.get("cluster") or "us2"
if not key:
raise ConnectionError("Kick indicou Pusher sem a chave")
url = f"wss://ws-{cluster}.pusher.com/app/{key}?protocol=7&client=js&version=8.4.0&flash=false"
with connect(url, open_timeout=20) as ws:
ws.send(json.dumps({"event": "pusher:subscribe", "data": {"auth": "", "channel": f"chatrooms.{room}.v2"}}))
batch, last_flush = [], time.monotonic()
while not self._stop.is_set():
@@ -142,14 +228,10 @@ class ChatReader:
self.status = "connected"
elif name == "pusher:ping":
ws.send(json.dumps({"event": "pusher:pong", "data": {}}))
elif name.endswith("ChatMessageEvent"):
data = json.loads(event.get("data") or "{}")
user = (data.get("sender") or {}).get("username", "")
# Emotes da Kick chegam como [emote:123:NOME]: fica só o nome, que é o que carrega a reação.
content = data.get("content", "")
kick_emotes = re.findall(r"\[emote:\d+:([^\]]+)\]", content)
text = re.sub(r"\[emote:\d+:([^\]]+)\]", r"\1", content)
batch.append((time.time(), user, text[:300], kick_emotes))
else:
item = kick_message(name, event.get("data") or "{}")
if item:
batch.append((time.time(), *item))
if time.monotonic() - last_flush >= 1.0:
self._deliver(batch)
batch, last_flush = [], time.monotonic()
+2 -2
View File
@@ -119,8 +119,8 @@ class Settings:
judge_model=env.get("CLIPPER_JUDGE_MODEL", ""),
judge_min_score=num("CLIPPER_JUDGE_MIN_SCORE", 6, 0),
)
if settings.judge_provider not in ("codex", "claude", "off"):
raise ConfigError("CLIPPER_JUDGE_PROVIDER precisa ser codex, claude ou off")
if settings.judge_provider not in ("codex", "claude", "gemini", "off"):
raise ConfigError("CLIPPER_JUDGE_PROVIDER precisa ser codex, claude, gemini ou off")
if settings.encoder not in ("auto", "libx264", "h264_nvenc"):
raise ConfigError("CLIPPER_ENCODER precisa ser auto, libx264 ou h264_nvenc")
if overrides:
+116
View File
@@ -0,0 +1,116 @@
"""Decisão do JUIZ de contexto pelo código (doc/clipador/EQUIPE-IA.md).
O juiz (IA, só texto) responde perguntas sim/não sobre o corte; quem decide é esta função, com regras fixas e
calibráveis no painel (papel `judge` em `judge.roles`):
- checagem **crítica** que falhou (padrão: começo, desfecho, funciona sozinho) + ajuste de trecho dentro dos limites
→ **ajusta** (o trecho é recalculado com `fit_window`) e o juiz confere UMA vez de novo; falhou de novo → descarta;
- crítica que falhou sem ajuste possível → **descarta** com o motivo em português;
- "funciona sozinho" (e "quem/o quê") falho + frase de contexto → a frase resolve: vai na tela no começo do corte;
- checagem não crítica que falhou só **baixa a nota** (`penalty` por checagem); abaixo da nota mínima → descarta;
- corte manual ("cortar agora"): o juiz só **avisa**, nunca descarta nem mexe no trecho.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from .roles import CHECK_NAMES, CHECKS, DEFAULT_CRITICAL, DEFAULT_PENALTY
from .scoring import fit_window
MIN_SHIFT_S = 1.0 # ajuste menor que isso não muda nada: conta como "sem ajuste"
CONTEXT_LINE_MAX_WORDS = 10
CONTEXT_LINE_MAX_CHARS = 60
OUT_BEFORE_S = 20.0 # o juiz vê 20 s antes do corte, marcados out=1 (o espectador não vê)…
OUT_AFTER_S = 15.0 # …e 15 s depois (para notar o desfecho que ficou de fora)
# O que a frase de contexto resolve (ela dá ao espectador frio quem/o quê e o pano de fundo).
SOLVED_BY_LINE = ("standalone", "who_what")
@dataclass
class Decision:
action: str # approve | adjust | discard | warn
failed: list[str] = field(default_factory=list) # todas as checagens que falharam
failed_critical: list[str] = field(default_factory=list) # críticas que falharam e a frase não resolveu
solved_by_line: list[str] = field(default_factory=list)
window: tuple[float, float] | None = None # trecho novo (só em adjust)
context_line: str = ""
score_after: float | None = None
reason_pt: str = ""
def usable_line(text: str) -> str:
"""Frase de contexto que cabe na tela no começo do corte (curta); senão vazia."""
text = " ".join((text or "").split())
if not text or len(text) > CONTEXT_LINE_MAX_CHARS or len(text.split()) > CONTEXT_LINE_MAX_WORDS:
return ""
return text
def _names(checks: list[str]) -> str:
names = [CHECK_NAMES.get(c, c) for c in checks]
return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " e " + names[-1]
def decide(result: dict, *, start_s: float, end_s: float, lo: float, hi: float, min_s: float, max_s: float,
conf: dict | None = None, score: float | None = None, min_score: float | None = None,
manual: bool = False, allow_fix: bool | None = None) -> Decision:
"""Ação pelo resultado do juiz (`judge.clean_context`). `conf` = papel `judge` da Equipe de IA.
`allow_fix=False` força a 2ª rodada (sem novo ajuste)."""
conf = conf or {}
critical = [c for c in conf.get("critical", DEFAULT_CRITICAL) if c in CHECKS]
penalty = float(conf.get("penalty", DEFAULT_PENALTY))
can_fix = conf.get("allowFix", True) if allow_fix is None else (allow_fix and conf.get("allowFix", True))
checks = result.get("checks") or {}
failed = [c for c in CHECKS if not (checks.get(c) or {}).get("ok", True)]
fix = result.get("fix") or {}
line = usable_line(fix.get("context_line", "")) if conf.get("allowContextLine", True) else ""
solved = [c for c in failed if c in SOLVED_BY_LINE] if line else []
failed_critical = [c for c in failed if c in critical and c not in solved]
others = [c for c in failed if c not in critical and c not in solved]
score_after = None if score is None else round(max(0.0, score - penalty * len(others)), 2)
why_pt = (result.get("pt") or {}).get("reason") or result.get("reason") or ""
d = Decision("approve", failed, failed_critical, solved, None, line, score_after)
if manual:
d.action = "warn" if failed else "approve"
d.reason_pt = (f"Aviso do juiz: falhou em {_names(failed)}. {why_pt}".strip() if failed else "")
return d
if failed_critical:
new = None
if can_fix and (fix.get("start_s") is not None or fix.get("end_s") is not None):
ns = fix["start_s"] if fix.get("start_s") is not None else start_s
ne = fix["end_s"] if fix.get("end_s") is not None else end_s
# Recuar o início (faltou o começo) mantém o início; estender o fim (faltou o desfecho) mantém o fim.
keep = "start" if "setup" in failed_critical or ns < start_s - MIN_SHIFT_S else "end"
ns, ne = fit_window(ns, ne, lo, hi, min_s, max_s, keep=keep)
if ne - ns >= min(min_s, 10.0) and (abs(ns - start_s) >= MIN_SHIFT_S or abs(ne - end_s) >= MIN_SHIFT_S):
new = (ns, ne)
if new:
d.action, d.window = "adjust", new
d.reason_pt = (f"Juiz ajustou o trecho para {new[0]:.0f}–{new[1]:.0f}s: faltava {_names(failed_critical)}. "
f"{why_pt}").strip()
else:
d.action = "discard"
d.reason_pt = f"Descartado pelo juiz: sem {_names(failed_critical)}. {why_pt}".strip()
return d
if score_after is not None and min_score is not None and others and score_after < min_score:
d.action = "discard"
d.reason_pt = (f"Descartado pelo juiz: a nota caiu para {score_after:.1f} (falhou em {_names(others)}). "
f"{why_pt}").strip()
return d
d.reason_pt = (f"Juiz aprovou{' com frase de contexto' if line and solved else ''}"
+ (f" (falhou em {_names(others)}, nota {score_after:.1f})" if others and score_after is not None else "")
+ (f". {why_pt}" if why_pt else "."))
return d
def view(result: dict, decision: Decision, model: str) -> dict:
"""O que vai em `judge_json.context` (o painel mostra em português)."""
return {"model": model, "viewerSummary": result.get("viewer_summary", ""), "checks": result.get("checks", {}),
"fix": result.get("fix", {}), "confidence": result.get("confidence"), "reason": result.get("reason", ""),
"pt": result.get("pt") or {}, "decision": decision.action, "failed": decision.failed,
"failedCritical": decision.failed_critical, "solvedByLine": decision.solved_by_line,
"contextLine": decision.context_line if decision.action in ("approve", "adjust", "warn") else "",
"scoreAfter": decision.score_after, "reasonPt": decision.reason_pt,
**({"window": [round(decision.window[0], 2), round(decision.window[1], 2)]} if decision.window else {})}
+101
View File
@@ -190,6 +190,106 @@ SCHEMA = [
);
CREATE INDEX deleted_clips_session ON deleted_clips (session_id);
""",
# v11: (a) parar uma sessão à mão pausa o monitor da fonte (`monitor_paused_at` + a sessão que motivou): o monitor
# não abre sessão nova enquanto a pausa existir; religar (PATCH monitor=true, gravar pelo link ou retomar) limpa.
# (b) idioma falado na live, por fonte e por sessão ('' = CLIPPER_LANGUAGE): transcrição e textos da IA.
"""
ALTER TABLE channels ADD COLUMN monitor_paused_at TEXT;
ALTER TABLE channels ADD COLUMN monitor_paused_session INTEGER;
ALTER TABLE channels ADD COLUMN language TEXT NOT NULL DEFAULT '';
ALTER TABLE sessions ADD COLUMN language TEXT NOT NULL DEFAULT '';
""",
# v12: perfil do jogo em dois idiomas (doc/clipador/JOGOS.md). `profile_json` continua sendo o português (o que o
# painel mostra); `profile_ai_json` é o inglês, que vai nos prompts; `translated_at` = quando uma versão foi gerada
# da outra; `aliases_json` = outros nomes do jogo (categoria "Grand Theft Auto VI" e tela "GTA 6" → mesmo perfil).
"""
ALTER TABLE games ADD COLUMN profile_ai_json TEXT;
ALTER TABLE games ADD COLUMN translated_at TEXT;
ALTER TABLE games ADD COLUMN aliases_json TEXT NOT NULL DEFAULT '[]';
""",
# v13: fonte em inglês (doc/clipador/IDIOMAS.md): a fala do corte em frases com tempo + tradução em português,
# para o painel e para a legenda de desenvolvimento (inglês em cima, português embaixo). NULL = não traduzido.
"""
ALTER TABLE clips ADD COLUMN translation_json TEXT;
""",
# v14: vídeo de revisão × vídeo final (doc/clipador/REVISAO.md). O render da fila é o de REVISÃO (com as camadas
# `dev` ligadas); ao aprovar, sai o FINAL (`dev=False`) em `clip-<id>-final.mp4`, que é o único que se publica.
# `review_dev_json` = camadas de desenvolvimento que entraram no arquivo de revisão (["translation", ...]; [] =
# nenhuma → o de revisão já é o final; NULL = desconhecido → renderiza o final). `final_status`: pending |
# rendering | ready | error (NULL = sem final: não aprovado, ou a aprovação foi desfeita/editada).
# Cortes de antes da v14: a única camada de desenvolvimento era a tradução, que só entra com `translation_json`;
# sem ela o arquivo já é limpo ([]).
"""
ALTER TABLE clips ADD COLUMN review_dev_json TEXT;
ALTER TABLE clips ADD COLUMN final_status TEXT CHECK (final_status IN ('pending', 'rendering', 'ready', 'error'));
ALTER TABLE clips ADD COLUMN final_file TEXT;
ALTER TABLE clips ADD COLUMN final_thumb TEXT;
ALTER TABLE clips ADD COLUMN final_cover TEXT;
ALTER TABLE clips ADD COLUMN final_error TEXT;
ALTER TABLE clips ADD COLUMN final_at TEXT;
UPDATE clips SET review_dev_json = '[]' WHERE file IS NOT NULL AND translation_json IS NULL;
UPDATE clips SET final_status = 'pending' WHERE status = 'approved' AND review_dev_json IS NULL AND file IS NOT NULL;
UPDATE clips SET final_status = 'ready', final_file = file, final_thumb = thumb, final_at = updated_at
WHERE status IN ('approved', 'published') AND review_dev_json = '[]';
""",
# v15: falantes (doc/clipador/FALANTES.md). Impressões de voz dos trechos de fala de cada bloco (WeSpeaker), com o
# volume; as vozes da sessão são agrupadas sob demanda a partir daqui (speakers.SpeakerService).
"""
CREATE TABLE IF NOT EXISTS voice_chunks (
session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
idx INTEGER NOT NULL,
data_json TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (session_id, idx)
);
""",
# v16: detecção do jogo (doc/clipador/DETECCAO-JOGO.md). `game_status`: user | agreed | probable | conflict | unknown
# ('' = sessão antiga, ainda não checada). `game_detect_json`: as pistas guardadas (categoria, tela), os candidatos
# com a nota, a sugestão de troca e a contagem de checagens seguidas.
"""
ALTER TABLE sessions ADD COLUMN game_status TEXT NOT NULL DEFAULT '';
ALTER TABLE sessions ADD COLUMN game_detect_json TEXT;
""",
# v17: Equipe de IA (doc/clipador/EQUIPE-IA.md).
# - `ai_calls`: cada chamada de IA (papel, IA, tamanho do prompt e das imagens, tokens quando a CLI informa, tempo)
# para comparar custo por hora (F0). Sem FK para a sessão: a medição fica depois de apagar a sessão.
# - `scene_notes`: frase curta do que está na tela num instante (escrita pela varredura/analista ao ver os quadros);
# vira o campo `v` da linha do tempo JSON.
# - `clips.owner_label`/`owner_note`: avaliação do dono (bom / ruim / sem contexto) para o conjunto de avaliação.
"""
CREATE TABLE IF NOT EXISTS ai_calls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
at TEXT NOT NULL,
role TEXT NOT NULL,
purpose TEXT NOT NULL,
provider TEXT NOT NULL,
model TEXT NOT NULL,
ok INTEGER NOT NULL,
error TEXT,
ms INTEGER,
system_chars INTEGER,
prompt_chars INTEGER,
images INTEGER,
image_bytes INTEGER,
tokens_in INTEGER,
tokens_out INTEGER,
tokens_cached INTEGER,
session_id INTEGER,
clip_id INTEGER,
mode TEXT
);
CREATE INDEX IF NOT EXISTS ai_calls_at ON ai_calls (at);
CREATE TABLE IF NOT EXISTS scene_notes (
session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
t REAL NOT NULL,
source TEXT NOT NULL,
text TEXT NOT NULL,
created_at TEXT NOT NULL,
PRIMARY KEY (session_id, t, source)
);
ALTER TABLE clips ADD COLUMN owner_label TEXT CHECK (owner_label IN ('good', 'bad', 'no_context'));
ALTER TABLE clips ADD COLUMN owner_note TEXT;
""",
]
@@ -215,6 +315,7 @@ class Database:
# Chat só fica "conectado" enquanto grava (sessões antigas ficaram com o estado velho gravado).
self.run("UPDATE sessions SET chat_status = 'off' WHERE status NOT IN ('starting', 'recording') AND chat_status != 'off'")
self.run("UPDATE clips SET status = 'pending' WHERE status = 'rendering'")
self.run("UPDATE clips SET final_status = 'pending' WHERE final_status = 'rendering'") # vídeo final idem
def _migrate(self) -> None:
version = self.conn.execute("PRAGMA user_version").fetchone()[0]
+391
View File
@@ -0,0 +1,391 @@
"""Dublagem em português por TTS — camada SÓ de desenvolvimento (doc/clipador/DUBLAGEM.md).
Pedido do dono (18/11/2026): fonte em inglês → "quando ele estiver falando, a gente dubla em português; baixa o áudio
dele, deixa um pouco baixo para escutar o som do carro, do ambiente do jogo". Só entra no vídeo de REVISÃO
(`dev.dub`); o vídeo final, depois de aprovar, sai com o áudio original (`layout.dev_flags(cfg, dev=False)`).
Fluxo: frases traduzidas (`clips.translation_json` → `[{s, e, text, pt, speaker?}]`, tempo da sessão) → tempo de
saída (`editor.to_output`, respeita os trechos removidos) → uma fala TTS por frase pelo serviço de voz local
(`POST /v1/synthesize`, WAV), com cache em disco por (voz, velocidade, texto) → encaixe no tempo (`fit`) → UMA faixa
WAV do trecho renderizado (`Dubber.build`) que o `editor_render` mistura com a voz original abaixada (`duck_factors`).
Voz: TTS PRONTA do catálogo (padrão `pt-br-antonio`, masculina, Edge). Nunca clonar a voz do streamer — é um
terceiro sem consentimento; o projeto só aceita clonagem com consentimento de quem fala.
"""
from __future__ import annotations
import hashlib
import io
import logging
import os
import threading
import time
import uuid
import wave
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
import httpx
from . import layout, media
from .editor import to_output
log = logging.getLogger("cenaforge_clipper.dub")
FALLBACK_VOICE = "pt-br-faber" # Piper, offline: quando a voz escolhida (Edge, online) falha
SPEAKER_OTHER = "other" # `lines[].speaker` (FALANTES.md): "streamer" | "other1", "other2"…; ausente = streamer
# Esclarecimento do dono (18/11/2026): NÃO é dublagem de filme — é para a equipe entender o contexto. Nada de
# sincronia labial: cada fala começa perto do início da original, em velocidade natural (inteligível primeiro), e pode
# escorrer depois da fala original. Duas nunca tocam juntas e o atraso não acumula (limite por frase, `MAX_LATE_S`).
TTS_SPEED = 1.05 # quase natural: o português traduzido costuma ser mais longo que o inglês falado
MAX_TEMPO = 1.2 # aceleração máxima (atempo), só quando nem escorrendo cabe; acima disso fica difícil de entender
MAX_LATE_S = 1.5 # quanto uma fala pode começar depois da original (porque a anterior escorreu); nunca acumula
# Frase PARTIDA no meio pela transcrição (a 1ª não termina em . ! ? …), do mesmo falante e colada (vão menor que
# MERGE_GAP_S), vira uma fala só. Juntar frases completas foi medido pior (corte 259: 8,5 s perdidos contra 3,0 s).
MERGE_GAP_S = 0.4
MERGE_MAX_S = 7.0 # …desde que a junção não passe disso (tempo da fala original)
MERGE_MAX_CHARS = 140
SENTENCE_END = (".", "!", "?", "…", ".\"", "?\"", "!\"")
GAP_S = 0.08 # silêncio mínimo entre duas dublagens (nunca duas tocando juntas)
MIN_SLOT_S = 0.45 # espaço menor que isso: a frase não é dublada (não daria para entender)
FADE_S = 0.12 # fade de saída quando a fala precisa ser cortada
RAMP_S = 0.15 # rampa do ducking (desce antes da dublagem começar, sobe depois que ela acaba)
DUCK_HOLD_S = 0.6 # vão entre duas dublagens menor que isso: a voz original continua baixa (sem "bombear")
SAMPLE_RATE = 48000
# Nível da dublagem: cada fala é guardada a −16 LUFS (média ≈ −16,5 dB RMS sem as pausas). No render, ela é posta
# `LEVEL_OVER_ORIGINAL_DB` acima do volume médio do próprio corte (medido no áudio original) — live baixa (medido no
# corte 259 do tfue: −32 dB) não ganha uma voz 14 dB mais alta que ele. Ganho entre `GAIN_RANGE_DB`; limitador no fim.
TTS_LEVEL_DB = -16.5
LEVEL_OVER_ORIGINAL_DB = 6.0
GAIN_RANGE_DB = (-20.0, 3.0)
WORKERS = 3 # sínteses em paralelo (Edge é online; o serviço tem fila por chave)
SYNTH_TIMEOUT_S = 120
CACHE_KEEP_DAYS = 30 # fala do cache sem uso há mais que isso é apagada quando o serviço sobe
class DubError(RuntimeError):
"""Falha ao sintetizar uma frase (serviço fora, voz inexistente…)."""
# ---------------------------------------------------------------- configuração
def options(cfg: dict) -> dict:
"""Vozes e volume da dublagem a partir da configuração efetiva do corte (grupo `dev`)."""
group = {**layout.DEFAULTS["dev"], **(cfg.get("dev") or {})}
return {"voice": group["dubVoice"], "voiceOther": group["dubVoiceOther"] or group["dubVoice"],
"duck": float(group["dubDuck"])}
def voice_for(line: dict, opts: dict) -> str:
"""Voz da frase: qualquer voz que não é o streamer (`other`, `other1`, `other2`…) usa a segunda voz; sem o
campo, a padrão."""
speaker = line.get("speaker")
return opts["voiceOther"] if isinstance(speaker, str) and speaker.startswith(SPEAKER_OTHER) else opts["voice"]
# ---------------------------------------------------------------- plano (contas puras, sem áudio)
@dataclass(frozen=True)
class DubLine:
at: float # início da frase no tempo de SAÍDA (do corte inteiro)
text: str # português
voice: str
speaker: str | None = None
end: float = 0.0 # fim da fala original (tempo de saída); 0 = desconhecido
@dataclass(frozen=True)
class Cue:
"""Uma dublagem posicionada: começa em `at` (tempo de saída), toca `length` s, acelerada por `tempo`."""
at: float
length: float
tempo: float
cut: bool # não coube nem acelerada: termina com fade
index: int # posição em `lines`
def plan_lines(lines: list[dict], cuts: list[dict], opts: dict) -> list[DubLine]:
"""Frases da tradução (tempo da sessão) → frases no tempo de saída, em ordem. Frase sem português, ou que caiu
inteira num trecho removido (nada dela na saída), fica de fora; fala curta ("Okay." de 0,18 s) é dublada.
Frase partida no meio + continuação (mesmo falante, colada) viram uma fala só (ex.: "…deve dar" + "tudo certo.")."""
out: list[DubLine] = []
for line in lines or []:
text = " ".join(str(line.get("pt") or "").split())
if not text:
continue
try:
s, e = float(line["s"]), float(line["e"])
except (KeyError, TypeError, ValueError):
continue
a, _ = to_output(s, cuts)
b, _ = to_output(e, cuts)
if b - a < 0.05:
continue
speaker = line.get("speaker") if isinstance(line.get("speaker"), str) else None
out.append(DubLine(round(a, 3), text, voice_for(line, opts), speaker, round(b, 3)))
out.sort(key=lambda x: x.at)
merged: list[DubLine] = []
for line in out:
prev = merged[-1] if merged else None
if (prev and prev.voice == line.voice and not prev.text.endswith(SENTENCE_END)
and line.at - prev.end < MERGE_GAP_S and line.end - prev.at <= MERGE_MAX_S
and len(prev.text) + len(line.text) < MERGE_MAX_CHARS):
merged[-1] = DubLine(prev.at, f"{prev.text} {line.text}", prev.voice, prev.speaker, max(prev.end, line.end))
else:
merged.append(line)
return merged
def fit(lines: list[DubLine], durations: list[float | None], total: float) -> list[Cue]:
"""Encaixa cada fala no tempo. `durations[i]` = duração natural do TTS da frase i: 0 = a síntese falhou (a frase
some e não limita a anterior); None = não sintetizada neste render (fora do trecho: não toca, mas ainda é o
limite da anterior).
- Começa no início da frase original (ou logo depois da dublagem anterior, se ela escorreu).
- Toca em velocidade natural e pode escorrer até `MAX_LATE_S` depois do começo da próxima frase (que começa
depois dela). O limite é contado de cada frase original: o atraso nunca acumula.
- Só se nem assim couber: acelera até `MAX_TEMPO`; se ainda não couber, corta com fade.
- Nunca duas tocando juntas (`GAP_S` entre elas) e nunca depois do fim do corte."""
cues: list[Cue] = []
cursor = float("-inf")
for i, (line, natural) in enumerate(zip(lines, durations)):
if not natural or natural <= 0:
continue
start = max(line.at, cursor + GAP_S)
nxt = next((lines[j].at for j in range(i + 1, len(lines)) if durations[j] is None or durations[j] > 0), None)
limit = min(total, nxt + MAX_LATE_S - GAP_S) if nxt is not None else total
room = limit - start
if room < MIN_SLOT_S or start >= total:
log.info("dublagem: frase %d sem espaço (%.2f s) — fica sem dublar", i, room)
continue
tempo = 1.0 if natural <= room else min(MAX_TEMPO, natural / room)
length = natural / tempo
cut = length > room + 1e-6
if cut:
length = room
cues.append(Cue(round(start, 3), round(length, 3), round(tempo, 3), cut, i))
cursor = start + length
return cues
def duck_spans(cues: list[Cue], merge_gap: float = DUCK_HOLD_S) -> list[tuple[float, float]]:
"""Intervalos em que a voz original fica baixa (as dublagens, com vãos curtos emendados)."""
spans: list[list[float]] = []
for c in sorted(cues, key=lambda c: c.at):
a, b = c.at, c.at + c.length
if spans and a - spans[-1][1] < merge_gap + 2 * RAMP_S:
spans[-1][1] = max(spans[-1][1], b)
else:
spans.append([a, b])
return [(round(a, 3), round(b, 3)) for a, b in spans]
def duck_factors(spans: list[tuple[float, float]], duck: float, ramp: float = RAMP_S) -> list[str]:
"""Fatores (expressões do FFmpeg em `t`) que multiplicam o volume da voz original: 1 fora das falas dubladas,
`duck` durante, com rampa de `ramp` s antes e depois. Vão no `volume='…':eval=frame` do `editor_render`."""
if duck >= 1 or not spans:
return []
depth, r = 1 - max(0.0, duck), max(0.01, ramp)
return [f"(1-{depth:.3f}*clip(min((t-{a - r:.3f})/{r:.3f},({b + r:.3f}-t)/{r:.3f}),0,1))" for a, b in spans]
# ---------------------------------------------------------------- síntese com cache
def wav_duration(data: bytes) -> float:
with wave.open(io.BytesIO(data)) as w:
return w.getnframes() / float(w.getframerate() or 1)
def voice_synth(url: str | None, key: str | None) -> Callable[[str, str], bytes]:
"""Função (texto, voz) → WAV pelo serviço de voz local (`POST /v1/synthesize`, mesma chave do `VoiceClient`)."""
def synth(text: str, voice: str) -> bytes:
if not (url and key):
raise DubError("serviço de voz não instalado")
try:
response = httpx.post(f"{url}/v1/synthesize", timeout=SYNTH_TIMEOUT_S, headers={"X-Service-Key": key},
json={"requestId": f"clipper-dub-{uuid.uuid4().hex[:24]}", "text": text, "voiceId": voice,
"params": {"speed": TTS_SPEED, "format": "wav"}})
except httpx.HTTPError as exc:
raise DubError(f"serviço de voz fora do ar ({url})") from exc
if response.status_code != 200:
raise DubError(f"voz {voice} respondeu {response.status_code}: {response.text[:160]}")
return response.content
return synth
class TtsCache:
"""Fala TTS por (voz, velocidade, texto) em disco — prévia e render seguintes não sintetizam de novo.
Com FFmpeg, cada fala é guardada já limpa: sem o silêncio do começo/fim (o Edge põe ~0,5 s), volume igualado
(loudnorm −16 LUFS, vozes de motores diferentes ficam parecidas) e 48 kHz mono."""
def __init__(self, folder: Path, synth: Callable[[str, str], bytes], ffmpeg: str | None):
self.folder, self.synth, self.ffmpeg = folder, synth, ffmpeg
self.synth_calls = 0
self._guard = threading.Lock()
self._locks: dict[str, threading.Lock] = {}
def path(self, voice: str, text: str) -> Path:
digest = hashlib.sha256(f"{voice}|{TTS_SPEED:.2f}|{text}".encode("utf-8")).hexdigest()[:24]
return self.folder / f"{digest}.wav"
def get(self, voice: str, text: str) -> tuple[Path, float]:
"""(arquivo, duração em s) da fala; sintetiza só se ainda não estiver no cache."""
out = self.path(voice, text)
with self._guard:
lock = self._locks.setdefault(out.name, threading.Lock())
with lock:
if not out.is_file():
raw = self.synth(text, voice)
with self._guard:
self.synth_calls += 1
self.folder.mkdir(parents=True, exist_ok=True)
tmp = out.with_suffix(".tmp.wav")
if self.ffmpeg:
raw_file = out.with_suffix(".raw.wav")
raw_file.write_bytes(raw)
try:
trim = "silenceremove=start_periods=1:start_threshold=-50dB"
media.run([self.ffmpeg, "-y", "-v", "error", "-i", str(raw_file), "-af",
f"{trim},areverse,{trim},areverse,loudnorm=I=-16:TP=-1.5:LRA=11,aresample={SAMPLE_RATE}",
"-ac", "1", "-c:a", "pcm_s16le", str(tmp)], timeout=60)
finally:
raw_file.unlink(missing_ok=True)
else:
tmp.write_bytes(raw)
tmp.replace(out)
else:
try:
os.utime(out) # "usada agora": a limpeza (`prune`) apaga só o que ninguém usa há tempo
except OSError:
pass
return out, wav_duration(out.read_bytes())
def prune(self, keep_days: float = CACHE_KEEP_DAYS) -> int:
"""Apaga as falas sem uso há mais de `keep_days` dias. Devolve quantas apagou."""
limit = time.time() - keep_days * 86400
removed = 0
for file in self.folder.glob("*.wav") if self.folder.is_dir() else []:
try:
if file.stat().st_mtime < limit:
file.unlink()
removed += 1
except OSError:
continue
return removed
# ---------------------------------------------------------------- faixa do trecho renderizado
def gain_for(level_db: float | None) -> float:
"""Ganho (dB) da faixa de dublagem para o volume médio `level_db` do áudio original (None = sem medida: 0 dB)."""
if level_db is None:
return 0.0
lo, hi = GAIN_RANGE_DB
return round(min(hi, max(lo, level_db + LEVEL_OVER_ORIGINAL_DB - TTS_LEVEL_DB)), 1)
@dataclass
class DubTrack:
file: Path # WAV 48 kHz estéreo, do tamanho do trecho (t1 − t0), começando em t0
spans: list[tuple[float, float]] # ducking, em tempo relativo a t0
duck: float
cues: int
seconds: float # quanto a dublagem custou neste render (síntese + faixa)
synthesized: int # falas sintetizadas agora (o resto veio do cache)
failed: list[str] = field(default_factory=list)
class Dubber:
def __init__(self, cache: TtsCache, ffmpeg: str | None):
self.cache, self.ffmpeg = cache, ffmpeg
def _speech(self, line: DubLine) -> tuple[Path, float] | None:
try:
return self.cache.get(line.voice, line.text)
except (DubError, media.MediaError, OSError, wave.Error, EOFError) as exc:
if line.voice != FALLBACK_VOICE and not str(exc).startswith("serviço de voz"):
log.warning("dublagem: voz %s falhou (%s); tentando %s", line.voice, exc, FALLBACK_VOICE)
try:
return self.cache.get(FALLBACK_VOICE, line.text)
except (DubError, media.MediaError, OSError, wave.Error, EOFError) as exc2:
exc = exc2
log.warning("dublagem: frase sem áudio (%s)", exc)
return None
def build(self, translation: list[dict], cuts: list[dict], cfg: dict, t0: float, t1: float, work: Path,
stem: str, level_db: float | None = None) -> DubTrack | None:
"""Faixa da dublagem da saída [t0, t1]. Só sintetiza as frases que tocam nesse trecho (prévia de 5 s não
sintetiza o corte inteiro). `level_db` = volume médio do áudio original do corte (nivela a dublagem; ver
`gain_for`). None = nada para dublar (ou serviço de voz fora)."""
if not self.ffmpeg:
return None
started = time.monotonic()
before = self.cache.synth_calls
opts = options(cfg)
lines = plan_lines(translation, cuts, opts)
if not lines:
return None
total = round(sum(c["end"] - c["start"] for c in cuts), 3)
# Frases que podem tocar em [t0, t1]: começam antes de t1 e a próxima (+ atraso máximo) passa de t0.
wanted = [i for i, ln in enumerate(lines)
if ln.at < t1 and (lines[i + 1].at + MAX_LATE_S if i + 1 < len(lines) else total) > t0]
if wanted and wanted[0] > 0: # a anterior decide se a 1ª atrasa: entra na conta (não na faixa)
wanted.insert(0, wanted[0] - 1)
speech: dict[int, tuple[Path, float] | None] = {}
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
for i, result in zip(wanted, pool.map(lambda i: self._speech(lines[i]), wanted)):
speech[i] = result
failed = [lines[i].text for i in wanted if speech.get(i) is None]
if wanted and len(failed) == len(wanted):
log.warning("dublagem: nenhuma fala sintetizada (%d frases) — vídeo sai sem dublagem", len(wanted))
return None
durations = [(speech[i][1] if speech[i] else 0.0) if i in speech else None for i in range(len(lines))]
# Fora de `wanted` a duração não é conhecida (None): a frase vizinha usa o começo dela (`at`) como limite, que
# é o que importa; essas frases não entram na faixa.
cues = [c for c in fit(lines, durations, total) if c.at < t1 and c.at + c.length > t0]
if not cues:
return None
out = work / f"{stem}.dub.wav"
self._mix(cues, [speech[c.index][0] for c in cues], t0, t1, out, gain_for(level_db)) # type: ignore[index]
spans = [(round(a - t0, 3), round(b - t0, 3)) for a, b in duck_spans(cues)]
return DubTrack(out, spans, opts["duck"], len(cues), round(time.monotonic() - started, 2),
self.cache.synth_calls - before, failed)
def _mix(self, cues: list[Cue], files: list[Path], t0: float, t1: float, out: Path, gain_db: float = 0.0) -> None:
"""Uma faixa só (48 kHz estéreo, `t1 − t0` s): cada fala acelerada/cortada e posta no lugar, com `gain_db`."""
length = t1 - t0
args: list[str] = [self.ffmpeg or "ffmpeg", "-y", "-v", "error"]
graph = [f"aevalsrc=0:s={SAMPLE_RATE}:d={length:.3f}[base]"]
for k, (cue, file) in enumerate(zip(cues, files)):
args += ["-i", str(file)]
chain = f"[{k}:a]aformat=sample_rates={SAMPLE_RATE}:channel_layouts=mono"
if cue.tempo > 1.001:
chain += f",atempo={cue.tempo:.3f}"
chain += f",atrim=end={cue.length:.3f}"
if cue.cut:
chain += f",afade=t=out:st={max(0.0, cue.length - FADE_S):.3f}:d={FADE_S:.3f}"
skip = t0 - cue.at
if skip > 0: # prévia que começa no meio desta fala
chain += f",atrim=start={skip:.3f}"
chain += f",asetpts=PTS-STARTPTS,adelay=delays={int(round(max(0.0, -skip) * 1000))}:all=1[d{k}]"
graph.append(chain)
graph.append("[base]" + "".join(f"[d{k}]" for k in range(len(cues)))
+ f"amix=inputs={len(cues) + 1}:duration=first:normalize=0,volume={gain_db:.1f}dB,"
f"alimiter=limit=0.9:level=0,aformat=channel_layouts=stereo[out]")
out.parent.mkdir(parents=True, exist_ok=True)
media.run([*args, "-filter_complex", ";".join(graph), "-map", "[out]", "-c:a", "pcm_s16le", "-t", f"{length:.3f}",
str(out)], timeout=120)
def for_engine(engine) -> Dubber:
"""Dublador do motor (um por processo, criado na 1ª vez): cache em `data/clipper/dub/`, voz pelo serviço local."""
dubber = getattr(engine, "_dubber", None)
if dubber is None:
settings = engine.settings
voice = getattr(engine, "voice", None)
synth = voice_synth(getattr(voice, "url", None) or settings.voice_url, getattr(voice, "key", None) or settings.voice_key)
cache = TtsCache(settings.data_dir / "dub", synth, settings.ffmpeg)
if cache.prune():
log.info("dublagem: cache limpo (falas sem uso há %d dias)", CACHE_KEEP_DAYS)
dubber = Dubber(cache, settings.ffmpeg)
engine._dubber = dubber
return dubber

Some files were not shown because too many files have changed in this diff Show More