diff --git a/.github/workflows/testes.yml b/.github/workflows/testes.yml index 02a9754..c95e0c5 100644 --- a/.github/workflows/testes.yml +++ b/.github/workflows/testes.yml @@ -4,15 +4,32 @@ on: push: branches: [main, dobramundo] pull_request: + workflow_dispatch: + inputs: + linux_diagnostics: + description: "Repetir apenas o build Linux para diagnosticar empacotamento (não substitui a CI completa)" + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: testes-${{ github.ref }} + cancel-in-progress: true jobs: testes: + if: github.event_name != 'workflow_dispatch' || !inputs.linux_diagnostics runs-on: ubuntu-latest strategy: fail-fast: false matrix: - # 3.8: mínimo declarado (código compatível com consoles mais antigos); 3.12: versão do build - python-version: ["3.8", "3.12"] + include: + - python-version: "3.8" + requirements: requirements-ci-py38.txt + - python-version: "3.12" + requirements: requirements-ci-py312.txt env: SDL_VIDEODRIVER: dummy SDL_AUDIODRIVER: dummy @@ -21,11 +38,86 @@ jobs: - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} + cache: pip + cache-dependency-path: ${{ matrix.requirements }} - name: Dependências (o jogo e os testes não precisam da webcam) - run: python -m pip install -r requirements.txt pytest ruff + run: python -m pip install -r ${{ matrix.requirements }} - name: Lint run: ruff check . + - name: Formatação + run: ruff format --check . - name: Testes - run: python -m pytest -q + run: python -m pytest -q -ra --cov=dobramundo --cov-branch --cov-report=term-missing:skip-covered --cov-report=xml - name: Self-test run: python -m dobramundo --self-test 60 + - name: Cobertura por comportamento (sem meta artificial de percentual) + uses: actions/upload-artifact@v4 + with: + name: cobertura-python-${{ matrix.python-version }} + path: coverage.xml + + executaveis: + needs: testes + if: always() && !cancelled() && (needs.testes.result == 'success' || (github.event_name == 'workflow_dispatch' && inputs.linux_diagnostics)) + strategy: + fail-fast: false + matrix: + os: ${{ fromJSON(github.event_name == 'workflow_dispatch' && inputs.linux_diagnostics && '["ubuntu-latest"]' || '["ubuntu-latest", "windows-latest"]') }} + runs-on: ${{ matrix.os }} + timeout-minutes: 25 + env: + SDL_VIDEODRIVER: dummy + SDL_AUDIODRIVER: dummy + MPLBACKEND: Agg + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: | + requirements-webcam.txt + requirements.txt + constraints-build.txt + - name: Runtimes gráficos do MediaPipe no Linux + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install --yes libegl1 libgles2 + - name: Dependências fixadas do build + run: python -m pip install -r requirements-webcam.txt pyinstaller -c constraints-build.txt + - name: Dependências nativas do MediaPipe + if: runner.os == 'Linux' + run: | + set -euo pipefail + library="$(python -c 'import mediapipe, pathlib; print(pathlib.Path(mediapipe.__file__).parent / "tasks/c/libmediapipe.so")')" + test -f "$library" + dependencies="$(ldd "$library")" + printf '%s\n' "$dependencies" + if grep -q 'not found' <<< "$dependencies"; then + echo 'Dependência nativa ausente para libmediapipe.so' >&2 + exit 1 + fi + - name: Gerar e testar executável com detector + run: python tools/build_desktop.py + - name: Empacotar Linux preservando permissão de execução + if: runner.os == 'Linux' + run: tar -czf dist/Dobramundo-Linux.tar.gz -C dist Dobramundo + - name: Executável Windows e relatório técnico + if: always() && runner.os == 'Windows' + uses: actions/upload-artifact@v4 + with: + name: Dobramundo-${{ runner.os }}-${{ github.sha }} + path: | + dist/Dobramundo/ + build/desktop-selftest/self_test.json + retention-days: 14 + - name: Pacote Linux e relatório técnico + if: always() && runner.os == 'Linux' + uses: actions/upload-artifact@v4 + with: + name: Dobramundo-${{ runner.os }}-${{ github.sha }} + path: | + dist/Dobramundo-Linux.tar.gz + build/desktop-selftest/self_test.json + retention-days: 14 diff --git a/.gitignore b/.gitignore index 1c89051..34517f5 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,9 @@ __pycache__/ .pytest_cache/ .pytest-* .ruff_cache/ +.coverage* +coverage.xml +htmlcov/ # Dados locais do jogo (perfil, relatórios) save/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 227e21f..713fe92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Histórico do Dobramundo +## 1.6.0 — 2026-10-25 + +- Perfis locais independentes com cartões anônimos, preservação do save legado e recuperação a partir de cópias anteriores; falhas de leitura bloqueiam gravação destrutiva. +- Preparação de sessão: exploração sem eliminação, limite opcional de 120/180/240 s, assistência previsível e sementes comunitárias repetíveis. Resultados parciais preservam ganhos sem registrar conclusão não alcançada. +- Missões oferecidas conforme alvos disponíveis, com expiração após 60 s sem penalidade e nova oferta após um intervalo; repetição mantém parâmetros e preferência de material. Ponto de troca custa 8 papel/8 plástico e Horta custa 24 papel/16 vidro, antecipando a transformação inicial. +- Oito variações regionais com sementes publicadas; relatório de economia usa movimento, colisões, reação, erros e pausas. +- Treze imagens preparadas para o tamanho de uso, manifesto de procedência, caches limitados por bytes e descarte por bioma. Render de pista, objetos, avião e piloto dividido por responsabilidade; fallback preservado. +- Fábrica de cenas injetável, contratos de leitura do desenho, fontes e ajuste de texto comuns; testes organizados por comportamento. Formatação global em commit separado, sem alteração das árvores sintáticas. +- CI com versões fixadas por Python, cobertura, formatação e builds Windows/Linux com self-test. Exceções do cartucho passam a ser registradas sem conteúdo dos perfis. + ## 1.5.0 — 2026-10-25 - Câmera com encerramento seguro e métricas locais de latência. @@ -8,13 +18,13 @@ - Carregamento seletivo do piloto, fundos opacos, renderização e pré-carga otimizadas. - README, ferramentas e versão da entrega alinhados. -## Prévia — sprint 3: controle confortável e mundo vivo +## Entrega anterior — sprint 3: controle confortável e mundo vivo O editor confirma escolhas mais devagar e exige sair do alvo antes de repetir. O controle de cabeça tolera melhor a perda de um marco facial, oferece calibração dos quatro alcances confortáveis e interrompe o cursor quando a leitura envelhece. Alto contraste também amplia avião, objetos e passagens, com escala ajustável. A vila começa industrial e colorida, tem moradores e pedidos persistentes e evolui para jardins, energia e alimentos integrados às construções. As margens do voo mudam gradualmente, o mapa tem rota e arte própria, o hangar mostra três modelos por página e a história usa quatro cenários ilustrados. Veja [escopo, operação e limites da sprint 3](docs/SPRINT3.md). Os testes de renderização e controle não substituem ensaios presenciais com webcam, projeção e crianças. -Baixe **Windows, cartucho e galeria** na [prévia da sprint 3](https://github.com/lapsin-maker/dobramundo/releases/tag/sprint3-controle-e-vida-2026-10-25). A [documentação da entrega](docs/ENTREGA_SPRINT3.md) inclui instalação, validação, desempenho medido e aceite presencial pendente. +Os artefatos dessa sprint pertencem à publicação histórica correspondente. Consulte a release mais recente para os downloads atuais. ## Entrega anterior — sprint 2: aquarela em movimento diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4cbc0ad..edb659f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,7 +4,7 @@ Use uma branch própria e descreva o problema e o comportamento final. Preserve ## Ambiente e validação -O pacote exige Python >=3.8; o build desktop usa 3.12. Instale `requirements.txt` para teclado/mouse, `pytest`, `ruff` e `Pillow` para desenvolver/testar. Para webcam, `pip install -e ".[webcam]"`. Use um ambiente separado para o TSDK, que exige Python 3.14. +O pacote declara Python >=3.8; a matriz de CI da entrega cobre 3.8/3.12 quando executada, e o build desktop usa 3.12. Instale `requirements.txt` para teclado/mouse, `pytest`, `ruff` e `Pillow` para desenvolver/testar. Para webcam, `pip install -e ".[webcam]"`. Use um ambiente separado para o TSDK, que exige Python 3.14. ```text python -m pytest -q @@ -12,7 +12,7 @@ ruff check . python -m dobramundo --self-test 1200 --exigir-camera ``` -O pytest isola dados em diretório temporário. Se o temporário padrão estiver inacessível, passe `--basetemp` apontando para uma **nova pasta de teste descartável**. Nunca use pasta de dados do jogador: pytest pode limpar o basetemp. +O pytest isola dados em diretório temporário. Se o temporário padrão estiver inacessível, passe `--basetemp` apontando para uma **nova pasta de teste descartável**. Nunca use pasta de dados do jogador: pytest pode limpar o basetemp. Perfis e recuperação devem ser testados com diretórios temporários injetados; não leia nem altere perfis reais durante os testes. `--exigir-camera` verifica a carga do detector; não captura vídeo. Para benchmark, use as ferramentas de `tools/` e registre condições, versão e equipamento. Não compare tempos enquanto outro build/teste pesado usa a mesma CPU. @@ -31,4 +31,4 @@ O lint ativo exclui `tools/legado`. Não formate todo o repositório dentro de u Mantenha originais e procedência. O runtime usa PNGs locais, sem geração por IA durante o jogo. Não converter formatos sem testar o suporte no console. Pintado → papel → lógico é uma cadeia de fallback, não código duplicado para apagar automaticamente. -Confira `__version__`, self-test do executável, check/build do TSDK e hashes dos pacotes antes da release. Registre o commit do código usado no build. Preserve releases históricas, branches compartilhadas e histórico Git sem limpeza destrutiva não solicitada. +Confira `__version__`, self-test do executável, check/build do TSDK e hashes dos pacotes antes da release. A versão do código é 1.6.0; isso, por si só, não confirma build nem publicação. Registre o commit do código usado no build e substitua apenas os campos explicitamente pendentes em `docs/ENTREGA_1_6.md` após produzir evidência. Preserve releases históricas, branches compartilhadas e histórico Git sem limpeza destrutiva não solicitada. diff --git a/Dobramundo.spec b/Dobramundo.spec index 89ef80f..bcf2a74 100644 --- a/Dobramundo.spec +++ b/Dobramundo.spec @@ -23,6 +23,8 @@ for file in sorted((ROOT / "assets").rglob("*")): datas.append((str(ROOT / "LICENSE"), ".")) # licença CC BY 4.0 junto do executável # MediaPipe: o hook padrão não leva a biblioteca nativa do MediaPipe Tasks (mediapipe/tasks/c). +# No Linux, libmediapipe.so usa libEGL.so.1 e libGLESv2.so.2: vêm do sistema +# (libegl1/libgles2), pois empacotá-las sem o driver/provider da máquina não é portátil. binaries, hiddenimports = [], [] try: from PyInstaller.utils.hooks import collect_all diff --git a/README.md b/README.md index c32cb7c..f9d4254 100644 --- a/README.md +++ b/README.md @@ -11,19 +11,21 @@ | Amazônia · Manaus | Caatinga · Petrolina | |---|---| -| ![Voo em Manaus](docs/screenshots/v150-manaus.png) | ![Voo em Petrolina](docs/screenshots/v150-petrolina.png) | +| ![Voo em Manaus](docs/screenshots/v160-manaus.png) | ![Voo em Petrolina](docs/screenshots/v160-petrolina.png) | ## Baixar e jogar -1. Abra a [última versão](https://github.com/lapsin-maker/dobramundo/releases/latest) e baixe o pacote **Windows**. +1. Abra a [última versão](https://github.com/lapsin-maker/dobramundo/releases/latest) e baixe o pacote **Windows** ou **Linux**. 2. Extraia **toda** a pasta; mantenha o executável junto da pasta `_internal`. -3. Abra **Jogar-Dobramundo.bat**. Não é necessário instalar Python. O lançador da versão 1.5 usa um perfil separado para não apagar os testes anteriores. +3. No Windows, abra **Jogar-Dobramundo.bat**; no Linux, instale os runtimes `libegl1` e `libgles2` (Debian/Ubuntu), extraia o `.tar.gz` e execute `./Dobramundo/Dobramundo`. Não é necessário instalar Python. A versão 1.6 mantém o perfil principal legado e oferece slots locais independentes para outros pilotos. -A release também oferece o cartucho `.ttea`, a galeria e hashes SHA-256. [Entrega 1.5.0 e validação](docs/ENTREGA_1_5.md) · [Histórico](CHANGELOG.md). +A release também oferece o cartucho `.ttea`, a galeria, o manifesto de build e hashes SHA-256. [Entrega 1.6.0 e resultados](docs/ENTREGA_1_6.md) · [Histórico](CHANGELOG.md). + +Se jogou a release 1.5 pelo seu lançador, use **Continuar-perfil-1.5.bat** para retomar aquela pasta de progresso. O atalho usa `%LOCALAPPDATA%\Dobramundo-1.5.0`, sem copiar ou apagar dados. O lançador padrão usa `%APPDATA%\Dobramundo`; os slots da tela **Trocar piloto** pertencem à pasta escolhida. ## O jogo -Para crianças de 6 a 10 anos, incluindo crianças neurodiversas e com deficiência, em uso mediado. A primeira personalização parte de um boneco neutro e inclui pele, cabelos, olhos, roupa, óculos, aparelho auditivo, cadeira de rodas e andador. +Projetado para crianças de 6 a 10 anos, com uso mediado e opções de controle e apresentação ajustáveis. A adequação e o conforto precisam de aceite presencial; este texto não afirma eficácia clínica. A primeira personalização parte de um boneco neutro e inclui pele, cabelos, olhos, roupa, óculos, aparelho auditivo, cadeira de rodas e andador. O ciclo é **piloto → vila → mapa → voo → resultado → obras e hangar**. A vila começa colorida, industrial e poluída; a coleta e as obras integram natureza, água, energia e alimentos. Manaus e Petrolina mantêm referências de seus biomas e construções nos três estágios. @@ -38,7 +40,7 @@ Detalhes de fases, ODS, regras e referências: [guia do jogo](docs/GUIA_DO_JOGO. - **Supervisor:** mouse e teclado, setas/WASD, pausa com Esc/P; recalibração e encerramento parcial no menu de pausa. - **Saída:** chão, mesa, parede ou monitor; rotação e espelho. Pés na projeção exigem calibrar seus quatro cantos. -Em **Opções → Preparar**, escolha conforto, contraste, treino e calibração. Calibre o neutro e os quatro alcances confortáveis com confirmação do supervisor. A ampliação no alto contraste vai de 1 a 1,6×. +Em **Opções → Preparar**, escolha exploração sem eliminação, duração (livre ou 120/180/240 s), assistência previsível, contraste, treino e calibração. O editor usa 3 segundos por padrão, ajustável. Calibre o neutro e os quatro alcances confortáveis com confirmação do supervisor. A ampliação no alto contraste vai de 1 a 1,6×. ## Acessibilidade e privacidade @@ -46,7 +48,7 @@ O jogo oferece permanência ajustável, cores e formas distintas, movimento redu A câmera é processada localmente; o jogo não grava vídeo nem envia imagens para serviços de IA. O diagnóstico exporta métricas técnicas. As ilustrações de IA são arquivos já incluídos no pacote. -Testes automatizados não substituem o ensaio da pessoa com a câmera, da projeção a 2–3 m e do conforto em sessão mediada. Consulte as condições e limitações nas notas da entrega. +Testes automatizados não substituem o ensaio da pessoa com a câmera, da projeção a 2–3 m e do conforto em sessão mediada. Os resultados de CI, builds e medições estão nas [notas da entrega](docs/ENTREGA_1_6.md); o [aceite presencial](docs/VALIDACAO_PRESENCIAL.md) continua pendente. ## Console T-TEA @@ -71,13 +73,14 @@ Para webcam, instale as dependências opcionais descritas em [CONTRIBUTING.md](C ```powershell python -m pytest -q ruff check . +ruff format --check . python -m dobramundo --self-test 1200 --exigir-camera python tools/benchmark_runtime.py --out build/benchmark --screenshots python tools/benchmark_camera.py --help python tools/check_routes.py --help ``` -O self-test percorre cenas/fases e carrega o detector de pose; **não abre a webcam**. A medição de câmera é uma ferramenta separada e explícita. `tools/legado` não faz parte do lint ativo. A formatação global ainda é trabalho separado. +O self-test percorre cenas/fases e carrega o detector de pose; **não abre a webcam**. A medição de câmera é uma ferramenta separada e explícita. `tools/legado` não faz parte do lint ativo. A formatação global foi isolada em commit próprio e agora é verificada na CI. Executável: `build_windows.bat` / `build_linux.sh`, ou `python -m PyInstaller --noconfirm Dobramundo.spec`. Os geradores procedurais são fallback e não recriam a arte de IA. [Ferramentas](tools/README.md) · [Arquitetura](docs/arquitetura.md) · [Análise consolidada e prioridades](docs/ANALISE_CONSOLIDADA.md). diff --git a/assets/watercolor_prepared/amazonia_0.png b/assets/watercolor_prepared/amazonia_0.png new file mode 100644 index 0000000..a99ea5d Binary files /dev/null and b/assets/watercolor_prepared/amazonia_0.png differ diff --git a/assets/watercolor_prepared/amazonia_1.png b/assets/watercolor_prepared/amazonia_1.png new file mode 100644 index 0000000..569e74a Binary files /dev/null and b/assets/watercolor_prepared/amazonia_1.png differ diff --git a/assets/watercolor_prepared/amazonia_2.png b/assets/watercolor_prepared/amazonia_2.png new file mode 100644 index 0000000..4bd914e Binary files /dev/null and b/assets/watercolor_prepared/amazonia_2.png differ diff --git a/assets/watercolor_prepared/asset_catalog.json b/assets/watercolor_prepared/asset_catalog.json new file mode 100644 index 0000000..13312f5 --- /dev/null +++ b/assets/watercolor_prepared/asset_catalog.json @@ -0,0 +1,914 @@ +{ + "schema": 1, + "generator": "tools/prepare_assets.py", + "generated_with": "pygame 2.6.1", + "provenance": { + "credit_file": "assets/watercolor/CREDITOS.txt", + "generation_metadata": [ + { + "file": "generation-pilot-sprint2.json", + "sha256": "b8ed28ae61fd8b89608b15ceed464474dfbc1a6f65c9527948db6ccdcee4f2f3" + }, + { + "file": "generation-sprint2.json", + "sha256": "bf20b6b201c5cbebb834a194d2ed8225cf70131f508b960093e0fef0e133a91c" + }, + { + "file": "generation-sprint3.json", + "sha256": "2079c96c91f5324b4aa1b68a3ceaf7094640fd06cd478d1354a53c192a3b800f" + }, + { + "file": "generation.json", + "sha256": "7a889ef29780c7940d50c924152e354b751f5c2066bd434ce7ac4fe13e702578" + } + ], + "method": "project-integrated image generation; local metadata is recorded, but is not a pixel-level source map" + }, + "license": "CC BY 4.0 project package; see root LICENSE and assets/watercolor/CREDITOS.txt.", + "logical_canvas": [ + 1100, + 650 + ], + "prepared_sizes": { + "amazonia_0": [ + 1132, + 650 + ], + "amazonia_1": [ + 1132, + 650 + ], + "amazonia_2": [ + 1132, + 650 + ], + "caatinga_0": [ + 1132, + 650 + ], + "caatinga_1": [ + 1132, + 650 + ], + "caatinga_2": [ + 1132, + 650 + ], + "planes_flight_a": [ + 768, + 512 + ], + "planes_flight_a_clean": [ + 768, + 512 + ], + "planes_flight_b": [ + 768, + 512 + ], + "planes_flight_c": [ + 768, + 512 + ], + "planes_menu_a": [ + 768, + 512 + ], + "planes_menu_b": [ + 768, + 512 + ], + "planes_menu_c": [ + 768, + 512 + ] + }, + "backdrop_target": [ + 1132, + 650 + ], + "backdrop_method": "pygame.transform.smoothscale; same raster operation as runtime fallback", + "assets": [ + { + "file": "amazonia_0.png", + "sha256": "378c3a0045a8c168e5cb6f058bdcf05acaa9aa7dd8b3281169b0215634df3eda", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 2904085, + "alpha_bounds": null, + "atlas": null, + "runtime_variant": { + "file": "watercolor_prepared/amazonia_0.png", + "dimensions": [ + 1132, + 650 + ], + "pivot": null, + "use": "flight backdrop; logical canvas plus 32 px parallax overscan", + "sha256": "980aa42f504072fcf995c5c8b86b41fd4aa03967a606cb44c78ebd6ad76f512c", + "bytes": 1273858 + } + }, + { + "file": "amazonia_1.png", + "sha256": "14688f31748ac59a57d57d0b7265add3a7f850f5367a48d011414b25b1e43985", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 2960187, + "alpha_bounds": null, + "atlas": null, + "runtime_variant": { + "file": "watercolor_prepared/amazonia_1.png", + "dimensions": [ + 1132, + 650 + ], + "pivot": null, + "use": "flight backdrop; logical canvas plus 32 px parallax overscan", + "sha256": "5771f31aa0b7a89df244ee8ed95cc1b96ed8188df334f4fd38cec0da6afd66ae", + "bytes": 1318216 + } + }, + { + "file": "amazonia_2.png", + "sha256": "b4325d933f998e17ce152b65b49d177ec34a739e7cd5669510eb916c455230a6", + "dimensions": [ + 1631, + 964 + ], + "source_bytes": 2893819, + "alpha_bounds": null, + "atlas": null, + "runtime_variant": { + "file": "watercolor_prepared/amazonia_2.png", + "dimensions": [ + 1132, + 650 + ], + "pivot": null, + "use": "flight backdrop; logical canvas plus 32 px parallax overscan", + "sha256": "0919dcee147c179af1209bf5cb16d02e93800dfc1f19c9a90983d628695cc4b2", + "bytes": 1281663 + } + }, + { + "file": "banks_amazonia.png", + "sha256": "4d9820b3e3cdab536823e08e7173513f809dac9315d10568bfbe7eb18a843bd8", + "dimensions": [ + 1448, + 1086 + ], + "source_bytes": 3069673, + "alpha_bounds": [ + 0, + 0, + 1448, + 1086 + ], + "atlas": { + "grid": [ + 4, + 3 + ], + "pivot": "cell bottom-center", + "use": "river margins" + } + }, + { + "file": "banks_caatinga.png", + "sha256": "83f8ee3c51fba9ad90f5c2d6a4368f6c7acf7515711f92cc2281231cf055b011", + "dimensions": [ + 1448, + 1086 + ], + "source_bytes": 2706432, + "alpha_bounds": [ + 0, + 13, + 1448, + 1073 + ], + "atlas": { + "grid": [ + 4, + 3 + ], + "pivot": "cell bottom-center", + "use": "desert margins" + } + }, + { + "file": "caatinga_0.png", + "sha256": "e3d574b22882edcf411c20657d59095c0a73204c2da1ccaeb5da552bf81b8f1f", + "dimensions": [ + 1631, + 964 + ], + "source_bytes": 2874699, + "alpha_bounds": null, + "atlas": null, + "runtime_variant": { + "file": "watercolor_prepared/caatinga_0.png", + "dimensions": [ + 1132, + 650 + ], + "pivot": null, + "use": "flight backdrop; logical canvas plus 32 px parallax overscan", + "sha256": "843f517d80b986c1ca12997e18ad12bbae151e584a34073c5e72d2c6af56ce2b", + "bytes": 1272481 + } + }, + { + "file": "caatinga_1.png", + "sha256": "ced9b5f31f620a653a42c8fd8acde7b16176e403237e862502a2a761904c1d94", + "dimensions": [ + 1631, + 964 + ], + "source_bytes": 2855673, + "alpha_bounds": null, + "atlas": null, + "runtime_variant": { + "file": "watercolor_prepared/caatinga_1.png", + "dimensions": [ + 1132, + 650 + ], + "pivot": null, + "use": "flight backdrop; logical canvas plus 32 px parallax overscan", + "sha256": "f9ccc5191b81c22072088d0830b5eeb413f5ffe868c091a2d2f5d8578f820c27", + "bytes": 1294012 + } + }, + { + "file": "caatinga_2.png", + "sha256": "ed7160eed01d3de42c64f82b340321099a283d9d4aa68d62abe3c71e929a9838", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 2906194, + "alpha_bounds": null, + "atlas": null, + "runtime_variant": { + "file": "watercolor_prepared/caatinga_2.png", + "dimensions": [ + 1132, + 650 + ], + "pivot": null, + "use": "flight backdrop; logical canvas plus 32 px parallax overscan", + "sha256": "f0926a421b6e853fdee5e7d53f557bb44bd939f26a138b46ad7e1ac3288f782f", + "bytes": 1277906 + } + }, + { + "file": "fauna_sprint3.png", + "sha256": "3624ba306d6f413609815cf02b24c5e0b2e82f5cae91d8e939cacb1252f29db0", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 1390714, + "alpha_bounds": [ + 15, + 11, + 1616, + 953 + ], + "atlas": { + "grid": [ + 3, + 2 + ], + "pivot": "cell bottom-center", + "use": "non-colliding distant fauna" + } + }, + { + "file": "items_refined.png", + "sha256": "2f9b1e70b3d2090dee45f2afebaf934b1991968545b742a2a26f747fd5fc8e56", + "dimensions": [ + 1774, + 887 + ], + "source_bytes": 1675791, + "alpha_bounds": [ + 32, + 6, + 1710, + 864 + ], + "atlas": { + "grid": [ + 4, + 2 + ], + "order": [ + "paper", + "plastic", + "metal", + "glass", + "shield", + "magnet", + "repair", + "blank" + ], + "pivot": "cell center", + "use": "collectibles and power-ups" + } + }, + { + "file": "obstacles_refined.png", + "sha256": "de3929f79a87144fd414bbd1da6dfa5584ab7ca52f096a265e3135034c173bb4", + "dimensions": [ + 1536, + 1024 + ], + "source_bytes": 2066398, + "alpha_bounds": [ + 23, + 0, + 1479, + 1024 + ], + "atlas": { + "grid": [ + 3, + 2 + ], + "order": [ + "industrial low", + "industrial gate", + "industrial tower", + "solar low", + "solar gate", + "solar tower" + ], + "pivot": "bottom-center; gate crop ends at physical beam edge", + "use": "collision visuals" + } + }, + { + "file": "pilot_base.png", + "sha256": "866891039c27117b6b978ded5d49cc2cc96c538f1a49e9af15167990a7b7e513", + "dimensions": [ + 1214, + 1295 + ], + "source_bytes": 951838, + "alpha_bounds": [ + 33, + 0, + 1163, + 1295 + ], + "atlas": { + "grid": [ + 2, + 2 + ], + "row_split": "710/1295 of source height", + "pivot": "cropped pose origin", + "use": "customizable pilot" + } + }, + { + "file": "pilot_hair_back.png", + "sha256": "9a5cf5a95e779a846ce1349d33880263b1b7b2a34125a32e76d854e224971151", + "dimensions": [ + 1448, + 1086 + ], + "source_bytes": 2102613, + "alpha_bounds": [ + 0, + 19, + 1448, + 1067 + ], + "atlas": { + "grid": [ + 4, + 3 + ], + "pivot": "fitted to pilot head anchor", + "use": "back hair layer" + } + }, + { + "file": "pilot_hair_front.png", + "sha256": "f0fef3ccaece02c170f40535e95c272809ea0c6de1aa38def1ef9ebbdb1d9b22", + "dimensions": [ + 1448, + 1086 + ], + "source_bytes": 1555743, + "alpha_bounds": [ + 0, + 15, + 1448, + 1071 + ], + "atlas": { + "grid": [ + 4, + 3 + ], + "pivot": "fitted to pilot head anchor", + "use": "front hair layer" + } + }, + { + "file": "pilot_mobility.png", + "sha256": "077e8468476db68acf1aedcb5c38abb1753031dd51324eba9d29907e5f380f22", + "dimensions": [ + 1215, + 1295 + ], + "source_bytes": 1425260, + "alpha_bounds": [ + 0, + 21, + 1207, + 1274 + ], + "atlas": { + "grid": [ + 2, + 2 + ], + "pivot": "pilot pose origin", + "use": "mobility aids" + } + }, + { + "file": "planes_flight_a.png", + "sha256": "af6a0a727a0f26ba4dfeaf1b4732bbc4c1078bc1f0dec5ecf9478863924d1cf8", + "dimensions": [ + 1536, + 1024 + ], + "source_bytes": 1868641, + "alpha_bounds": [ + 17, + 15, + 1505, + 1009 + ], + "atlas": { + "grid": [ + 2, + 2 + ], + "pivot": "plane center", + "use": "flight aircraft" + }, + "runtime_variant": { + "file": "watercolor_prepared/planes_flight_a.png", + "dimensions": [ + 768, + 512 + ], + "pivot": "atlas cells preserve row-major order; cell pivot handled by runtime cropper", + "use": "aircraft atlas; 384×256 px cells, scaled from 768×512 originals", + "sha256": "bf6f242e6422a6f7771df0ee7266037c3db39d8870b804650d343ed586173688", + "bytes": 491210 + } + }, + { + "file": "planes_flight_a_clean.png", + "sha256": "821d383eab93b8d28b59fb152d960df6e01900679273482851af9b8e9ae60859", + "dimensions": [ + 1536, + 1024 + ], + "source_bytes": 1782497, + "alpha_bounds": [ + 50, + 47, + 1472, + 907 + ], + "atlas": { + "grid": [ + 2, + 2 + ], + "pivot": "plane center", + "use": "flight aircraft fallback" + }, + "runtime_variant": { + "file": "watercolor_prepared/planes_flight_a_clean.png", + "dimensions": [ + 768, + 512 + ], + "pivot": "atlas cells preserve row-major order; cell pivot handled by runtime cropper", + "use": "aircraft atlas; 384×256 px cells, scaled from 768×512 originals", + "sha256": "a3b288864a3ae2cc8ba836046bb915f88082378586e15094783130bd4e721718", + "bytes": 479609 + } + }, + { + "file": "planes_flight_b.png", + "sha256": "cae9f9d6c64762af22b2640c222bda2008a1c2960247dc7d2d2f4c883ac37109", + "dimensions": [ + 1536, + 1024 + ], + "source_bytes": 1845699, + "alpha_bounds": [ + 35, + 9, + 1489, + 1015 + ], + "atlas": { + "grid": [ + 2, + 2 + ], + "pivot": "plane center", + "use": "flight aircraft" + }, + "runtime_variant": { + "file": "watercolor_prepared/planes_flight_b.png", + "dimensions": [ + 768, + 512 + ], + "pivot": "atlas cells preserve row-major order; cell pivot handled by runtime cropper", + "use": "aircraft atlas; 384×256 px cells, scaled from 768×512 originals", + "sha256": "0f68853797723409dc569b53036edd23f69be69f79df4d6583bcdddd645d52f9", + "bytes": 489038 + } + }, + { + "file": "planes_flight_c.png", + "sha256": "d22b6b0e5d0d083f87e72f33c09325f6b16636210cb65fab3c49d7223c76311f", + "dimensions": [ + 1536, + 1024 + ], + "source_bytes": 1679184, + "alpha_bounds": [ + 14, + 17, + 1521, + 921 + ], + "atlas": { + "grid": [ + 2, + 2 + ], + "pivot": "plane center", + "use": "flight aircraft" + }, + "runtime_variant": { + "file": "watercolor_prepared/planes_flight_c.png", + "dimensions": [ + 768, + 512 + ], + "pivot": "atlas cells preserve row-major order; cell pivot handled by runtime cropper", + "use": "aircraft atlas; 384×256 px cells, scaled from 768×512 originals", + "sha256": "2c8e0ceee783655c6f7c6d0d308e370f7941c17fe35f0341ea9d0cf7d69c4027", + "bytes": 451095 + } + }, + { + "file": "planes_menu_a.png", + "sha256": "4f7095b985ed8b415b681f2100e7b3e44206d899f213dde438cd0b2b71dd8931", + "dimensions": [ + 1536, + 1024 + ], + "source_bytes": 1983178, + "alpha_bounds": [ + 0, + 23, + 1518, + 961 + ], + "atlas": { + "grid": [ + 2, + 2 + ], + "pivot": "plane center", + "use": "menu aircraft" + }, + "runtime_variant": { + "file": "watercolor_prepared/planes_menu_a.png", + "dimensions": [ + 768, + 512 + ], + "pivot": "atlas cells preserve row-major order; cell pivot handled by runtime cropper", + "use": "aircraft atlas; 384×256 px cells, scaled from 768×512 originals", + "sha256": "812dc2746b003467bcfd7db25172f126bc9a46019eda2233bcff857c990240d2", + "bytes": 534877 + } + }, + { + "file": "planes_menu_b.png", + "sha256": "4493bd4179a628a8d4e281c1edfc7b4506ded78a40f312e5352a0405313ddf40", + "dimensions": [ + 1536, + 1024 + ], + "source_bytes": 1911546, + "alpha_bounds": [ + 0, + 21, + 1496, + 979 + ], + "atlas": { + "grid": [ + 2, + 2 + ], + "pivot": "plane center", + "use": "menu aircraft" + }, + "runtime_variant": { + "file": "watercolor_prepared/planes_menu_b.png", + "dimensions": [ + 768, + 512 + ], + "pivot": "atlas cells preserve row-major order; cell pivot handled by runtime cropper", + "use": "aircraft atlas; 384×256 px cells, scaled from 768×512 originals", + "sha256": "2d567cc624db593f90bf00e339089dbeafe967a008fc83a20b11b33400941f5a", + "bytes": 506630 + } + }, + { + "file": "planes_menu_c.png", + "sha256": "1c559f8ae0df8f4dcd25ddaddbc7ba61af6faf81ced069b9fb663d2b83cd72f3", + "dimensions": [ + 1536, + 1024 + ], + "source_bytes": 1856635, + "alpha_bounds": [ + 0, + 14, + 1514, + 972 + ], + "atlas": { + "grid": [ + 2, + 2 + ], + "pivot": "plane center", + "use": "menu aircraft" + }, + "runtime_variant": { + "file": "watercolor_prepared/planes_menu_c.png", + "dimensions": [ + 768, + 512 + ], + "pivot": "atlas cells preserve row-major order; cell pivot handled by runtime cropper", + "use": "aircraft atlas; 384×256 px cells, scaled from 768×512 originals", + "sha256": "b37612b4146c0eba4e48a09396accdd32f3c8fb8e8c95ffb5988bdfc668d5f9b", + "bytes": 496830 + } + }, + { + "file": "story_city.png", + "sha256": "c48038c928e02d5858188bd8a33a200f467391f0463d5caaa766c4ffda138912", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 3328924, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "story_fold.png", + "sha256": "0679719dafd431b089daa93e64ea53f46a4b7e308fff5987859bb4d924ab3321", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 2731740, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "story_launch.png", + "sha256": "cd45a6e5ab98a9a79a3ff73eec9c5956b5dba3eaf238b0984fddeea1ea35e229", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 2928390, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "story_newspaper.png", + "sha256": "5bd37d7d82b4cc09976185797feb68ea9a7a8538808ad3b861e5150761ccc137", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 3288084, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "terrain_tiles.png", + "sha256": "e2d194ebdbcb985f837450cc2dd4627da1d0196648c78d70d4cf5cd57cce8ba0", + "dimensions": [ + 1254, + 1254 + ], + "source_bytes": 3293927, + "alpha_bounds": null, + "atlas": { + "grid": [ + 2, + 2 + ], + "pivot": "repeating tile", + "use": "legacy ground fallback" + } + }, + { + "file": "terrain_tiles_v3.png", + "sha256": "8a8010969960038d6f3ab7f23bdc0792119bfc432cd82f1a3c3f00341c203490", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 2594430, + "alpha_bounds": null, + "atlas": { + "grid": [ + 2, + 2 + ], + "pivot": "repeating tile", + "use": "ground materials" + } + }, + { + "file": "travel_amazonia.png", + "sha256": "fe19f35b74cf02a068b077a0112f8332857716b286bf3aea677316b94af7a677", + "dimensions": [ + 1536, + 1024 + ], + "source_bytes": 3101371, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "travel_caatinga.png", + "sha256": "aced248bcea5757dabef88ff3fb63407811c0b168268d3d38dffdf02b2b532c2", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 3401828, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "village_clean.png", + "sha256": "db444a6831426531bb294c9bfe1995aadd9810812e2578c939d2710ecefe8d5b", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 3095653, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "village_final.png", + "sha256": "0c522d5efc506701f281c24cdd451353d4837579dfecaf75e8546dc7d60aeca1", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 3329833, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "village_industrial_v3.png", + "sha256": "94ab9fc34cdae157b8c1a86c762838e259b2c44a0554156b7fb72ef70355c114", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 3237767, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "village_intermediate.png", + "sha256": "723da0aeb1fb5dd63966fb35d02ab29f521df5c7151f502e530244359518b829", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 3164562, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "village_props.png", + "sha256": "4e0a985e34b78a734d0019e700c04a668ea4ba159d551161b85f45e0738fd378", + "dimensions": [ + 1774, + 887 + ], + "source_bytes": 2626170, + "alpha_bounds": [ + 0, + 9, + 1764, + 878 + ], + "atlas": { + "grid": [ + 4, + 2 + ], + "pivot": "cell bottom-center", + "use": "community upgrades" + } + }, + { + "file": "village_start.png", + "sha256": "a44f77bc17b87ea24911dfa64c2e78b0f371c0dfc9a869730a02f5298ca4e31b", + "dimensions": [ + 1632, + 964 + ], + "source_bytes": 3184460, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "village_start_v2.png", + "sha256": "2df5bc32ba6402a8722e445ff810a2ab9b9bba55307a1f1e80be0ce41900d9f7", + "dimensions": [ + 1631, + 964 + ], + "source_bytes": 3175159, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "village_transition_v3.png", + "sha256": "4baca37cc7bf7ea44979e1a31ea428a61e3a78b9b72b2a3c633994b3785c33e1", + "dimensions": [ + 1630, + 965 + ], + "source_bytes": 3226916, + "alpha_bounds": null, + "atlas": null + }, + { + "file": "villagers_sprint3.png", + "sha256": "77281d4fa3b409dd3af3e6d6cd688e7b412183a0bf78bf8cd1cdd4756096993d", + "dimensions": [ + 1536, + 1024 + ], + "source_bytes": 2286679, + "alpha_bounds": [ + 0, + 0, + 1518, + 1008 + ], + "atlas": { + "grid": [ + 3, + 2 + ], + "pivot": "cropped cell bottom-center", + "use": "village residents" + } + } + ] +} diff --git a/assets/watercolor_prepared/caatinga_0.png b/assets/watercolor_prepared/caatinga_0.png new file mode 100644 index 0000000..1a173dd Binary files /dev/null and b/assets/watercolor_prepared/caatinga_0.png differ diff --git a/assets/watercolor_prepared/caatinga_1.png b/assets/watercolor_prepared/caatinga_1.png new file mode 100644 index 0000000..da472b5 Binary files /dev/null and b/assets/watercolor_prepared/caatinga_1.png differ diff --git a/assets/watercolor_prepared/caatinga_2.png b/assets/watercolor_prepared/caatinga_2.png new file mode 100644 index 0000000..e310333 Binary files /dev/null and b/assets/watercolor_prepared/caatinga_2.png differ diff --git a/assets/watercolor_prepared/planes_flight_a.png b/assets/watercolor_prepared/planes_flight_a.png new file mode 100644 index 0000000..e495262 Binary files /dev/null and b/assets/watercolor_prepared/planes_flight_a.png differ diff --git a/assets/watercolor_prepared/planes_flight_a_clean.png b/assets/watercolor_prepared/planes_flight_a_clean.png new file mode 100644 index 0000000..8bdb31b Binary files /dev/null and b/assets/watercolor_prepared/planes_flight_a_clean.png differ diff --git a/assets/watercolor_prepared/planes_flight_b.png b/assets/watercolor_prepared/planes_flight_b.png new file mode 100644 index 0000000..0ea1127 Binary files /dev/null and b/assets/watercolor_prepared/planes_flight_b.png differ diff --git a/assets/watercolor_prepared/planes_flight_c.png b/assets/watercolor_prepared/planes_flight_c.png new file mode 100644 index 0000000..e0f7f73 Binary files /dev/null and b/assets/watercolor_prepared/planes_flight_c.png differ diff --git a/assets/watercolor_prepared/planes_menu_a.png b/assets/watercolor_prepared/planes_menu_a.png new file mode 100644 index 0000000..8289ddd Binary files /dev/null and b/assets/watercolor_prepared/planes_menu_a.png differ diff --git a/assets/watercolor_prepared/planes_menu_b.png b/assets/watercolor_prepared/planes_menu_b.png new file mode 100644 index 0000000..86dbd96 Binary files /dev/null and b/assets/watercolor_prepared/planes_menu_b.png differ diff --git a/assets/watercolor_prepared/planes_menu_c.png b/assets/watercolor_prepared/planes_menu_c.png new file mode 100644 index 0000000..403d846 Binary files /dev/null and b/assets/watercolor_prepared/planes_menu_c.png differ diff --git a/build_linux.sh b/build_linux.sh index e2c7b9b..408624e 100644 --- a/build_linux.sh +++ b/build_linux.sh @@ -1,66 +1,11 @@ #!/usr/bin/env bash -# build_linux.sh - gera o executavel Linux do Dobramundo com PyInstaller (onedir). -# -# Uso: -# ./build_linux.sh -# Saida: dist/Dobramundo/Dobramundo (distribua a pasta dist/Dobramundo inteira). -# -# Assets: o Dobramundo.spec ja empacota assets/ no executavel. Por isso assets/ -# NAO e copiado para dist/Dobramundo/. O jogo tambem procura assets/ ao lado do -# executavel, antes do pacote: para trocar um sprite sem recompilar, basta -# colocar o PNG em dist/Dobramundo/assets//.png. -# -# O PyInstaller nao faz compilacao cruzada: o .exe do Windows deve ser gerado -# no Windows (build_windows.bat). +# Build nativo Linux; mantém outras saídas de dist/ e perfis do jogador. set -euo pipefail - -die() { - echo "ERRO: $*" >&2 - exit 1 -} - cd "$(dirname "${BASH_SOURCE[0]}")" - -APP_DIR="dist/Dobramundo" -EXE="$APP_DIR/Dobramundo" - -command -v python3 >/dev/null 2>&1 \ - || die "python3 nao encontrado (no Debian/Ubuntu: sudo apt install python3 python3-venv)." - -echo "[1/5] Preparando o ambiente virtual .venv..." if [ ! -x ".venv/bin/python" ]; then - python3 -m venv .venv \ - || die "falha ao criar .venv (no Debian/Ubuntu instale o pacote python3-venv)." + python3.12 -m venv .venv fi PY=".venv/bin/python" - -echo "[2/5] Instalando dependencias (jogo, webcam e PyInstaller)..." -"$PY" -m pip install -r requirements-webcam.txt "pyinstaller>=6,<7" -c constraints-build.txt \ - || die "falha ao instalar as dependencias. Verifique a conexao com a internet." - -echo "[3/5] Limpando build/ e dist/..." -rm -rf build dist - -echo "[4/5] Gerando o executavel com PyInstaller..." -"$PY" -m PyInstaller --noconfirm --clean Dobramundo.spec \ - || die "o PyInstaller falhou. Veja as mensagens acima." -[ -x "$EXE" ] || die "executavel nao encontrado: $EXE" - -echo "[5/5] Copiando README.md e executando o self-test..." -cp README.md "$APP_DIR/" || die "nao foi possivel copiar README.md para $APP_DIR/." - -# Pasta de dados do jogo (ver user_data_dir em dobramundo/paths.py). -DATA_DIR="${DOBRAMUNDO_DATA_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/Dobramundo}" -REPORT="$DATA_DIR/self_test.json" -rm -f "$REPORT" - -if ! SDL_VIDEODRIVER=dummy "$EXE" --self-test 90 --exigir-camera; then - die "o self-test falhou (codigo de saida diferente de 0)." -fi -[ -f "$REPORT" ] || die "o self-test nao gerou o relatorio em $REPORT." -grep -q '"status": "ok"' "$REPORT" || die "relatorio do self-test sem status ok: $REPORT" - -echo "" -echo "Build concluido com sucesso." -echo "Executavel: $(pwd)/$EXE" -echo "Relatorio do self-test: $REPORT" +"$PY" -c 'import sys; assert sys.version_info[:2] == (3, 12), "O build fixado requer Python 3.12"' +"$PY" -m pip install -r requirements-webcam.txt pyinstaller -c constraints-build.txt +"$PY" tools/build_desktop.py "$@" diff --git a/build_windows.bat b/build_windows.bat index 0d645fd..a48d154 100644 --- a/build_windows.bat +++ b/build_windows.bat @@ -1,155 +1,28 @@ @echo off -rem ============================================================================ -rem build_windows.bat - gera o executavel do Dobramundo com PyInstaller -rem -rem Uso: -rem build_windows.bat gera dist\Dobramundo\Dobramundo.exe (onedir, padrao) -rem build_windows.bat onefile gera dist\Dobramundo.exe (arquivo unico) -rem build_windows.bat nopause nao espera tecla no final (uso automatizado) -rem Os argumentos podem ser combinados: build_windows.bat onefile nopause -rem -rem Requisitos: Python 3 para Windows (launcher py ou python no PATH). -rem O PyInstaller nao faz compilacao cruzada: gere o .exe neste Windows. -rem -rem Assets: o Dobramundo.spec ja empacota assets\ no executavel (em -rem _internal\assets no onedir). Por isso assets\ NAO e copiado para -rem dist\Dobramundo\assets\. O jogo tambem procura assets\ ao lado do .exe, -rem antes do pacote: para trocar um sprite sem recompilar, basta colocar o -rem PNG em dist\Dobramundo\assets\\.png. -rem -rem Variavel opcional: DOBRA_CONSOLE=1 mantem a janela de console (depuracao). -rem Aviso: se o self-test falhar, o executavel sem console mostra uma caixa -rem de mensagem, que so fecha quando for confirmada. -rem ============================================================================ +rem Build Windows; Python 3.12, sem apagar outras saídas ou saves. +rem Uso: build_windows.bat [onefile] [nopause] setlocal EnableExtensions - -set "ONEFILE=0" +cd /d "%~dp0" +if errorlevel 1 goto :fail +set "BUILD_ARGS=" set "NOPAUSE=0" for %%A in (%*) do ( - if /i "%%~A"=="onefile" set "ONEFILE=1" + if /i "%%~A"=="onefile" set "BUILD_ARGS=--onefile" if /i "%%~A"=="nopause" set "NOPAUSE=1" ) - -cd /d "%~dp0" -if errorlevel 1 goto :fail_cd - -if "%ONEFILE%"=="1" ( - set "MODO=onefile" - set "EXE=dist\Dobramundo.exe" - set "OUT_DIR=dist" -) else ( - set "MODO=onedir" - set "EXE=dist\Dobramundo\Dobramundo.exe" - set "OUT_DIR=dist\Dobramundo" -) - -rem Relatorio do self-test: pasta de dados do jogo (ver user_data_dir em dobramundo\paths.py). -set "REPORT=%APPDATA%\Dobramundo\self_test.json" -if defined DOBRAMUNDO_DATA_DIR set "REPORT=%DOBRAMUNDO_DATA_DIR%\self_test.json" - -echo [1/5] Procurando Python 3 e preparando o ambiente virtual .venv... -set "PY=" -py -3 -c "import sys" >nul 2>&1 -if not errorlevel 1 set "PY=py -3" -if not defined PY ( - python -c "import sys" >nul 2>&1 - if not errorlevel 1 set "PY=python" -) -if not defined PY goto :fail_python - +if not exist ".venv\Scripts\python.exe" py -3.12 -m venv .venv +if errorlevel 1 goto :fail set "VENV_PY=%CD%\.venv\Scripts\python.exe" -if exist "%VENV_PY%" goto :venv_ok -%PY% -m venv .venv -if errorlevel 1 goto :fail_venv -:venv_ok - -echo [2/5] Instalando dependencias (jogo, webcam e PyInstaller)... -"%VENV_PY%" -m pip install -r requirements-webcam.txt "pyinstaller>=6,<7" -c constraints-build.txt -if errorlevel 1 goto :fail_pip - -echo [3/5] Limpando build e dist... -if exist build rmdir /s /q build -if exist build goto :fail_clean -if exist dist rmdir /s /q dist -if exist dist goto :fail_clean - -echo [4/5] Gerando o executavel com PyInstaller (%MODO%)... -rem O spec le DOBRA_ONEFILE; limpamos para nao herdar um valor antigo do ambiente. -set "DOBRA_ONEFILE=" -if "%ONEFILE%"=="1" set "DOBRA_ONEFILE=1" -"%VENV_PY%" -m PyInstaller --noconfirm --clean Dobramundo.spec -if errorlevel 1 goto :fail_pyinstaller -if not exist "%EXE%" goto :fail_missing_exe - -echo [5/5] Copiando README.md e executando o self-test... -copy /y "README.md" "%OUT_DIR%\" >nul -if errorlevel 1 goto :fail_copy - -if exist "%REPORT%" del /q "%REPORT%" -set "SDL_VIDEODRIVER=dummy" -"%EXE%" --self-test 90 --exigir-camera -set "TEST_RC=%ERRORLEVEL%" -set "SDL_VIDEODRIVER=" -if not "%TEST_RC%"=="0" goto :fail_selftest -if not exist "%REPORT%" goto :fail_selftest - -echo. -echo Build concluido (%MODO%). -if "%ONEFILE%"=="1" ( - echo Distribua o arquivo: %CD%\%EXE% -) else ( - echo Distribua a pasta inteira: %CD%\%OUT_DIR% - echo Executavel: %CD%\%EXE% -) -echo Relatorio do self-test: %REPORT% -goto :end - -:fail_cd -echo ERRO: nao foi possivel entrar na pasta do script. -goto :fail - -:fail_python -echo ERRO: Python 3 nao encontrado. -echo Instale em https://www.python.org/downloads/ marcando "Add python.exe to PATH". -goto :fail - -:fail_venv -echo ERRO: falha ao criar o ambiente virtual .venv. -goto :fail - -:fail_pip -echo ERRO: falha ao instalar as dependencias. Verifique a conexao com a internet. -goto :fail - -:fail_clean -echo ERRO: nao foi possivel remover build ou dist. Feche programas que estejam usando esses arquivos. -goto :fail - -:fail_pyinstaller -echo ERRO: o PyInstaller falhou. Veja as mensagens acima. -goto :fail - -:fail_missing_exe -echo ERRO: executavel nao encontrado: %EXE% -goto :fail - -:fail_copy -echo ERRO: nao foi possivel copiar README.md para %OUT_DIR%. -goto :fail - -:fail_selftest -echo ERRO: o self-test falhou (codigo %TEST_RC%) ou nao gerou o relatorio em %REPORT%. -goto :fail - +"%VENV_PY%" -c "import sys; assert sys.version_info[:2] == (3, 12), 'O build fixado requer Python 3.12'" +if errorlevel 1 goto :fail +"%VENV_PY%" -m pip install -r requirements-webcam.txt pyinstaller -c constraints-build.txt +if errorlevel 1 goto :fail +"%VENV_PY%" tools\build_desktop.py %BUILD_ARGS% +if errorlevel 1 goto :fail +if "%BUILD_ARGS%"=="--onefile" (echo Build concluido: dist\Dobramundo.exe) else (echo Build concluido: distribua toda a pasta dist\Dobramundo) +if "%NOPAUSE%"=="0" pause +exit /b 0 :fail -echo. -echo Build NAO concluido. +echo ERRO: build nao concluido. Consulte a mensagem acima. if "%NOPAUSE%"=="0" pause -endlocal exit /b 1 - -:end -echo. -if "%NOPAUSE%"=="0" pause -endlocal -exit /b 0 diff --git a/constraints-build.txt b/constraints-build.txt index 53f4c98..d5d00fb 100644 --- a/constraints-build.txt +++ b/constraints-build.txt @@ -1,6 +1,7 @@ # Versões exatas usadas para gerar o executável (pip freeze do .venv de build). -# Os scripts de build instalam com "-c constraints-build.txt": o .exe sai igual em -# qualquer máquina. Para atualizar: instale as novas versões, teste e rode pip freeze. +# Os scripts instalam com "-c constraints-build.txt" para fixar as dependências. +# Sistema, toolchain e timestamps ainda podem produzir binários diferentes. +# Para atualizar: instale as novas versões, teste e rode pip freeze. absl-py==2.5.1 altgraph==0.17.5 certifi==2026.10.23 diff --git a/dobramundo/__init__.py b/dobramundo/__init__.py index 2262a21..b9b8e11 100644 --- a/dobramundo/__init__.py +++ b/dobramundo/__init__.py @@ -14,4 +14,4 @@ """ APP_NAME = "Dobramundo" -__version__ = "1.5.0" +__version__ = "1.6.0" diff --git a/dobramundo/app.py b/dobramundo/app.py index 9bcaf0a..db8265d 100644 --- a/dobramundo/app.py +++ b/dobramundo/app.py @@ -10,18 +10,32 @@ from __future__ import annotations import os -from typing import List, Optional +from typing import Callable, List, Optional import pygame from . import APP_NAME from . import config as C from .core import GameCore -from .persistence import Profile, load_profile +from .persistence import ( + Profile, + create_profile_slot, + list_profile_slots, + load_active_profile, + load_profile_with_notice, + profile_read_blocked, + save_profile, + set_active_profile_slot, +) class App(GameCore): - def __init__(self, audio: bool = True, profile: Optional[Profile] = None) -> None: + def __init__( + self, + audio: bool = True, + profile: Optional[Profile] = None, + scene_factory: Optional[Callable] = None, + ) -> None: pygame.init() pygame.display.set_caption(APP_NAME) if audio and not pygame.mixer.get_init(): @@ -30,16 +44,97 @@ def __init__(self, audio: bool = True, profile: Optional[Profile] = None) -> Non except pygame.error: pass # sem dispositivo de áudio: o jogo segue em silêncio self.display = self.open_window() - super().__init__(profile or load_profile(), audio, canvas=pygame.Surface((C.WIDTH, C.HEIGHT)).convert()) + if profile is None: + selected_profile, self.profile_slot, self.storage_notice = load_active_profile() + else: + selected_profile, self.profile_slot, self.storage_notice = profile, "principal", None + super().__init__( + selected_profile, + audio, + save=self._save_selected_profile, + canvas=pygame.Surface((C.WIDTH, C.HEIGHT)).convert(), + scene_factory=scene_factory, + ) icon = self.assets.sprite("ui", "icone") if icon is not None: pygame.display.set_icon(icon) self.clock = pygame.time.Clock() self.smooth_dt = 1.0 / C.FPS self.apply_options() - if self.profile.opcoes.tela_cheia: + + def apply_options(self) -> None: + super().apply_options() + self._sync_fullscreen() + + def _sync_fullscreen(self) -> None: + display = pygame.display.get_surface() + if display is None: + return + fullscreen = bool(display.get_flags() & pygame.FULLSCREEN) + if self.options.tela_cheia != fullscreen: self.toggle_fullscreen() + def _save_selected_profile(self, profile: Profile) -> bool: + return save_profile(profile, self.profile_slot) + + def list_profiles(self) -> list: + """Slots locais anônimos disponíveis para esta instalação desktop.""" + return list_profile_slots() + + def dismiss_storage_notice(self) -> None: + self.storage_notice = None + + def _activate_profile(self, slot_id: str) -> bool: + profile, notice = load_profile_with_notice(slot_id) + if profile_read_blocked(slot_id): + self.storage_notice = notice or "Não consegui ler este piloto. O perfil atual continua aberto." + return False + if not set_active_profile_slot(slot_id): + self.storage_notice = "Não consegui salvar a escolha deste piloto. O perfil atual continua aberto." + return False + self.profile_slot = slot_id + self.profile = profile + self.storage_notice = notice + self.save_failed = False + self.input.clear_keys() + self.input.mouse_pos = None + self.apply_options() + body = self.input.body + if body is not None: + body.recalibrate() + if hasattr(body, "point"): + body.point = None + from .core import first_scene + + self.go(first_scene(self)) + return True + + def select_profile(self, slot_id: str) -> bool: + """Salva o piloto atual antes de abrir outro; falha de escrita cancela a troca.""" + if self.platform != "desktop" or slot_id == self.profile_slot: + return slot_id == self.profile_slot + if not any(slot.id == slot_id for slot in self.list_profiles()): + return False + self.save() + if self.save_failed: + self.storage_notice = "Não foi possível salvar este piloto. A troca foi cancelada." + return False + return self._activate_profile(slot_id) + + def create_profile(self) -> bool: + """Cria um slot anônimo e o abre sem pedir nome ou dado pessoal.""" + if self.platform != "desktop": + return False + self.save() + if self.save_failed: + self.storage_notice = "Não foi possível salvar este piloto. O novo piloto não foi criado." + return False + slot = create_profile_slot() + if slot is None: + self.storage_notice = "Não consegui criar outro piloto. Confira o espaço disponível." + return False + return self._activate_profile(slot.id) + def floor_setup(self): """Pés sobre a projeção só com a superfície "chão" e os 4 cantos calibrados.""" o = self.options diff --git a/dobramundo/audio.py b/dobramundo/audio.py index 28dc4b7..23325ce 100644 --- a/dobramundo/audio.py +++ b/dobramundo/audio.py @@ -17,8 +17,12 @@ MUSIC_FADE_MS = 1600 CELEBRATION_PRIORITY = { - "sfx_powerup": 1, "sfx_compra": 2, "sfx_estrela": 3, - "sfx_estagio": 4, "sfx_fim_fase": 5, "sfx_game_over": 5, + "sfx_powerup": 1, + "sfx_compra": 2, + "sfx_estrela": 3, + "sfx_estagio": 4, + "sfx_fim_fase": 5, + "sfx_game_over": 5, } COLLECT_SFX = { "papel": "sfx_coleta_papel", diff --git a/dobramundo/cartridge.py b/dobramundo/cartridge.py index 75f57ae..587d0a4 100644 --- a/dobramundo/cartridge.py +++ b/dobramundo/cartridge.py @@ -17,7 +17,7 @@ from __future__ import annotations -from typing import List, Optional +from typing import Callable, List, Optional import pygame from ttea.sdk.api import Game, GameContext, feet_centre @@ -25,6 +25,7 @@ from . import config as C from .core import GameCore, first_scene from .input.console import TrackingSource, body_points +from .log import log from .persistence import Profile, ProfileError from .scenes.flight import FlightScene from .ui import theme as T @@ -75,11 +76,17 @@ class ConsoleCore(GameCore): platform = "ttea" - def __init__(self, profile: Profile, context: GameContext, source: TrackingSource) -> None: + def __init__( + self, + profile: Profile, + context: GameContext, + source: TrackingSource, + scene_factory: Optional[Callable] = None, + ) -> None: self.context = context self.source = source self.session: Optional[int] = None - super().__init__(profile, audio=True, save=self.store) + super().__init__(profile, audio=True, save=self.store, scene_factory=scene_factory) self.input.source_factory = lambda: source self.apply_options() @@ -92,7 +99,8 @@ def store(self, profile: Profile) -> bool: self.context.storage.write(PROFILE_KEY, profile.to_dict()) if self.context.records is not None: self.context.records.update_configuration(player_settings(profile)) - except Exception: # o armazenamento é do console: o jogo segue mesmo se falhar + except Exception: + log.exception("falha ao gravar dados do jogador no armazenamento T-TEA") return False return True @@ -106,17 +114,23 @@ def on_flight(self, summary: dict) -> None: self.session = records.start_session({"jogo": "dobramundo"}) records.record_event(self.session, summary) except Exception: + log.exception("falha ao registrar resumo de voo no T-TEA") self.session = None def load_profile(context: GameContext) -> Profile: """Perfil salvo deste jogador; na primeira vez, já com os pés sobre o chão interativo.""" - data = context.storage.read(PROFILE_KEY) + try: + data = context.storage.read(PROFILE_KEY) + except Exception: + log.exception("falha ao ler perfil do jogador no armazenamento T-TEA") + data = None profile = None if isinstance(data, dict): try: profile = Profile.from_dict(data) except ProfileError: + log.exception("perfil T-TEA inválido; iniciando perfil local do jogador") profile = None if profile is None: profile = Profile() @@ -126,7 +140,7 @@ def load_profile(context: GameContext) -> Profile: try: profile = apply_settings(profile, context.records.configuration(player_settings(profile))) except Exception: - pass + log.exception("falha ao ler opções do jogador no T-TEA") return profile diff --git a/dobramundo/config.py b/dobramundo/config.py index abeb91e..894faba 100644 --- a/dobramundo/config.py +++ b/dobramundo/config.py @@ -52,6 +52,12 @@ PLANE_HEIGHT = 34.0 MAX_LIVES = 3 INVULNERABLE_S = 1.25 +# Assistência opcional: ajuste fixo desde a decolagem (não muda velocidade nem rota). +ASSISTED_MAX_LIVES = 5 +ASSISTED_INVULNERABLE_S = 2.0 +# Durações selecionáveis na preparação. Zero mantém o voo livre histórico. +SESSION_LIMITS_S = (0, 120, 180, 240) +COMMUNITY_CHALLENGE_SEEDS = (20261025, 41721, 90817, 203011) HIT_FLASH_S = 0.28 HIT_SHAKE_S = 0.35 # tremor curto da tela na colisão (opção "efeitos fortes") diff --git a/dobramundo/content/biomes.py b/dobramundo/content/biomes.py index 0f2e7b1..81768ec 100644 --- a/dobramundo/content/biomes.py +++ b/dobramundo/content/biomes.py @@ -445,15 +445,6 @@ class LockedBiome(NamedTuple): } -def all_obstacle_specs() -> Dict[str, ObstacleTable]: - """Tabelas de obstáculos de todas as fases (para validar sprites e colisões).""" - tables: Dict[str, ObstacleTable] = {} - for biome in BIOMES.values(): - tables[f"{biome.key}:industrial"] = biome.industrial_obstacles - tables[f"{biome.key}:solar"] = biome.solar_obstacles - return tables - - def biome_sprite_names(biome: Biome) -> List[str]: """Todos os sprites de cenário que a fase usa.""" names = set() diff --git a/dobramundo/content/progress.py b/dobramundo/content/progress.py index f105575..b34dcd5 100644 --- a/dobramundo/content/progress.py +++ b/dobramundo/content/progress.py @@ -14,7 +14,7 @@ from ..config import ERA_SPAN Cost = Dict[str, int] # tipo de resíduo -> quantidade -COST_SCALE = 12 # custos-base x 12: tudo comprado em ~11 voos no Normal e ~5 no Difícil (tools/balance.py) +COST_SCALE = 12 # escala dos custos posteriores; primeiras obras têm preço de entrada próprio. def scaled(cost: Cost) -> Cost: @@ -39,7 +39,7 @@ class VillageUpgrade(NamedTuple): "ponto_troca", "Ponto de troca", "Separa os resíduos e os transforma em recursos.", - scaled({"papel": 6, "plastico": 6}), + {"papel": 8, "plastico": 8}, "VL_PontoTroca", (150, 470, 120), ), @@ -47,7 +47,7 @@ class VillageUpgrade(NamedTuple): "horta", "Horta urbana", "Alimento fresco plantado no meio da vila.", - scaled({"papel": 8, "vidro": 6}), + {"papel": 24, "vidro": 16}, "VL_Horta", (330, 520, 70), ), diff --git a/dobramundo/content/story.py b/dobramundo/content/story.py new file mode 100644 index 0000000..5b357bc --- /dev/null +++ b/dobramundo/content/story.py @@ -0,0 +1,9 @@ +"""Ritmo da abertura ilustrada, em segundos; geometria permanece na cena.""" + +PAGE_DURATIONS = (3.4, 4.2, 6.2, 5.2) +PAGE_TURN_S = 0.45 +LAUNCH_GLIDE_S = 3.2 +LAUNCH_FADE_S = 0.6 +LAUNCH_CAPTION_S = 2.4 +LOGO_APPEAR_S = 2.6 +LOGO_FADE_S = 1.0 diff --git a/dobramundo/core.py b/dobramundo/core.py index 6373125..2045fe7 100644 --- a/dobramundo/core.py +++ b/dobramundo/core.py @@ -33,20 +33,19 @@ def first_scene(app): """Aviso -> calibração -> treino de permanência -> piloto -> vila na primeira vez.""" - from .scenes import make_scene - - scene = make_scene(app, "vila") + scene = app.create_scene("vila") if not app.profile.piloto_montado: # a primeira coisa: a criança monta o personagem da história - pilot = make_scene(app, "piloto", first_time=True, return_to=scene) - scene = make_scene(app, "dwell_treino", next_scene=pilot, return_to=pilot) + pilot = app.create_scene("piloto", first_time=True, return_to=scene) + scene = app.create_scene("dwell_treino", next_scene=pilot, return_to=pilot) if app.input.uses_body: - scene = make_scene(app, "calibracao", return_to=scene) + scene = app.create_scene("calibracao", return_to=scene) if not app.profile.consentimento: - scene = make_scene(app, "aviso", scene) + scene = app.create_scene("aviso", scene) return scene class GameCore: + storage_notice: Optional[str] = None platform = "desktop" # "ttea" no console: as cenas escondem o que é só do executável def __init__( @@ -55,15 +54,17 @@ def __init__( audio: bool = True, save: Optional[Callable[[Profile], bool]] = None, canvas: Optional[pygame.Surface] = None, + scene_factory: Optional[Callable] = None, ) -> None: self.profile = profile self.canvas = canvas if canvas is not None else display_format(pygame.Surface((C.WIDTH, C.HEIGHT))) self.assets = shared_assets() self.text = Text() - self.view = WorldView(self.assets) + self.view = WorldView(self.assets, font=self.text.font(20, True)) self.audio = Audio(audio) self.input = InputHub() self.writer = save or save_profile + self.scene_factory = scene_factory self.running = True # False: a plataforma encerra o jogo (sair na vila ou no aviso) self.save_failed = False self.frame = 0 @@ -81,6 +82,14 @@ def save(self) -> None: """Grava o perfil; se não der, a vila avisa (o jogo segue).""" self.save_failed = not self.writer(self.profile) + def create_scene(self, name: str, *args, **kwargs): + """Cria uma cena pela fábrica injetada ou pelo registro padrão, sob demanda.""" + if self.scene_factory is not None: + return self.scene_factory(self, name, *args, **kwargs) + from .scenes import make_scene + + return make_scene(self, name, *args, **kwargs) + def apply_options(self) -> None: self.audio.apply(self.options) self.view.high_contrast = self.options.alto_contraste diff --git a/dobramundo/engine/accessible_view.py b/dobramundo/engine/accessible_view.py index 37401b3..b8676ea 100644 --- a/dobramundo/engine/accessible_view.py +++ b/dobramundo/engine/accessible_view.py @@ -22,10 +22,10 @@ def viewport(scale: float, focus: tuple, plane_size: tuple) -> pygame.Rect: half_h = min(180, plane_size[1] * scale / 2 + 12) target_x = clamp(x, half_w, C.WIDTH - half_w) target_y = clamp(y, 162 + half_h, C.HEIGHT - half_h - 8) - return pygame.Rect(round(clamp(x - target_x / scale, 0, C.WIDTH - w)), - round(clamp(y - target_y / scale, 0, C.HEIGHT - h)), w, h) + return pygame.Rect( + round(clamp(x - target_x / scale, 0, C.WIDTH - w)), round(clamp(y - target_y / scale, 0, C.HEIGHT - h)), w, h + ) def screen_point(point: tuple, rect: pygame.Rect) -> tuple: - return ((point[0] - rect.x) * C.WIDTH / rect.width, - (point[1] - rect.y) * C.HEIGHT / rect.height) + return ((point[0] - rect.x) * C.WIDTH / rect.width, (point[1] - rect.y) * C.HEIGHT / rect.height) diff --git a/dobramundo/engine/assets.py b/dobramundo/engine/assets.py index 6589bf2..1207b7f 100644 --- a/dobramundo/engine/assets.py +++ b/dobramundo/engine/assets.py @@ -15,6 +15,7 @@ from ..log import log from ..paths import asset_dir_candidates +from .cache import BoundedCache # Pastas de cenário que formam um único espaço de nomes (os nomes não se repetem). SCENERY_FOLDERS = ("dieselpunk_sprites", "scenario_sprites", "era_final_sprites", "biome_sprites") @@ -46,41 +47,95 @@ def load_image(path: Path, alpha: bool = True) -> Optional[pygame.Surface]: class Assets: - """Biblioteca de sprites por pasta, com cache.""" + """Biblioteca de sprites por pasta, com cache e liberação seletiva.""" def __init__(self) -> None: - self._folders: Dict[str, SpriteSet] = {} - self._loaded: Dict[str, pygame.Surface] = {} + # Índices de nomes/caminhos apenas: não mantenha uma segunda coleção de + # superfícies escondida além do cache de imagens decodificadas. + self._folders: BoundedCache = BoundedCache(64) + self._loaded: BoundedCache = BoundedCache(256, 48 * 1024 * 1024) self._scenery: Optional[SpriteSet] = None def folder(self, name: str, names: Optional[Iterable[str]] = None) -> SpriteSet: """Todos os PNGs da pasta (ou só os nomes pedidos, se informados).""" + names = None if names is None else tuple(names) key = name if names is None else f"{name}|{','.join(sorted(names))}" - cached = self._folders.get(key) - if cached is not None: - return cached wanted = None if names is None else set(names) - sprites: SpriteSet = {} - # Do pacote para o lado do executável: a pasta de maior prioridade sobrescreve. - for directory in reversed(asset_dir_candidates(name)): - if not directory.is_dir(): - continue - for path in sorted(directory.glob("*.png")): - if wanted is not None and path.stem not in wanted: + paths = self._folders.get(key) + if paths is None: + by_name = {} + # Do pacote para o lado do executável: a pasta de maior prioridade sobrescreve. + for directory in reversed(asset_dir_candidates(name)): + if not directory.is_dir(): continue - image = self._loaded.get(str(path)) - if image is None: - image = load_image(path) - if image is not None: - self._loaded[str(path)] = image + for path in sorted(directory.glob("*.png")): + if wanted is None or path.stem in wanted: + by_name[path.stem] = str(path) + paths = tuple(sorted(by_name.items())) + self._folders[key] = paths + sprites: SpriteSet = {} + for stem, path in paths: + image = self._loaded.get(path) + if image is None: + image = load_image(Path(path)) if image is not None: - sprites[path.stem] = image - self._folders[key] = sprites + self._loaded[path] = image + if image is not None: + sprites[stem] = image return sprites def sprite(self, folder: str, name: str) -> Optional[pygame.Surface]: return self.folder(folder, names=(name,)).get(name) + def scenery_for(self, names: Iterable[str]) -> SpriteSet: + """Carrega somente os nomes de cenário de que a vista ativa precisa.""" + wanted = set(names) + merged: SpriteSet = {} + for folder in SCENERY_FOLDERS: + merged.update(self.folder(folder, names=wanted)) + return merged + + def release_folder(self, name: str, names: Optional[Iterable[str]] = None) -> int: + """Solta referências de cache a uma pasta, ou a nomes específicos. + + Superfícies que uma cena ainda mantém continuam válidas; seus donos devem + soltar essas referências antes de pedir descarte seletivo. + """ + wanted = None if names is None else set(names) + folder_keys = [key for key in self._folders if key == name or key.startswith(name + "|")] + candidate_paths = set() + for key in folder_keys: + candidate_paths.update(path for stem, path in self._folders[key] if wanted is None or stem in wanted) + del self._folders[key] + removed = 0 + still_indexed = {path for paths in self._folders.values() for _, path in paths} + for path in candidate_paths - still_indexed: + if path in self._loaded: + del self._loaded[path] + removed += 1 + if name in SCENERY_FOLDERS: + self._scenery = None + return removed + + def release_scenery(self, names: Optional[Iterable[str]] = None) -> int: + removed = 0 + for folder in SCENERY_FOLDERS: + removed += self.release_folder(folder, names) + return removed + + def cache_stats(self) -> dict: + """Contagens e bytes estimados das superfícies retidas no cache da biblioteca.""" + seen = set() + retained = sum(BoundedCache.value_bytes(image, seen) for image in self._loaded.values()) + if self._scenery is not None: + retained += BoundedCache.value_bytes(self._scenery, seen) + return { + "loaded_images": len(self._loaded), + "loaded_surface_bytes": self._loaded.bytes, + "unique_retained_surface_bytes": retained, + "folder_views": len(self._folders), + } + @property def scenery(self) -> SpriteSet: """Todos os sprites de cenário (kits industriais, solarpunk e biomas).""" diff --git a/dobramundo/engine/cache.py b/dobramundo/engine/cache.py index 81cb7c5..8c78aed 100644 --- a/dobramundo/engine/cache.py +++ b/dobramundo/engine/cache.py @@ -8,19 +8,100 @@ from typing import Any, Dict, Hashable +import pygame + class BoundedCache(Dict[Hashable, Any]): """dict comum (get, in, len) que guarda no máximo ``limit`` itens.""" - def __init__(self, limit: int) -> None: + def __init__(self, limit: int, byte_limit: int = 0) -> None: super().__init__() self.limit = max(1, int(limit)) + self.byte_limit = max(0, int(byte_limit)) + self.bytes = 0 + + @classmethod + def value_bytes(cls, value: Any, seen=None) -> int: + """Estimativa de pixels retidos; não inclui objetos Python auxiliares.""" + if seen is None: + seen = set() + identity = id(value) + if identity in seen: + return 0 + seen.add(identity) + if isinstance(value, pygame.Surface): + return value.get_pitch() * value.get_height() + if isinstance(value, dict): + return sum(cls.value_bytes(item, seen) for item in value.values()) + if isinstance(value, (list, tuple, set)): + return sum(cls.value_bytes(item, seen) for item in value) + return 0 def __setitem__(self, key: Hashable, value: Any) -> None: + value_size = self.value_bytes(value) + if self.byte_limit and value_size > self.byte_limit: + if key in self: + self.__delitem__(key) + return + if key in self: + self.__delitem__(key) if key not in self: - while len(self) >= self.limit: - del self[next(iter(self))] + while len(self) >= self.limit or (self.byte_limit and self.bytes + value_size > self.byte_limit): + self.__delitem__(next(iter(self))) super().__setitem__(key, value) + self.bytes += value_size + + def __delitem__(self, key: Hashable) -> None: + value = super().__getitem__(key) + self.bytes = max(0, self.bytes - self.value_bytes(value)) + super().__delitem__(key) + + def clear(self) -> None: + super().clear() + self.bytes = 0 + + def pop(self, key: Hashable, *default: Any) -> Any: + if len(default) > 1: + raise TypeError(f"pop expected at most 2 arguments, got {len(default) + 1}") + if key not in self: + if default: + return default[0] + raise KeyError(key) + value = super().__getitem__(key) + self.__delitem__(key) + return value + + def popitem(self): + if not self: + raise KeyError("popitem(): cache is empty") + key = next(reversed(self)) + return key, self.pop(key) + + def setdefault(self, key: Hashable, default: Any = None) -> Any: + if key not in self: + self[key] = default + return self.get(key, default) + + def update(self, other=(), **kwargs: Any) -> None: + try: + for key in other.keys(): + self[key] = other[key] + except AttributeError: + for key, value in other: + self[key] = value + for key, value in kwargs.items(): + self[key] = value + + def __ior__(self, other): + self.update(other) + return self + + def discard_where(self, predicate) -> int: + """Remove itens que atendem ao predicado e devolve quantos saíram.""" + keys = [key for key in self if predicate(key)] + for key in keys: + self.__delitem__(key) + return len(keys) def put(self, key: Hashable, value: Any) -> Any: """Guarda e devolve o valor (para usar numa expressão).""" diff --git a/dobramundo/engine/contracts.py b/dobramundo/engine/contracts.py new file mode 100644 index 0000000..27d1512 --- /dev/null +++ b/dobramundo/engine/contracts.py @@ -0,0 +1,111 @@ +"""Dados lidos pelo desenho; nenhuma importação das regras ou plataformas. + +Objetos do jogo satisfazem estes Protocols estruturalmente. O desenho não +constrói partidas nem recalcula colisões: recebe seus limites já definidos. +Não copiar todo o mundo a cada quadro; os contratos descrevem uma leitura. +""" + +from __future__ import annotations + +from typing import Optional, Protocol, Sequence, Tuple + +from ..content.biomes import Biome +from ..content.items import ObstacleSpec +from ..util import Color + + +class BoundsView(Protocol): + x_min: float + x_max: float + y_min: float + y_max: float + z_min: float + z_max: float + + +class EntityView(Protocol): + x: float + y: float + z: float + kind: str + sprite: str + spec: Optional[ObstacleSpec] + solar: bool + collected: bool + hit: bool + dodged: bool + + def hitbox(self) -> BoundsView: ... + + +class ChallengeView(Protocol): + key: str + title: str + preferred_obstacle: str + decorations: Tuple[str, ...] + + +class WorldStateView(Protocol): + biome: Biome + distance: float + visual: float + entities: Sequence[EntityView] + challenge_theme: Optional[ChallengeView] + segments: Sequence[float] + segment_base: int + + def segment_green(self, seg: int) -> float: ... + def segment_solar(self, seg: int) -> float: ... + def solar_share(self) -> float: ... + def stage_flags(self) -> tuple: ... + def visual_stage_pair(self) -> tuple: ... + + +class PlayerView(Protocol): + x: float + y: float + vy: float + cam_x: float + roll: float + maneuver: object + + def hitbox(self) -> BoundsView: ... + def maneuver_pose(self) -> Optional[tuple]: ... + + +class BeamView(Protocol): + x: float + z: float + color: Color + ttl: float + + +class FloatingTextView(Protocol): + x: float + y: float + text: str + color: Color + ttl: float + + +class FlightView(Protocol): + world: WorldStateView + player: PlayerView + mode: str + invulnerable_timer: float + shield_timer: float + magnet_timer: float + beams: Sequence[BeamView] + floating: Sequence[FloatingTextView] + + +class PlaneLook: + """O que o jogador escolheu para o avião (modelo, pintura, piloto).""" + + def __init__( + self, plane: str, color: str = "original", pattern: str = "jornal", pilot: Optional[dict] = None + ) -> None: + self.plane = plane + self.color = color + self.pattern = pattern + self.pilot = pilot diff --git a/dobramundo/engine/entity_layer.py b/dobramundo/engine/entity_layer.py new file mode 100644 index 0000000..1c56eec --- /dev/null +++ b/dobramundo/engine/entity_layer.py @@ -0,0 +1,145 @@ +"""Objetos coletáveis e obstáculos, com contrato de leitura do motor.""" + +from __future__ import annotations + +import math + +import pygame + +from .. import config as C +from ..content.items import POWERUP_COLORS, WASTE_BY_KEY, ObstacleSpec +from ..util import Color, rgb +from .contracts import EntityView, WorldStateView +from .sprites import fog_level, project + +HC_OBSTACLE = rgb("ff3d00") + + +class EntityLayer: + def halo(self, screen: pygame.Surface, world: WorldStateView, entity: EntityView, size: float) -> None: + """Halo pulsante atrás do que se pode PEGAR, em todos os estágios e modos. + + O GDD pede distinguir resíduos de obstáculos: o halo marca o que se coleta e os + chevrons no chão (alert) marcam o que colide. + """ + halo = self.fx.get("halo_coletavel") + if halo is None: + return + pulse = (0.94, 1.0, 1.06)[int(self.elapsed * 4.0 + entity.z * 0.01) % 3] + h = size * C.FINAL_HALO_SCALE * pulse + self.blit_world(screen, halo, ("fx", "halo"), entity.x, entity.y - h / 2, entity.z + 1.0, h) + + def alert(self, screen: pygame.Surface, entity: EntityView, spec: ObstacleSpec) -> None: + """Estágio solarpunk: chevrons âmbar no chão da faixa antes do que COLIDE.""" + alert = self.fx.get("alerta_chao") + if alert is None: + return + near, far = entity.z - C.FINAL_ALERT_DEPTH[1], entity.z - C.FINAL_ALERT_DEPTH[0] + if near < C.NEAR_CLIP_Z or fog_level(far) >= C.FOG_LEVELS: + return + half = min(spec.width, C.LANE_WIDTH) * 0.42 + x0, y_far, _ = project(entity.x - half, 0, far, self.cam) + x1, _, _ = project(entity.x + half, 0, far, self.cam) + x2, y_near, _ = project(entity.x - half, 0, near, self.cam) + x3, _, _ = project(entity.x + half, 0, near, self.cam) + w, h = int(max(x1 - x0, x3 - x2)), int(y_near - y_far) + if w < 4 or h < 2 or w > C.WIDTH * 2: + return + step = max(2, int(w * 0.05)) + size = (w - w % step + step, max(2, h - h % max(2, int(h * 0.05)) + 2)) + scaled = self.cache.get(alert, ("fx", "alerta"), size) + level = fog_level(far) + if level > 0: + scaled = self.cache.fogged(scaled, (("fx", "alerta"), size, False), level) + screen.blit(scaled, (int((x2 + x3) / 2 - size[0] / 2), int(y_far))) + + def draw_entity(self, screen: pygame.Surface, world: WorldStateView, entity: EntityView) -> None: + if self.watercolor.load(world.biome.key): + self.paper_items.draw(screen, entity, self.cam, self.high_contrast) + if self.show_hitboxes: + pygame.draw.rect(screen, rgb("ff1744"), self.hitbox_rect(entity.hitbox()), 2) + return + if entity.kind == "waste": + self.draw_waste_entity(screen, world, entity) + elif entity.spec is None: # power-up + self.draw_powerup_entity(screen, world, entity) + else: + self.draw_obstacle_entity(screen, entity) + if self.show_hitboxes: + rect = self.hitbox_rect(entity.hitbox()) + pygame.draw.rect(screen, rgb("00e676") if entity.kind == "waste" else rgb("ff1744"), rect, 2) + + def draw_waste_entity(self, screen: pygame.Surface, world: WorldStateView, entity: EntityView) -> None: + self.halo(screen, world, entity, 46.0) + self.shadow(screen, entity.x, entity.z, 50, 70) + sprite = self.waste.get(entity.sprite) + color = WASTE_BY_KEY[entity.sprite].color if entity.sprite in WASTE_BY_KEY else rgb("ffb300") + bob = math.sin(self.elapsed * 3.0 + entity.z * 0.02) * 3 + if sprite is None: + self.fallback_ball(screen, entity, color, 22) + return + self.blit_world( + screen, + sprite, + ("item", entity.sprite), + entity.x, + entity.y - 23 + bob, + entity.z, + 46, + outline=color if self.high_contrast else None, + ) + + def draw_powerup_entity(self, screen: pygame.Surface, world: WorldStateView, entity: EntityView) -> None: + self.halo(screen, world, entity, 56.0) + self.shadow(screen, entity.x, entity.z, 46, 60) + sprite = self.powerups.get(entity.kind) + color = POWERUP_COLORS.get(entity.kind, (255, 255, 255)) + bob = math.sin(self.elapsed * 3.2 + entity.z * 0.015) * 4 + if sprite is None: + self.fallback_ball(screen, entity, color, 20) + return + self.blit_world( + screen, + sprite, + ("item", entity.kind), + entity.x, + entity.y - 26 + bob, + entity.z, + 56, + outline=color if self.high_contrast else None, + ) + + def draw_obstacle_entity(self, screen: pygame.Surface, entity: EntityView) -> None: + spec = entity.spec + if spec is None: + return + self.alert(screen, entity, spec) + self.ensure_scenery() + sprite = self.scenery.get(spec.sprite) + if sprite is not None: + self.blit_world( + screen, + sprite, + ("scenery", spec.sprite), + entity.x, + 0, + entity.z, + spec.visual_height, + outline=HC_OBSTACLE if self.high_contrast else None, + ) + return + rect = self.hitbox_rect(entity.hitbox()) + color = {"low": rgb("5d4037"), "gate": rgb("311b92"), "tower": rgb("3e2723")}[entity.kind] + pygame.draw.rect(screen, color, rect, 5 if entity.kind == "gate" else 0) + + def fallback_ball(self, screen: pygame.Surface, entity: EntityView, color: Color, radius: float) -> None: + x, y, scale = project(entity.x, entity.y, entity.z, self.cam) + r = max(3, int(radius * max(0.08, scale))) + pygame.draw.circle(screen, color, (int(x), int(y)), r) + pygame.draw.circle(screen, (255, 255, 255), (int(x), int(y)), r, max(1, r // 6)) + + def hitbox_rect(self, box) -> pygame.Rect: + z = max(20.0, (box.z_min + box.z_max) / 2) + x0, y0, _ = project(box.x_min, min(box.y_max, 330.0), z, self.cam) + x1, y1, _ = project(box.x_max, box.y_min, z, self.cam) + return pygame.Rect(int(x0), int(y0), max(1, int(x1 - x0)), max(1, int(y1 - y0))) diff --git a/dobramundo/engine/ground.py b/dobramundo/engine/ground.py index cfd3b03..e3f0c6f 100644 --- a/dobramundo/engine/ground.py +++ b/dobramundo/engine/ground.py @@ -17,6 +17,7 @@ from .. import config as C from ..util import Color, haze_at, lerp_color from .assets import Assets, display_format +from .cache import BoundedCache from .sprites import project Row = Tuple[int, float, int] # y da tela, profundidade, grupo de escala @@ -36,7 +37,7 @@ class GroundRenderer: def __init__(self, assets: Assets) -> None: self.textures = {name: display_format(s) for name, s in assets.folder("ground").items()} self.rows = compute_ground_rows() - self.groups: Dict[tuple, object] = {} + self.groups: BoundedCache = BoundedCache(256, 72 * 1024 * 1024) self.fog_cache: Dict[Color, pygame.Surface] = {} def has(self, name: Optional[str]) -> bool: diff --git a/dobramundo/engine/painted_pilot.py b/dobramundo/engine/painted_pilot.py index cc21b61..9e57f84 100644 --- a/dobramundo/engine/painted_pilot.py +++ b/dobramundo/engine/painted_pilot.py @@ -33,8 +33,18 @@ DEFAULT_SKIN_KEY = (252, 193, 128) DEFAULT_SHIRT_KEY = (162, 200, 225) HAIR_ORDER = ( - "curto", "cacheado", "crespo", "longo", "trancas", "coque", - "franja", "chiquinhas", "puffs", "moicano", "hijab", "raspado", + "curto", + "cacheado", + "crespo", + "longo", + "trancas", + "coque", + "franja", + "chiquinhas", + "puffs", + "moicano", + "hijab", + "raspado", ) HAIR_FIT = { # target head-width multiplier, crown offset as a fraction of body height @@ -310,296 +320,313 @@ def _mobility_layer(sprites, pose: str, look: Mapping[str, str], size, padding: return layer -def _painted_overlays( - size, - pose, - look, - skin_key, - seated, - view, - padding=0, - hair_back_art=None, - hair_front_art=None, - mobility_art=None, -): - """Paint hair, selectable eyes, accessories and mobility in a 3x transparent layer.""" - width, height = size - padding = max(0, int(padding)) - q = 3 - layer = pygame.Surface(((width + 2 * padding) * q, height * q), pygame.SRCALPHA) - ink = (48, 54, 76) - style = look["cabelo"] if hair_back_art is None and hair_front_art is None else UNSELECTED - hair = find_option(HAIR_COLORS, look["cor_cabelo"]).color - if hair is None or look["cor_cabelo"] == UNSELECTED: - hair = (105, 76, 58) - dark_hair = tuple(round(c * 0.62) for c in hair) - light_hair = tuple(min(255, c + 48) for c in hair) - if seated: - hx, hy, hw, hh = width * 0.055, 0, width * 0.86, height * 0.33 - eye_points = ((width * 0.333, height * 0.178), (width * 0.647, height * 0.178)) - else: - hx, hy, hw, hh = width * 0.143, 0, width * 0.72, height * 0.253 - eye_points = ((width * 0.377, height * 0.144), (width * 0.639, height * 0.144)) - - def r(x, y, w, h): - return pygame.Rect(round((x + padding) * q), round(y * q), max(1, round(w * q)), max(1, round(h * q))) - - def ellipse(box, fill, outline=dark_hair, width_px=2): - pygame.draw.ellipse(layer, outline, r(box[0], box[1], box[2], box[3]).inflate(width_px * q, width_px * q)) - pygame.draw.ellipse(layer, fill, r(*box)) - - def line(points, color, width_px=3, outline=ink): - pts = [(round((x + padding) * q), round(y * q)) for x, y in points] - if outline: - pygame.draw.lines(layer, outline, False, pts, max(1, round((width_px + 2) * q))) - pygame.draw.lines(layer, color, False, pts, max(1, round(width_px * q))) - - def poly(points, color, outline=dark_hair, width_px=2): - pts = [(round((x + padding) * q), round(y * q)) for x, y in points] - pygame.draw.polygon(layer, outline, pts) if outline else None - pygame.draw.polygon(layer, color, pts) - if outline and width_px: - pygame.draw.lines(layer, outline, True, pts, width_px * q) - - def hair_back(): - if style == UNSELECTED or style == "raspado": - return - if style == "hijab": - ellipse((hx - hw * 0.08, hy - hh * 0.05, hw * 1.16, hh * 1.03), hair, ink, max(2, round(width * 0.009))) - return - # Cap base is behind the painted face and leaves all original features intact. - cap_h = hh * 0.48 - ellipse((hx - hw * 0.055, hy - hh * 0.08, hw * 1.11, cap_h), hair, ink, max(2, round(width * 0.008))) - if style in ("longo", "trancas"): - for side in (-1, 1): - x = hx + (0 if side < 0 else hw * 0.78) - w = hw * 0.22 - ellipse((x, hy + hh * 0.28, w, hh * 1.05), hair, ink, max(2, round(width * 0.008))) - if style in ("coque", "chiquinhas"): - centers = (hx + hw * 0.12, hx + hw * 0.88) if style == "chiquinhas" else (hx + hw * 0.5,) - for x in centers: - ellipse((x - hw * 0.12, hy - hh * 0.16, hw * 0.24, hh * 0.27), hair, ink, max(2, round(width * 0.008))) - elif style == "puffs": - for x in (hx - hw * 0.09, hx + hw * 0.91): - ellipse((x - hw * 0.12, hy + hh * 0.04, hw * 0.24, hh * 0.28), hair, ink, max(2, round(width * 0.008))) - - def front_hair(): - if style == UNSELECTED or style == "raspado": - return - if style == "hijab": - # Framing folds track the temple line without covering eyes or cheeks. - for side in (-1, 1): - x = hx - hw * 0.045 if side < 0 else hx + hw * 0.91 - line( - [ - (x, hy + hh * 0.16), - (x - hw * 0.025 if side < 0 else x + hw * 0.025, hy + hh * 0.42), - (x + hw * 0.015 if side < 0 else x - hw * 0.015, hy + hh * 0.68), - ], - light_hair, - max( - 2, - round(width * 0.008), - ), - None, - ) - return - top = hy - hh * 0.015 - cap_bottom = hy + hh * 0.39 - if style in ("crespo", "cacheado", "puffs"): - count = 10 if style == "crespo" else 8 - radius = hw * 0.085 if style == "crespo" else hw * 0.071 - for i in range(count): - x = hx + hw * 0.02 + i * (hw * 0.96 / (count - 1)) - y = top + hh * 0.18 + math.sin(i * 1.8) * hh * 0.045 - ellipse((x - radius, y - radius, radius * 2, radius * 2), hair, ink, max(2, round(width * 0.006))) - pygame.draw.arc( - layer, - light_hair, - r(x - radius * 0.45, y - radius * 0.45, radius * 0.9, radius * 0.85), - 3.5, - 5.9, - max(1, round(width * 0.004)), - ) - elif style == "moicano": - poly( - [(hx + hw * 0.31, cap_bottom), (hx + hw * 0.5, top - hh * 0.12), (hx + hw * 0.7, cap_bottom)], - hair, - ink, - max(2, round(width * 0.008)), - ) - elif style == "franja": - poly( +def _painted_hair_back(canvas): + width = canvas["width"] + style = canvas["style"] + ellipse = canvas["ellipse"] + hx = canvas["hx"] + hw = canvas["hw"] + hy = canvas["hy"] + hh = canvas["hh"] + hair = canvas["hair"] + ink = canvas["ink"] + + if style == UNSELECTED or style == "raspado": + return + if style == "hijab": + ellipse((hx - hw * 0.08, hy - hh * 0.05, hw * 1.16, hh * 1.03), hair, ink, max(2, round(width * 0.009))) + return + # Cap base is behind the painted face and leaves all original features intact. + cap_h = hh * 0.48 + ellipse((hx - hw * 0.055, hy - hh * 0.08, hw * 1.11, cap_h), hair, ink, max(2, round(width * 0.008))) + if style in ("longo", "trancas"): + for side in (-1, 1): + x = hx + (0 if side < 0 else hw * 0.78) + w = hw * 0.22 + ellipse((x, hy + hh * 0.28, w, hh * 1.05), hair, ink, max(2, round(width * 0.008))) + if style in ("coque", "chiquinhas"): + centers = (hx + hw * 0.12, hx + hw * 0.88) if style == "chiquinhas" else (hx + hw * 0.5,) + for x in centers: + ellipse((x - hw * 0.12, hy - hh * 0.16, hw * 0.24, hh * 0.27), hair, ink, max(2, round(width * 0.008))) + elif style == "puffs": + for x in (hx - hw * 0.09, hx + hw * 0.91): + ellipse((x - hw * 0.12, hy + hh * 0.04, hw * 0.24, hh * 0.28), hair, ink, max(2, round(width * 0.008))) + + +def _painted_front_hair(canvas): + width = canvas["width"] + style = canvas["style"] + ellipse = canvas["ellipse"] + line = canvas["line"] + poly = canvas["poly"] + hx = canvas["hx"] + hw = canvas["hw"] + hy = canvas["hy"] + hh = canvas["hh"] + hair = canvas["hair"] + ink = canvas["ink"] + light_hair = canvas["light_hair"] + layer = canvas["layer"] + r = canvas["r"] + + if style == UNSELECTED or style == "raspado": + return + if style == "hijab": + # Framing folds track the temple line without covering eyes or cheeks. + for side in (-1, 1): + x = hx - hw * 0.045 if side < 0 else hx + hw * 0.91 + line( [ - (hx, hy + hh * 0.32), - (hx + hw * 0.18, hy + hh * 0.25), - (hx + hw * 0.35, hy + hh * 0.43), - (hx + hw * 0.5, hy + hh * 0.25), - (hx + hw * 0.67, hy + hh * 0.43), - (hx + hw * 0.84, hy + hh * 0.25), - (hx + hw, hy + hh * 0.35), - (hx + hw, top), - (hx, top), + (x, hy + hh * 0.16), + (x - hw * 0.025 if side < 0 else x + hw * 0.025, hy + hh * 0.42), + (x + hw * 0.015 if side < 0 else x - hw * 0.015, hy + hh * 0.68), ], - hair, - ink, - max(2, round(width * 0.006)), + light_hair, + max( + 2, + round(width * 0.008), + ), + None, ) - else: - ellipse((hx, top, hw, hh * 0.42), hair, ink, max(2, round(width * 0.007))) - # Fine hand-painted strands pick up the selected hair color. - for i in range(5): - x = hx + hw * (0.14 + i * 0.18) - line( - [(x, hy + hh * 0.08), (x - hw * 0.025, hy + hh * 0.20), (x, hy + hh * 0.31)], + return + top = hy - hh * 0.015 + cap_bottom = hy + hh * 0.39 + if style in ("crespo", "cacheado", "puffs"): + count = 10 if style == "crespo" else 8 + radius = hw * 0.085 if style == "crespo" else hw * 0.071 + for i in range(count): + x = hx + hw * 0.02 + i * (hw * 0.96 / (count - 1)) + y = top + hh * 0.18 + math.sin(i * 1.8) * hh * 0.045 + ellipse((x - radius, y - radius, radius * 2, radius * 2), hair, ink, max(2, round(width * 0.006))) + pygame.draw.arc( + layer, light_hair, + r(x - radius * 0.45, y - radius * 0.45, radius * 0.9, radius * 0.85), + 3.5, + 5.9, max(1, round(width * 0.004)), - None, ) - if style == "trancas": - for side in (-1, 1): - x = hx - hw * 0.02 if side < 0 else hx + hw * 0.98 - for j in range(5): - y = hy + hh * (0.35 + j * 0.17) - ellipse((x - hw * 0.055, y, hw * 0.11, hh * 0.12), hair, ink, max(1, round(width * 0.005))) - line( - [ - (x - hw * 0.025, y + hh * 0.02), - (x + hw * 0.025, y + hh * 0.07), - (x - hw * 0.02, y + hh * 0.11), - ], - light_hair, - max(1, round(width * 0.004)), - None, - ) - elif style == "longo": - for side in (-1, 1): - x = hx + hw * 0.06 if side < 0 else hx + hw * 0.94 + elif style == "moicano": + poly( + [(hx + hw * 0.31, cap_bottom), (hx + hw * 0.5, top - hh * 0.12), (hx + hw * 0.7, cap_bottom)], + hair, + ink, + max(2, round(width * 0.008)), + ) + elif style == "franja": + poly( + [ + (hx, hy + hh * 0.32), + (hx + hw * 0.18, hy + hh * 0.25), + (hx + hw * 0.35, hy + hh * 0.43), + (hx + hw * 0.5, hy + hh * 0.25), + (hx + hw * 0.67, hy + hh * 0.43), + (hx + hw * 0.84, hy + hh * 0.25), + (hx + hw, hy + hh * 0.35), + (hx + hw, top), + (hx, top), + ], + hair, + ink, + max(2, round(width * 0.006)), + ) + else: + ellipse((hx, top, hw, hh * 0.42), hair, ink, max(2, round(width * 0.007))) + # Fine hand-painted strands pick up the selected hair color. + for i in range(5): + x = hx + hw * (0.14 + i * 0.18) + line( + [(x, hy + hh * 0.08), (x - hw * 0.025, hy + hh * 0.20), (x, hy + hh * 0.31)], + light_hair, + max(1, round(width * 0.004)), + None, + ) + if style == "trancas": + for side in (-1, 1): + x = hx - hw * 0.02 if side < 0 else hx + hw * 0.98 + for j in range(5): + y = hy + hh * (0.35 + j * 0.17) + ellipse((x - hw * 0.055, y, hw * 0.11, hh * 0.12), hair, ink, max(1, round(width * 0.005))) line( [ - (x, hy + hh * 0.27), - (x + side * hw * 0.035, hy + hh * 0.52), - (x + side * hw * 0.01, hy + hh * 0.82), + (x - hw * 0.025, y + hh * 0.02), + (x + hw * 0.025, y + hh * 0.07), + (x - hw * 0.02, y + hh * 0.11), ], light_hair, max(1, round(width * 0.004)), None, ) - - def device_back(): - if look["cadeira"] == "sim": - radius = width * 0.20 - cy = height * 0.73 - for cx in (-width * 0.02, width * 1.02): - pygame.draw.circle( - layer, - ink, - (round((cx + padding) * q), round(cy * q)), - round(radius * q), - max(2, round(width * 0.012 * q)), - ) - pygame.draw.circle( - layer, - (228, 235, 227), - (round((cx + padding) * q), round(cy * q)), - round(radius * 0.88 * q), - max(2, round(width * 0.007 * q)), - ) - for angle in range(0, 360, 45): - ex = cx + radius * 0.76 * math.cos(math.radians(angle)) - ey = cy + radius * 0.76 * math.sin(math.radians(angle)) - line([(cx, cy), (ex, ey)], (120, 151, 163), max(1, round(width * 0.004)), None) + elif style == "longo": + for side in (-1, 1): + x = hx + hw * 0.06 if side < 0 else hx + hw * 0.94 line( - [(width * 0.31, height * 0.64), (width * 0.69, height * 0.64)], - (81, 139, 157), - max(3, round(width * 0.015)), + [ + (x, hy + hh * 0.27), + (x + side * hw * 0.035, hy + hh * 0.52), + (x + side * hw * 0.01, hy + hh * 0.82), + ], + light_hair, + max(1, round(width * 0.004)), + None, ) - line( - [(width * 0.30, height * 0.70), (width * 0.70, height * 0.70)], - (235, 181, 111), - max(3, round(width * 0.018)), + + +def _painted_device_back(canvas): + width = canvas["width"] + height = canvas["height"] + look = canvas["look"] + layer = canvas["layer"] + ink = canvas["ink"] + q = canvas["q"] + padding = canvas["padding"] + line = canvas["line"] + + if look["cadeira"] == "sim": + radius = width * 0.20 + cy = height * 0.73 + for cx in (-width * 0.02, width * 1.02): + pygame.draw.circle( + layer, + ink, + (round((cx + padding) * q), round(cy * q)), + round(radius * q), + max(2, round(width * 0.012 * q)), ) - elif look["andador"] == "sim": - for x, inward in ((width * 0.045, width * 0.17), (width * 0.955, width * 0.83)): - line( - [(x, height * 0.52), (x, height * 0.82), (x + (inward - x) * 0.32, height * 0.95)], - (83, 143, 160), - max(4, round(width * 0.018)), - ) - line( - [(width * 0.045, height * 0.52), (width * 0.17, height * 0.52)], - (83, 143, 160), - max(5, round(width * 0.022)), + pygame.draw.circle( + layer, + (228, 235, 227), + (round((cx + padding) * q), round(cy * q)), + round(radius * 0.88 * q), + max(2, round(width * 0.007 * q)), ) + for angle in range(0, 360, 45): + ex = cx + radius * 0.76 * math.cos(math.radians(angle)) + ey = cy + radius * 0.76 * math.sin(math.radians(angle)) + line([(cx, cy), (ex, ey)], (120, 151, 163), max(1, round(width * 0.004)), None) + line( + [(width * 0.31, height * 0.64), (width * 0.69, height * 0.64)], + (81, 139, 157), + max(3, round(width * 0.015)), + ) + line( + [(width * 0.30, height * 0.70), (width * 0.70, height * 0.70)], + (235, 181, 111), + max(3, round(width * 0.018)), + ) + elif look["andador"] == "sim": + for x, inward in ((width * 0.045, width * 0.17), (width * 0.955, width * 0.83)): line( - [(width * 0.83, height * 0.52), (width * 0.955, height * 0.52)], + [(x, height * 0.52), (x, height * 0.82), (x + (inward - x) * 0.32, height * 0.95)], (83, 143, 160), - max(5, round(width * 0.022)), - ) - line( - [(width * 0.045, height * 0.78), (width * 0.955, height * 0.78)], - (117, 167, 177), - max(3, round(width * 0.012)), + max(4, round(width * 0.018)), ) + line( + [(width * 0.045, height * 0.52), (width * 0.17, height * 0.52)], + (83, 143, 160), + max(5, round(width * 0.022)), + ) + line( + [(width * 0.83, height * 0.52), (width * 0.955, height * 0.52)], + (83, 143, 160), + max(5, round(width * 0.022)), + ) + line( + [(width * 0.045, height * 0.78), (width * 0.955, height * 0.78)], + (117, 167, 177), + max(3, round(width * 0.012)), + ) - def device_front(): - if look["cadeira"] == "sim": - line( - [(width * 0.30, height * 0.80), (width * 0.70, height * 0.80)], - (80, 136, 154), - max(3, round(width * 0.014)), - ) - line( - [ - (width * 0.35, height * 0.78), - (width * 0.35, height * 0.88), - (width * 0.65, height * 0.88), - (width * 0.65, height * 0.78), - ], - (80, 136, 154), - max(3, round(width * 0.014)), - ) - line( - [(width * 0.34, height * 0.89), (width * 0.47, height * 0.89)], - (240, 191, 110), - max(3, round(width * 0.012)), + +def _painted_device_front(canvas): + width = canvas["width"] + height = canvas["height"] + look = canvas["look"] + layer = canvas["layer"] + ink = canvas["ink"] + q = canvas["q"] + padding = canvas["padding"] + line = canvas["line"] + + if look["cadeira"] == "sim": + line( + [(width * 0.30, height * 0.80), (width * 0.70, height * 0.80)], + (80, 136, 154), + max(3, round(width * 0.014)), + ) + line( + [ + (width * 0.35, height * 0.78), + (width * 0.35, height * 0.88), + (width * 0.65, height * 0.88), + (width * 0.65, height * 0.78), + ], + (80, 136, 154), + max(3, round(width * 0.014)), + ) + line( + [(width * 0.34, height * 0.89), (width * 0.47, height * 0.89)], + (240, 191, 110), + max(3, round(width * 0.012)), + ) + line( + [(width * 0.53, height * 0.89), (width * 0.66, height * 0.89)], + (240, 191, 110), + max(3, round(width * 0.012)), + ) + elif look["andador"] == "sim": + for x in (width * 0.045, width * 0.955): + pygame.draw.circle( + layer, + ink, + (round((x + padding) * q), round(height * 0.95 * q)), + max(7, round(width * 0.038 * q)), ) - line( - [(width * 0.53, height * 0.89), (width * 0.66, height * 0.89)], - (240, 191, 110), - max(3, round(width * 0.012)), + pygame.draw.circle( + layer, + (115, 169, 179), + (round((x + padding) * q), round(height * 0.95 * q)), + max(5, round(width * 0.027 * q)), ) - elif look["andador"] == "sim": - for x in (width * 0.045, width * 0.955): - pygame.draw.circle( - layer, - ink, - (round((x + padding) * q), round(height * 0.95 * q)), - max(7, round(width * 0.038 * q)), - ) - pygame.draw.circle( - layer, - (115, 169, 179), - (round((x + padding) * q), round(height * 0.95 * q)), - max(5, round(width * 0.027 * q)), - ) - hair_back() + +def _compose_painted_overlays(canvas): + width = canvas["width"] + height = canvas["height"] + padding = canvas["padding"] + q = canvas["q"] + layer = canvas["layer"] + hair_back_art = canvas["hair_back_art"] + hair_front_art = canvas["hair_front_art"] + mobility_art = canvas["mobility_art"] + view = canvas["view"] + look = canvas["look"] + eye_points = canvas["eye_points"] + r = canvas["r"] + ink = canvas["ink"] + line = canvas["line"] + poly = canvas["poly"] + hx = canvas["hx"] + hw = canvas["hw"] + hy = canvas["hy"] + hh = canvas["hh"] + + _painted_hair_back(canvas) if hair_back_art is not None: layer.blit(hair_back_art, (0, 0)) if mobility_art is not None: layer.blit(mobility_art, (0, 0)) else: - device_back() + _painted_device_back(canvas) # A single layer combines back details, then caller places base art over it. final_size = (width + 2 * padding, height) back = pygame.transform.smoothscale(layer, final_size) layer.fill((0, 0, 0, 0)) - front_hair() + _painted_front_hair(canvas) if hair_front_art is not None: layer.blit(hair_front_art, (0, 0)) if mobility_art is None: - device_front() + _painted_device_front(canvas) # Personalized iris overlays sit on top of painted sclera only after a selection. if view != "flight" and look["olhos"] != UNSELECTED: @@ -709,6 +736,61 @@ def device_front(): return back, front +def _painted_overlays( + size, + pose, + look, + skin_key, + seated, + view, + padding=0, + hair_back_art=None, + hair_front_art=None, + mobility_art=None, +): + """Paint hair, selectable eyes, accessories and mobility in a 3x transparent layer.""" + width, height = size + padding = max(0, int(padding)) + q = 3 + layer = pygame.Surface(((width + 2 * padding) * q, height * q), pygame.SRCALPHA) + ink = (48, 54, 76) + style = look["cabelo"] if hair_back_art is None and hair_front_art is None else UNSELECTED + hair = find_option(HAIR_COLORS, look["cor_cabelo"]).color + if hair is None or look["cor_cabelo"] == UNSELECTED: + hair = (105, 76, 58) + dark_hair = tuple(round(c * 0.62) for c in hair) + light_hair = tuple(min(255, c + 48) for c in hair) + if seated: + hx, hy, hw, hh = width * 0.055, 0, width * 0.86, height * 0.33 + eye_points = ((width * 0.333, height * 0.178), (width * 0.647, height * 0.178)) + else: + hx, hy, hw, hh = width * 0.143, 0, width * 0.72, height * 0.253 + eye_points = ((width * 0.377, height * 0.144), (width * 0.639, height * 0.144)) + + def r(x, y, w, h): + return pygame.Rect(round((x + padding) * q), round(y * q), max(1, round(w * q)), max(1, round(h * q))) + + def ellipse(box, fill, outline=dark_hair, width_px=2): + pygame.draw.ellipse(layer, outline, r(box[0], box[1], box[2], box[3]).inflate(width_px * q, width_px * q)) + pygame.draw.ellipse(layer, fill, r(*box)) + + def line(points, color, width_px=3, outline=ink): + pts = [(round((x + padding) * q), round(y * q)) for x, y in points] + if outline: + pygame.draw.lines(layer, outline, False, pts, max(1, round((width_px + 2) * q))) + pygame.draw.lines(layer, color, False, pts, max(1, round(width_px * q))) + + def poly(points, color, outline=dark_hair, width_px=2): + pts = [(round((x + padding) * q), round(y * q)) for x, y in points] + pygame.draw.polygon(layer, outline, pts) if outline else None + pygame.draw.polygon(layer, color, pts) + if outline and width_px: + pygame.draw.lines(layer, outline, True, pts, width_px * q) + + canvas = locals() + return _compose_painted_overlays(canvas) + + def _action_overlay(image, view, skin, base_size, padding): """Distinct paper-plane gestures layered over the painted base pose.""" if view not in ("segura", "lanca"): @@ -763,8 +845,16 @@ def __init__( self.tolerance = tolerance # Pedir apenas as camadas do piloto: esta pasta também contém cenários # grandes que pertencem a outras cenas e devem continuar sob demanda. - names = (ATLAS_KEY, "pilot_hair_front", "pilot_hair_back", "pilot_mobility", - "front_standing", "back_standing", "front_seated", "back_seated") + names = ( + ATLAS_KEY, + "pilot_hair_front", + "pilot_hair_back", + "pilot_mobility", + "front_standing", + "back_standing", + "front_seated", + "back_seated", + ) self.sprites = dict(assets.folder(BASE_FOLDER, names=names)) atlas = self.sprites.get(ATLAS_KEY) if atlas is not None: @@ -802,21 +892,27 @@ def __init__( pygame.Rect(0, mid_y, mid_x, mobility_atlas.get_height() - mid_y), pygame.Rect(mid_x, mid_y, mobility_atlas.get_width() - mid_x, mobility_atlas.get_height() - mid_y), ) - for name, box in zip( - ("wheelchair_front", "wheelchair_back", "walker_front", "walker_back"), boxes - ): + for name, box in zip(("wheelchair_front", "wheelchair_back", "walker_front", "walker_back"), boxes): tile = mobility_atlas.subsurface(box).copy() bounds = tile.get_bounding_rect(min_alpha=15) if bounds.width and bounds.height: self.mobility_sprites[name] = tile.subsurface(bounds).copy() - self.palette = {name: _palette_layers(sprite) for name, sprite in self.sprites.items() if name in { - "front_standing", "back_standing", "front_seated", "back_seated" - }} - self.cache = BoundedCache(24) + for atlas_name in (ATLAS_KEY, "pilot_hair_front", "pilot_hair_back", "pilot_mobility"): + self.sprites.pop(atlas_name, None) + try: + assets.release_folder(BASE_FOLDER, (ATLAS_KEY, "pilot_hair_front", "pilot_hair_back", "pilot_mobility")) + except AttributeError: # compatibilidade com provedores mínimos usados por ferramentas/testes + pass + self.palette = { + name: _palette_layers(sprite) + for name, sprite in self.sprites.items() + if name in {"front_standing", "back_standing", "front_seated", "back_seated"} + } + self.cache = BoundedCache(24, 20 * 1024 * 1024) # Each cached pair is rendered at 3x for antialiasing; keep the raster # working set small so rapid appearance changes stay memory-bounded. - self.hair_cache = BoundedCache(8) - self.mobility_cache = BoundedCache(4) + self.hair_cache = BoundedCache(8, 12 * 1024 * 1024) + self.mobility_cache = BoundedCache(4, 6 * 1024 * 1024) @property def available(self) -> bool: diff --git a/dobramundo/engine/painted_planes.py b/dobramundo/engine/painted_planes.py index dd6cc55..b280b3c 100644 --- a/dobramundo/engine/painted_planes.py +++ b/dobramundo/engine/painted_planes.py @@ -27,7 +27,7 @@ def __init__(self, assets: Assets) -> None: self._bases: Dict[Tuple[str, str], Optional[pygame.Surface]] = {} self._paper_masks: Dict[str, pygame.Surface] = {} self._patterns: Dict[str, Optional[pygame.Surface]] = {} - self._cache = BoundedCache(96) + self._cache = BoundedCache(96, 40 * 1024 * 1024) @staticmethod def _atlas_index(plane: str) -> Optional[int]: @@ -42,9 +42,13 @@ def _atlas(self, plane: str, view: str) -> Optional[pygame.Surface]: return None group, cell_index = divmod(index, 4) names = MENU_ATLASES if view == "menu" else FLIGHT_ATLASES - atlas = self.assets.sprite("watercolor", names[group]) + atlas = self.assets.sprite("watercolor_prepared", names[group]) + if atlas is None: + atlas = self.assets.sprite("watercolor", names[group]) if atlas is None and view == "menu": - atlas = self.assets.sprite("watercolor", FLIGHT_ATLASES[group]) + atlas = self.assets.sprite("watercolor_prepared", FLIGHT_ATLASES[group]) + if atlas is None: + atlas = self.assets.sprite("watercolor", FLIGHT_ATLASES[group]) if atlas is None: return None cell_w, cell_h = atlas.get_width() // 2, atlas.get_height() // 2 @@ -99,8 +103,9 @@ def _pattern(self, assets: Assets, name: str, size: Tuple[int, int]) -> Optional return pygame.transform.smoothscale(pattern, size) return pattern - def painted(self, plane: str, view: str, color_key: str, pattern_key: str, - patterns: Assets) -> Optional[pygame.Surface]: + def painted( + self, plane: str, view: str, color_key: str, pattern_key: str, patterns: Assets + ) -> Optional[pygame.Surface]: base = self.base(plane, view) if base is None: return None @@ -130,8 +135,7 @@ def painted(self, plane: str, view: str, color_key: str, pattern_key: str, return out @staticmethod - def mount_pilot(plane_surface: pygame.Surface, pilot_renderer, plane: str, - view: str, look: dict) -> pygame.Surface: + def mount_pilot(plane_surface: pygame.Surface, pilot_renderer, plane: str, view: str, look: dict) -> pygame.Surface: """Encaixe relativo ao avião ilustrado, independente dos anchors legados.""" pilot_view = "flight" if view == "flight" else "menu" pilot_pose = "back_seated" if view == "flight" else "front_seated" diff --git a/dobramundo/engine/painted_route.py b/dobramundo/engine/painted_route.py index 93d7bd6..37f1a19 100644 --- a/dobramundo/engine/painted_route.py +++ b/dobramundo/engine/painted_route.py @@ -28,9 +28,9 @@ def __init__(self, atlas: pygame.Surface) -> None: for index, name in enumerate(("negro", "solimoes", "soil", "green")): w, h = atlas.get_size() col, row = index % 2, index // 2 - rect = pygame.Rect(col * w // 2, row * h // 2, - (col + 1) * w // 2 - col * w // 2, - (row + 1) * h // 2 - row * h // 2) + rect = pygame.Rect( + col * w // 2, row * h // 2, (col + 1) * w // 2 - col * w // 2, (row + 1) * h // 2 - row * h // 2 + ) small = pygame.transform.smoothscale(atlas.subsurface(rect), (512, 512)) # Espelhamento evita emendas de posição/cor no módulo da textura. tile = display_format(pygame.Surface((1024, 1024))) @@ -39,10 +39,11 @@ def __init__(self, atlas: pygame.Surface) -> None: self.textures[name] = tile # Faixas de três pixels preservam perspectiva sem custar centenas de # transformações extras; objetos/piloto continuam em resolução integral. - self.rows = compute_ground_rows()[::self.ROW_HEIGHT] + self.rows = compute_ground_rows()[:: self.ROW_HEIGHT] self.fog_cache = {} - self.source_rows = {name: tuple(tile.subsurface((0, v, 1024, 1)) for v in range(1024)) - for name, tile in self.textures.items()} + self.source_rows = { + name: tuple(tile.subsurface((0, v, 1024, 1)) for v in range(1024)) for name, tile in self.textures.items() + } self.line_buffers = {} def warm_tasks(self): @@ -113,6 +114,7 @@ def __init__(self, assets: Assets) -> None: atlas = assets.sprite("watercolor", "terrain_tiles") valid = atlas is not None and min(atlas.get_size()) >= 2 and atlas.get_bounding_rect().w > 0 self.ground = PaintedGround(atlas) if valid else None + assets.release_folder("watercolor", ("terrain_tiles_v3", "terrain_tiles")) self.banks = {} self.cache = SpriteCache() self.assets = assets @@ -125,9 +127,9 @@ def load(self, biome: str) -> tuple: w, h = atlas.get_size() for index in range(12): col, row = index % 4, index // 4 - rect = pygame.Rect(col * w // 4, row * h // 3, - (col + 1) * w // 4 - col * w // 4, - (row + 1) * h // 3 - row * h // 3) + rect = pygame.Rect( + col * w // 4, row * h // 3, (col + 1) * w // 4 - col * w // 4, (row + 1) * h // 3 - row * h // 3 + ) cell = atlas.subsurface(rect) bounds = cell.get_bounding_rect(min_alpha=30) if bounds.w == 0 or bounds.h == 0: @@ -135,8 +137,13 @@ def load(self, biome: str) -> tuple: break # pacote parcial: o chamador usa o cenário procedural completo sprites.append(display_format(cell.subsurface(bounds).copy(), True)) self.banks[biome] = tuple(sprites) + self.assets.release_folder("watercolor", ("banks_" + biome,)) return self.banks[biome] + def release_biome(self, biome: str) -> None: + self.banks.pop(biome, None) + self.cache = SpriteCache() + def ready(self, biome: str) -> bool: return self.ground is not None and len(self.load(biome)) == 12 diff --git a/dobramundo/engine/paper_items.py b/dobramundo/engine/paper_items.py index 9dbb348..843dd47 100644 --- a/dobramundo/engine/paper_items.py +++ b/dobramundo/engine/paper_items.py @@ -13,9 +13,9 @@ from .. import config as C from ..content.items import POWERUP_COLORS, POWERUP_KINDS, WASTE_BY_KEY -from ..game.entities import Entity from ..paths import find_asset_file from .cache import BoundedCache +from .contracts import EntityView from .sprites import project Color = Tuple[int, int, int] @@ -106,8 +106,22 @@ def _paper_token(key: str, rim: Color) -> pygame.Surface: pygame.draw.line(surface, (69, 161, 192), (47, 50), (59, 36), 4) elif key == "magnet": magnet = [ - (26, 21), (39, 21), (39, 46), (42, 54), (48, 58), (54, 54), (57, 46), (57, 21), - (70, 21), (70, 47), (65, 61), (56, 70), (48, 73), (39, 70), (30, 61), (26, 47), + (26, 21), + (39, 21), + (39, 46), + (42, 54), + (48, 58), + (54, 54), + (57, 46), + (57, 21), + (70, 21), + (70, 47), + (65, 61), + (56, 70), + (48, 73), + (39, 70), + (30, 61), + (26, 47), ] _polygon(surface, magnet, (196, 111, 202), 5) pygame.draw.rect(surface, CORAL, (26, 18, 13, 13), border_radius=2) @@ -291,15 +305,13 @@ def __init__(self, cache_limit: int = 192) -> None: index = (3 if solar else 0) + ("low", "gate", "tower").index(kind) base = obstacle_art[index] self.canonical[("obstacle", kind, solar)] = base - self._scaled: BoundedCache = BoundedCache(cache_limit) - self._shadows: BoundedCache = BoundedCache(64) + self._scaled: BoundedCache = BoundedCache(cache_limit, 12 * 1024 * 1024) + self._shadows: BoundedCache = BoundedCache(64, 2 * 1024 * 1024) for kind in ("low", "gate", "tower"): for solar in (False, True): key = ("obstacle", kind, solar) warning = CORAL if solar else SUN - self.canonical[("obstacle-outline", kind, solar)] = _obstacle_outline( - self.canonical[key], warning - ) + self.canonical[("obstacle-outline", kind, solar)] = _obstacle_outline(self.canonical[key], warning) def _scale(self, key: Hashable, size: Size) -> pygame.Surface: size = (max(1, int(size[0])), max(1, int(size[1]))) @@ -326,7 +338,7 @@ def _shadow(self, size: Size) -> pygame.Surface: self._shadows[size] = result return result - def _draw_token(self, screen: pygame.Surface, entity: Entity, cam: float, high_contrast: bool) -> None: + def _draw_token(self, screen: pygame.Surface, entity: EntityView, cam: float, high_contrast: bool) -> None: if entity.kind == "waste": key = ("waste", entity.sprite if entity.sprite in WASTE_BY_KEY else "papel") radius = 30.0 @@ -351,7 +363,7 @@ def _draw_token(self, screen: pygame.Surface, entity: Entity, cam: float, high_c sprite = self._scale(key, (diameter, diameter)) screen.blit(sprite, (int(sx - diameter / 2), int(sy - diameter / 2))) - def _draw_obstacle(self, screen: pygame.Surface, entity: Entity, cam: float, high_contrast: bool) -> None: + def _draw_obstacle(self, screen: pygame.Surface, entity: EntityView, cam: float, high_contrast: bool) -> None: spec = entity.spec if spec is None: return @@ -384,7 +396,7 @@ def _draw_obstacle(self, screen: pygame.Surface, entity: Entity, cam: float, hig sprite = self._scale(key, (width, height)) screen.blit(sprite, rect) - def draw(self, screen: pygame.Surface, entity: Entity, cam: float, high_contrast: bool = False) -> None: + def draw(self, screen: pygame.Surface, entity: EntityView, cam: float, high_contrast: bool = False) -> None: """Desenha entidade no centro projetado, sem alterar seu tipo ou hitbox. Waste e power-ups usam o centro de sua hitbox (raios 30/28 do mundo); diff --git a/dobramundo/engine/paper_pilot.py b/dobramundo/engine/paper_pilot.py index 18ad681..0cea889 100644 --- a/dobramundo/engine/paper_pilot.py +++ b/dobramundo/engine/paper_pilot.py @@ -382,49 +382,18 @@ def _painterly_finish(surface: pygame.Surface, view: str, look: dict) -> pygame. return pygame.transform.scale(image, SIZE) -def _draw_pilot_painted(view: str, look: dict) -> pygame.Surface: - """High-resolution native-Pygame illustration; all measurements are logical pixels.""" - q = 3 - image = pygame.Surface((SIZE[0] * q, SIZE[1] * q), pygame.SRCALPHA) - ink = (31, 53, 93) - face = find_option(SKIN_CHOICES, look["pele"]).color or (247, 229, 198) - shirt = find_option(SHIRT_COLORS, look["roupa"]).color or (239, 226, 194) - hair_color = find_option(HAIR_COLORS, look["cor_cabelo"]).color or (218, 211, 193) - eye_color = find_option(EYE_COLORS, look["olhos"]).color or (83, 66, 52) - - def rect(x, y, w, h): - return pygame.Rect(round(x * q), round(y * q), round(w * q), round(h * q)) - - def ellipse(box, color, border=ink, width=2): - outer = rect(*box).inflate(width * 2 * q, width * 2 * q) - pygame.draw.ellipse(image, border, outer) - pygame.draw.ellipse(image, color, rect(*box)) - - def stroke(points, color, width=3, outline=ink): - pts = [(round(x * q), round(y * q)) for x, y in points] - if outline and width > 1: - pygame.draw.lines(image, outline, False, pts, round((width + 2.3) * q)) - pygame.draw.lines(image, color, False, pts, max(1, round(width * q))) - for x, y in (pts[0], pts[-1]): - pygame.draw.circle(image, color, (x, y), max(1, round(width * q / 2))) - - def polygon(points, color, border=ink, width=2): - pts = [(round(x * q), round(y * q)) for x, y in points] - if border: - pygame.draw.polygon(image, border, pts) - pygame.draw.polygon(image, color, pts) - if border and width > 1: - pygame.draw.lines(image, border, True, pts, width * q) - - def wash_ellipse(box, color): - layer = pygame.Surface(image.get_size(), pygame.SRCALPHA) - pygame.draw.ellipse(layer, color, rect(*box)) - image.blit(layer, (0, 0)) - - def wash_arc(box, color, start, stop, width): - layer = pygame.Surface(image.get_size(), pygame.SRCALPHA) - pygame.draw.arc(layer, color, rect(*box), start, stop, width * q) - image.blit(layer, (0, 0)) +def _draw_paper_body(canvas): + image = canvas["image"] + look = canvas["look"] + rect = canvas["rect"] + q = canvas["q"] + ink = canvas["ink"] + ellipse = canvas["ellipse"] + stroke = canvas["stroke"] + polygon = canvas["polygon"] + wash_arc = canvas["wash_arc"] + face = canvas["face"] + shirt = canvas["shirt"] # Soft landing shadow and assistive device are placed behind the body. pygame.draw.ellipse(image, (50, 65, 77, 42), rect(25, 212, 140, 14)) @@ -511,6 +480,18 @@ def wash_arc(box, color, start, stop, width): polygon([(88, 163), (108, 170), (91, 176)], (255, 248, 228), None) stroke([(88, 163), (91, 176)], ink, 1.4, None) + +def _draw_paper_hair_silhouette(canvas): + image = canvas["image"] + look = canvas["look"] + rect = canvas["rect"] + ellipse = canvas["ellipse"] + stroke = canvas["stroke"] + polygon = canvas["polygon"] + q = canvas["q"] + ink = canvas["ink"] + hair_color = canvas["hair_color"] + # Hair silhouette behind the head, with shape-specific volume and strand rhythm. style = look["cabelo"] if style not in (UNSELECTED, "raspado"): @@ -560,6 +541,24 @@ def wash_arc(box, color, start, stop, width): polygon([(70, 55), (92, 5), (117, 55)], hair_color, ink, 2) elif style == "franja": polygon([(51, 43), (68, 38), (82, 54), (98, 39), (114, 54), (133, 39), (140, 50)], hair_color, ink, 1) + return style + + +def _draw_paper_face(canvas): + image = canvas["image"] + view = canvas["view"] + look = canvas["look"] + face = canvas["face"] + eye_color = canvas["eye_color"] + hair_color = canvas["hair_color"] + rect = canvas["rect"] + ellipse = canvas["ellipse"] + polygon = canvas["polygon"] + wash_ellipse = canvas["wash_ellipse"] + stroke = canvas["stroke"] + q = canvas["q"] + ink = canvas["ink"] + style = canvas["style"] # Head, cheek volume, ears and face-facing/away expressions. if view == "flight": @@ -670,6 +669,16 @@ def wash_arc(box, color, start, stop, width): ellipse((136, 76, 9, 11), (45, 146, 157), width=1) pygame.draw.ellipse(image, (247, 213, 124), rect(139, 78, 3, 4)) + +def _draw_paper_gesture(canvas): + view = canvas["view"] + face = canvas["face"] + shirt = canvas["shirt"] + ellipse = canvas["ellipse"] + polygon = canvas["polygon"] + stroke = canvas["stroke"] + ink = canvas["ink"] + # Poses: a paper plane close to the chest, or an arm raised to launch it. if view == "segura": polygon([(77, 157), (111, 157), (117, 178), (75, 178)], (252, 246, 228), ink, 2) @@ -682,6 +691,14 @@ def wash_arc(box, color, start, stop, width): ellipse((154, 108, 17, 18), face, width=1) polygon([(158, 104), (168, 87), (170, 107)], (255, 248, 228), ink, 1) + +def _finish_paper_pilot(canvas): + image = canvas["image"] + view = canvas["view"] + look = canvas["look"] + face = canvas["face"] + style = canvas["style"] + # Paper fibers and pigment blooms are clipped to the character silhouette. grain = pygame.Surface(image.get_size(), pygame.SRCALPHA) rng = random.Random(20261025) @@ -707,6 +724,59 @@ def wash_arc(box, color, start, stop, width): return final +def _draw_pilot_painted(view: str, look: dict) -> pygame.Surface: + """High-resolution native-Pygame illustration; all measurements are logical pixels.""" + q = 3 + image = pygame.Surface((SIZE[0] * q, SIZE[1] * q), pygame.SRCALPHA) + ink = (31, 53, 93) + face = find_option(SKIN_CHOICES, look["pele"]).color or (247, 229, 198) + shirt = find_option(SHIRT_COLORS, look["roupa"]).color or (239, 226, 194) + hair_color = find_option(HAIR_COLORS, look["cor_cabelo"]).color or (218, 211, 193) + eye_color = find_option(EYE_COLORS, look["olhos"]).color or (83, 66, 52) + + def rect(x, y, w, h): + return pygame.Rect(round(x * q), round(y * q), round(w * q), round(h * q)) + + def ellipse(box, color, border=ink, width=2): + outer = rect(*box).inflate(width * 2 * q, width * 2 * q) + pygame.draw.ellipse(image, border, outer) + pygame.draw.ellipse(image, color, rect(*box)) + + def stroke(points, color, width=3, outline=ink): + pts = [(round(x * q), round(y * q)) for x, y in points] + if outline and width > 1: + pygame.draw.lines(image, outline, False, pts, round((width + 2.3) * q)) + pygame.draw.lines(image, color, False, pts, max(1, round(width * q))) + for x, y in (pts[0], pts[-1]): + pygame.draw.circle(image, color, (x, y), max(1, round(width * q / 2))) + + def polygon(points, color, border=ink, width=2): + pts = [(round(x * q), round(y * q)) for x, y in points] + if border: + pygame.draw.polygon(image, border, pts) + pygame.draw.polygon(image, color, pts) + if border and width > 1: + pygame.draw.lines(image, border, True, pts, width * q) + + def wash_ellipse(box, color): + layer = pygame.Surface(image.get_size(), pygame.SRCALPHA) + pygame.draw.ellipse(layer, color, rect(*box)) + image.blit(layer, (0, 0)) + + def wash_arc(box, color, start, stop, width): + layer = pygame.Surface(image.get_size(), pygame.SRCALPHA) + pygame.draw.arc(layer, color, rect(*box), start, stop, width * q) + image.blit(layer, (0, 0)) + + canvas = locals() + + _draw_paper_body(canvas) + canvas["style"] = _draw_paper_hair_silhouette(canvas) + _draw_paper_face(canvas) + _draw_paper_gesture(canvas) + return _finish_paper_pilot(canvas) + + def draw_pilot(view: str, raw_look: dict) -> pygame.Surface: """Renderiza piloto em papel, com acabamento supersampled determinístico.""" look = normalize_pilot(raw_look) diff --git a/dobramundo/engine/pilot.py b/dobramundo/engine/pilot.py index cfdddc6..9b2b505 100644 --- a/dobramundo/engine/pilot.py +++ b/dobramundo/engine/pilot.py @@ -18,7 +18,6 @@ from .paper_pilot import draw_pilot FOLDER = "pilot_layers" -INK = (29, 36, 51) MIN_PILOT_SHARE = 0.32 # leitura do piloto acima da escala do avião durante o voo EXPRESSIONS = {"curious", "focused", "happy", "recover"} @@ -50,9 +49,9 @@ def _expression_layer(size: Tuple[int, int], look: dict, pose: str, expression: skin = (*skin_rgb, 190) def line(points, color, thickness): - pygame.draw.lines(layer, color, False, - [(round(x * q), round(y * q)) for x, y in points], - max(1, round(thickness * q))) + pygame.draw.lines( + layer, color, False, [(round(x * q), round(y * q)) for x, y in points], max(1, round(thickness * q)) + ) def arc(rect, start, stop, color, thickness): scaled = pygame.Rect(*(round(v * q) for v in rect)) @@ -64,64 +63,79 @@ def arc(rect, start, stop, color, thickness): if expression == "focused": for side, (cx, _) in enumerate(centers): direction = 1 if side == 0 else -1 - line([(cx - brow_dx, brow_y - height * 0.006), - (cx + brow_dx, brow_y + height * 0.008 * direction)], ink, max(2, height * 0.006)) + line( + [(cx - brow_dx, brow_y - height * 0.006), (cx + brow_dx, brow_y + height * 0.008 * direction)], + ink, + max(2, height * 0.006), + ) elif expression == "curious": for cx, _ in centers: - arc((cx - brow_dx, brow_y - height * 0.018, 2 * brow_dx, height * 0.035), 0.25, 2.9, ink, - max(2, height * 0.006)) + arc( + (cx - brow_dx, brow_y - height * 0.018, 2 * brow_dx, height * 0.035), + 0.25, + 2.9, + ink, + max(2, height * 0.006), + ) elif expression == "recover": for side, (cx, _) in enumerate(centers): direction = -1 if side == 0 else 1 - line([(cx - brow_dx, brow_y + height * 0.006 * direction), - (cx + brow_dx, brow_y - height * 0.014)], ink, max(2, height * 0.006)) + line( + [(cx - brow_dx, brow_y + height * 0.006 * direction), (cx + brow_dx, brow_y - height * 0.014)], + ink, + max(2, height * 0.006), + ) # Blend a small skin wash over the base smile before drawing the new mouth. wash = pygame.Surface((width * q, height * q), pygame.SRCALPHA) - pygame.draw.ellipse(wash, skin, pygame.Rect( - (mouth_x - round(body_width * 0.065)) * q, - (mouth_y - round(height * 0.018)) * q, - max(2, round(body_width * 0.13) * q), - max(2, round(height * 0.058) * q), - )) + pygame.draw.ellipse( + wash, + skin, + pygame.Rect( + (mouth_x - round(body_width * 0.065)) * q, + (mouth_y - round(height * 0.018)) * q, + max(2, round(body_width * 0.13) * q), + max(2, round(height * 0.058) * q), + ), + ) layer.blit(wash, (0, 0)) if expression == "curious": - pygame.draw.ellipse(layer, ink, pygame.Rect( - (mouth_x - round(height * 0.012)) * q, - (mouth_y - round(height * 0.014)) * q, - max(3, round(height * 0.024) * q), max(3, round(height * 0.034) * q), - ), max(1, round(height * 0.004) * q)) + pygame.draw.ellipse( + layer, + ink, + pygame.Rect( + (mouth_x - round(height * 0.012)) * q, + (mouth_y - round(height * 0.014)) * q, + max(3, round(height * 0.024) * q), + max(3, round(height * 0.034) * q), + ), + max(1, round(height * 0.004) * q), + ) elif expression == "focused": - line([(mouth_x - body_width * 0.045, mouth_y), (mouth_x + body_width * 0.045, mouth_y)], ink, - max(2, height * 0.006)) + line( + [(mouth_x - body_width * 0.045, mouth_y), (mouth_x + body_width * 0.045, mouth_y)], + ink, + max(2, height * 0.006), + ) elif expression == "recover": - arc((mouth_x - body_width * 0.045, mouth_y - height * 0.002, - body_width * 0.09, height * 0.026), 3.3, 6.1, ink, max(2, height * 0.006)) + arc( + (mouth_x - body_width * 0.045, mouth_y - height * 0.002, body_width * 0.09, height * 0.026), + 3.3, + 6.1, + ink, + max(2, height * 0.006), + ) else: # happy: a broad, visibly upturned smile - arc((mouth_x - body_width * 0.058, mouth_y - height * 0.026, - body_width * 0.116, height * 0.056), 3.45, 5.95, (153, 68, 75, 240), max(2, height * 0.008)) + arc( + (mouth_x - body_width * 0.058, mouth_y - height * 0.026, body_width * 0.116, height * 0.056), + 3.45, + 5.95, + (153, 68, 75, 240), + max(2, height * 0.008), + ) return pygame.transform.smoothscale(layer, size) -def tinted(layer: pygame.Surface, color) -> pygame.Surface: - out = layer.copy() - out.fill((*color, 255), special_flags=pygame.BLEND_RGBA_MULT) - return out - - -def ink_outline(surface: pygame.Surface, color=INK, thickness: int = 2) -> pygame.Surface: - """Traço de tinta em volta do piloto (mesma linguagem dos sprites "papel e aquarela").""" - mask = pygame.mask.from_surface(surface, 40) - line = mask.to_surface(setcolor=(*color, 255), unsetcolor=(0, 0, 0, 0)) - out = pygame.Surface((surface.get_width() + 2 * thickness, surface.get_height() + 2 * thickness), pygame.SRCALPHA) - for dx in range(-thickness, thickness + 1): - for dy in range(-thickness, thickness + 1): - if dx * dx + dy * dy <= thickness * thickness + 1: - out.blit(line, (thickness + dx, thickness + dy)) - out.blit(surface, (thickness, thickness)) - return out - - class PilotRenderer: def __init__(self, assets: Assets) -> None: self.assets = assets @@ -130,11 +144,9 @@ def __init__(self, assets: Assets) -> None: self.cache = BoundedCache(32) # piloto montado por vista e aparência self.expression_cache = BoundedCache(16) - def layer(self, view: str, name: str) -> Optional[pygame.Surface]: - return self.assets.folder(FOLDER).get(f"{view}__{name}") - - def compose(self, view: str, look: dict, pose: Optional[str] = None, - expression: Optional[str] = None) -> Optional[pygame.Surface]: + def compose( + self, view: str, look: dict, pose: Optional[str] = None, expression: Optional[str] = None + ) -> Optional[pygame.Surface]: """Piloto 2D de papel, independente das antigas camadas low-poly.""" look = normalize_pilot(look) key = (view, pose, tuple(sorted(look.items()))) diff --git a/dobramundo/engine/plane_layer.py b/dobramundo/engine/plane_layer.py new file mode 100644 index 0000000..461ac08 --- /dev/null +++ b/dobramundo/engine/plane_layer.py @@ -0,0 +1,145 @@ +"""Avião, manobras e efeitos visuais; conserva o fallback vetorial.""" + +from __future__ import annotations + +import math +from typing import Tuple + +import pygame + +from .. import config as C +from ..content.items import POWERUP_COLORS +from ..content.planes import MANEUVER_STYLES +from ..util import clamp, lerp_color, rgb +from .contracts import FlightView, PlaneLook +from .sprites import project + +HC_PLANE = rgb("ffeb3b") + + +class PlaneLayer: + def draw_player(self, screen: pygame.Surface, run: FlightView, look: PlaneLook) -> None: + player = run.player + self.shadow( + screen, + player.x, + C.PLAYER_Z, + C.PLANE_WIDTH * (1.1 - player.y / 800), + int(clamp(150 - player.y * 0.5, 40, 150)), + ) + blink = not self.reduce_motion and not self.high_contrast + if blink and run.invulnerable_timer > 0 and int(self.elapsed * 14) % 2: + return # pisca depois de uma colisão + bob = 0 if self.reduce_motion else math.sin(self.elapsed * 3.0) * 3.0 + sx, sy, scale = project(player.x, player.y + bob, C.PLAYER_Z, self.cam) + width = max(8, int(C.PLANE_WIDTH * scale)) + sprite = self.skin.surface(look.plane, "flight", look.color, look.pattern, look.pilot) + look_key = self.skin.look_key(look.plane, look.color, look.pattern, look.pilot) + if sprite is not None and self.high_contrast: + sprite = self.cache.outlined_source(sprite, ("plane", look_key), HC_PLANE) + look_key += "#hc" + pose = player.maneuver_pose() + if sprite is None: + self.player_rect = pygame.Rect(0, 0, width, max(24, round(width * 0.6))) + self.player_rect.center = round(sx), round(sy) + self.draw_paper_fallback(screen, int(sx), int(sy), width, player.roll + (pose[0] if pose else 0.0)) + return + aspect = sprite.get_height() / max(1, sprite.get_width()) + height = max(4, int(width * aspect)) + max_h = int(120 * scale) # piloto alto não cobre a tela + if height > max_h: + height = max_h + width = max(8, int(height / aspect)) + if pose is not None: + m_roll, m_pitch, m_dx, m_dy, m_dz = pose + style = MANEUVER_STYLES[player.maneuver] + sx += m_dx * style.sway * width + sy = max(C.MANEUVER_TOP_MARGIN, sy - m_dy * style.lift * width) + depth = 1.0 / max(0.4, 1.0 + style.depth * m_dz) + vertical = math.cos(math.radians(m_pitch)) + thickness = round(max(C.MANEUVER_MIN_THICKNESS, abs(vertical)) * 25) / 25 + # tamanho e ângulo em degraus: a manobra se repete e reaproveita as imagens prontas + size = (max(8, int(width * depth)) // 4 * 4, max(4, int(height * depth * thickness)) // 4 * 4) + angle = round((player.roll + m_roll) / 4.0) * 4.0 + key = ("manobra", look_key, size, angle, vertical < 0) + image = self.rotations.get(key) + if image is None: + img = self.cache.get(sprite, ("plane", look_key), size) + if vertical < 0: # de cabeça para baixo (topo do looping) + img = pygame.transform.flip(img, False, True) + image = self.remember_rotation(key, pygame.transform.rotozoom(img, angle, 1.0)) + width = size[0] + else: + # papel tremulando no ar e nariz que sobe ou desce com a velocidade vertical + # (em degraus, para reaproveitar as imagens giradas prontas) + flutter = 0 if self.reduce_motion else C.PAPER_FLUTTER_DEG * math.sin(self.elapsed * 7.0) + if not self.reduce_motion and self.celebration > 0: + flutter += 5 * math.sin(self.celebration * math.tau) * min(1.0, self.celebration) + pitch = clamp(player.vy / C.MAX_VERTICAL_SPEED, -1.0, 1.0) + height = max(4, int(height * (1.0 + round(pitch * C.PITCH_STRETCH * 25) / 25))) + base = self.cache.get(sprite, ("plane", look_key), (width, height)) + angle = round((player.roll + flutter) / 2.0) * 2.0 + key = (look_key, width, height, angle) + image = self.rotations.get(key) + if image is None: + image = self.remember_rotation(key, pygame.transform.rotozoom(base, angle, 1.0)) + self.player_rect = image.get_rect(center=(int(sx), int(sy))) + screen.blit(image, self.player_rect) + if run.shield_timer > 0: + pulse = 0.5 + 0.5 * math.sin(self.elapsed * 8.0) + pygame.draw.ellipse( + screen, + lerp_color(rgb("40c4ff"), (255, 255, 255), pulse * 0.4), + pygame.Rect(int(sx - width * 0.62), int(sy - width * 0.36), int(width * 1.24), int(width * 0.72)), + max(2, int(3 * scale)), + ) + if run.magnet_timer > 0: + pygame.draw.circle( + screen, + POWERUP_COLORS["magnet"], + (int(sx), int(sy)), + int(width * (0.7 + 0.05 * math.sin(self.elapsed * 10))), + 1, + ) + if self.show_hitboxes: + pygame.draw.rect(screen, rgb("40c4ff"), self.hitbox_rect(player.hitbox()), 2) + + @staticmethod + def splash(screen: pygame.Surface, center, color, progress: float, scale: float) -> None: + """Gotas que se abrem e somem (progress 0 -> 1), com um pingo claro no meio.""" + cx, cy = int(center[0]), int(center[1]) + pale = lerp_color(color, (255, 255, 255), 0.35) + for k in range(7): + angle = k * 0.9 + 0.3 + reach = (14 + 70 * progress) * scale + r = max(1, int((7 - 5 * progress) * scale)) + px, py = int(cx + math.cos(angle) * reach), int(cy + math.sin(angle) * reach * 0.7) + pygame.draw.circle(screen, color, (px, py), r) + core = max(1, int((22 - 20 * progress) * scale)) + pygame.draw.circle(screen, pale, (cx, cy), core) + if progress < 0.6: + pygame.draw.circle(screen, (255, 255, 255), (cx - core // 3, cy - core // 3), max(1, core // 3)) + + def remember_rotation(self, key: tuple, image: pygame.Surface) -> pygame.Surface: + """Guarda uma rotação do avião (descarte gradual, como o cache de sprites).""" + return self.rotations.put(key, image) + + @staticmethod + def draw_paper_fallback(screen: pygame.Surface, cx: int, cy: int, width: int, roll: float) -> None: + """Avião de papel desenhado por código (se os sprites faltarem).""" + h = width * 0.28 + angle = math.radians(roll) + + def rot(px: float, py: float) -> Tuple[int, int]: + return ( + int(cx + px * math.cos(angle) - py * math.sin(angle)), + int(cy + px * math.sin(angle) + py * math.cos(angle)), + ) + + left = [rot(0, -h * 0.35), rot(-width / 2, h * 0.25), rot(0, h * 0.1)] + right = [rot(0, -h * 0.35), rot(width / 2, h * 0.25), rot(0, h * 0.1)] + keel = [rot(0, -h * 0.35), rot(-width * 0.05, h * 0.6), rot(width * 0.05, h * 0.6)] + pygame.draw.polygon(screen, (232, 232, 226), left) + pygame.draw.polygon(screen, (250, 250, 246), right) + pygame.draw.polygon(screen, (180, 186, 190), keel) + pygame.draw.lines(screen, rgb("78909c"), True, left + right[1:], 1) diff --git a/dobramundo/engine/plane_skin.py b/dobramundo/engine/plane_skin.py index 0dcab7a..470575f 100644 --- a/dobramundo/engine/plane_skin.py +++ b/dobramundo/engine/plane_skin.py @@ -36,8 +36,8 @@ def __init__(self, assets: Assets) -> None: self.patterns[key] = surface if surface.get_size() == size else pygame.transform.smoothscale(surface, size) self.palettes = BoundedCache(C.PATTERN_CACHE_LIMIT) # ~2,7 MB cada self.uv_indices = BoundedCache(8) - self.cache = BoundedCache(48) # avião pintado com piloto - self.thumbs: Dict[tuple, pygame.Surface] = {} + self.cache = BoundedCache(48, 40 * 1024 * 1024) + self.thumbs: BoundedCache = BoundedCache(32, 4 * 1024 * 1024) def base(self, plane: str, view: str) -> Optional[pygame.Surface]: watercolor = self.painted_planes.base(plane, view) diff --git a/dobramundo/engine/regional_life.py b/dobramundo/engine/regional_life.py index 12c9ffb..ab31f39 100644 --- a/dobramundo/engine/regional_life.py +++ b/dobramundo/engine/regional_life.py @@ -27,6 +27,7 @@ def __init__(self, assets): cell = atlas.subsurface((col * w // 3, row * h // 2, w // 3, h // 2)) bounds = cell.get_bounding_rect(min_alpha=40) self.frames.append(display_format(cell.subsurface(bounds).copy(), True) if bounds.w else None) + assets.release_folder("watercolor", ("fauna_sprint3",)) @staticmethod def quiet_share(world): @@ -71,6 +72,9 @@ def encounter(self, world, reduced): opacity = smoothstep(clamp((1500 - z) / 220, 0.0, 1.0)) opacity *= smoothstep(clamp((z - 260) / 160, 0.0, 1.0)) opacity *= smoothstep(clamp((world.visual - 25) / 10, 0.0, 1.0)) + theme = world.challenge_theme + if theme is not None and "fauna" in theme.decorations: + opacity = min(1.0, opacity * 1.15) return x, y, z, pair, mix, opacity * self._quiet, side def draw(self, screen, world, cam, reduced): diff --git a/dobramundo/engine/sky.py b/dobramundo/engine/sky.py index 06a46cb..6750f88 100644 --- a/dobramundo/engine/sky.py +++ b/dobramundo/engine/sky.py @@ -116,8 +116,8 @@ def __init__(self, assets: Assets) -> None: self.panorama = self.panorama_base self.clouds = self.prepare_clouds(atmosphere.get("smog_cloud")) self.skyline_sprites = assets.folder("skyline_sprites") - self.gradients = BoundedCache(24) - self.decor_cache = BoundedCache(64) + self.gradients = BoundedCache(24, 20 * 1024 * 1024) + self.decor_cache = BoundedCache(64, 20 * 1024 * 1024) self.biome: Optional[Biome] = None self.pollution = 1.0 self.fog_color: Color = (92, 54, 26) @@ -127,18 +127,32 @@ def __init__(self, assets: Assets) -> None: self.birds_x = 300.0 self.skyline_cache: Dict[str, Optional[pygame.Surface]] = {} self.skyline_state: Dict[str, dict] = {} + self.decor_sprites: Dict[str, pygame.Surface] = {} def set_biome(self, biome: Biome) -> None: if self.biome is biome: return self.biome = biome self.panorama = self.tint_panorama(biome) + decor_names = {decor.sprite for decor in biome.sky_decor} + decor_names.add(biome.horizon_vehicle[0]) + self.decor_sprites = self.assets.scenery_for(decor_names) self.skyline_cache = {} self.skyline_state = {} - self.decor_cache = BoundedCache(64) + self.decor_cache = BoundedCache(64, 20 * 1024 * 1024) count = max(1, len(biome.sky_decor)) self.decor_x = [i * C.DECOR_CYCLE / count + 120 * i for i in range(len(biome.sky_decor))] + def release_biome_cache(self) -> None: + """Solta faixas e variações específicas de uma fase já encerrada.""" + self.biome = None + self.panorama = self.panorama_base + self.skyline_cache.clear() + self.skyline_state.clear() + self.decor_cache.clear() + self.decor_sprites = {} + self.decor_x = [] + # ------------------------------------------------------------ preparo def tint_panorama(self, biome: Biome) -> Optional[pygame.Surface]: """O panorama de fumaça do kit é alaranjado; aqui ele vira cinza e recebe a cor do bioma @@ -193,7 +207,7 @@ def prepare_clouds(smog: Optional[pygame.Surface]) -> List[dict]: "opacity": opacity, "smoke": smoke, "clean": clean, - "baked": {}, + "baked": BoundedCache(24, 2 * 1024 * 1024), } ) return clouds @@ -230,6 +244,7 @@ def draw( distance: float, solar_share: float, elapsed: float, + challenge_theme=None, ) -> None: screen.blit(self.gradient(top, horizon), (0, 0)) self.draw_sun(screen, cam_x, horizon) @@ -237,7 +252,7 @@ def draw( self.draw_clouds(screen, cam_x, distance) self.draw_skyline(screen, horizon, cam_x, distance, solar_share) self.draw_sky_decor(screen, cam_x, solar_share, elapsed) - self.draw_horizon_vehicle(screen, cam_x, solar_share) + self.draw_horizon_vehicle(screen, cam_x, solar_share, challenge_theme) def draw_sun(self, screen: pygame.Surface, cam_x: float, horizon: Color) -> None: """Sol de papel: pálido atrás da fumaça, amarelo e com halo quando o céu limpa.""" @@ -314,10 +329,11 @@ def build_skyline(layout: List[Tuple[str, int]], sprites: dict) -> Optional[pyga def skyline_base(self, name: str) -> Optional[pygame.Surface]: if name not in self.skyline_cache: biome = self.biome + layout: List[Tuple[str, int]] if name == "green" and biome is not None: - strip = self.build_skyline(biome.green_skyline, self.assets.scenery) + layout = biome.green_skyline elif name == "city" and biome is not None: - strip = self.build_skyline(biome.solar_skyline, self.assets.scenery) + layout = biome.solar_skyline elif name == "back": layout: List[Tuple[str, int]] = [] regional = list(biome.industrial_skyline) if biome is not None else [] @@ -325,9 +341,11 @@ def skyline_base(self, name: str) -> Optional[pygame.Surface]: layout.append(item) if regional and i % 3 == 1: layout.append(regional[(i // 3) % len(regional)]) - strip = self.build_skyline(layout, {**self.skyline_sprites, **self.assets.scenery}) else: - strip = self.build_skyline(SKYLINE_FRONT, self.skyline_sprites) + layout = SKYLINE_FRONT + names = {sprite for sprite, _ in layout} + scene_sprites = self.assets.scenery_for(names) if name != "front" else {} + strip = self.build_skyline(layout, {**self.skyline_sprites, **scene_sprites}) self.skyline_cache[name] = strip return self.skyline_cache[name] @@ -454,7 +472,7 @@ def update_decor(self, dt: float) -> None: self.birds_x = (self.birds_x + 32.0 * dt) % C.DECOR_CYCLE def decor_sprite(self, name: str, height: int, alpha: int, haze: float = 0.0) -> Optional[pygame.Surface]: - sprite = self.assets.scenery.get(name) + sprite = self.decor_sprites.get(name) if sprite is None or height < 2: return None fog = tuple(c // 16 * 16 for c in self.fog_color) @@ -490,11 +508,17 @@ def draw_sky_decor(self, screen: pygame.Surface, cam_x: float, amount: float, el flap = math.sin(elapsed * 9.0 + k * 1.7) * 3.0 pygame.draw.lines(screen, color, False, [(px - 5, py - 2 - flap), (px, py), (px + 5, py - 2 - flap)], 2) - def draw_horizon_vehicle(self, screen: pygame.Surface, cam_x: float, amount: float) -> None: + def draw_horizon_vehicle(self, screen: pygame.Surface, cam_x: float, amount: float, challenge_theme=None) -> None: """Na linha do horizonte, à frente das silhuetas: barco (Manaus) ou bonde (Petrolina).""" if amount <= 0.0 or self.biome is None: return name, height, _, parallax = self.biome.horizon_vehicle + if challenge_theme is not None: + tags = challenge_theme.decorations + if name.startswith("AM_") and "boat" in tags: + amount = min(1.0, amount * 1.15) + elif name == "EF_BondeVLT" and "tram" in tags: + amount = min(1.0, amount * 1.15) surf = self.decor_sprite(name, height, int(255 * amount), haze=0.35) if surf is None: return diff --git a/dobramundo/engine/sprites.py b/dobramundo/engine/sprites.py index 109d965..f91d55b 100644 --- a/dobramundo/engine/sprites.py +++ b/dobramundo/engine/sprites.py @@ -18,6 +18,9 @@ Size = Tuple[int, int] MIP_CACHE_LIMIT = 600 # ~120 sprites de cenário x 2 lados + aparências do avião OUTLINE_CACHE_LIMIT = 200 +SCALED_CACHE_BYTES = 28 * 1024 * 1024 +MIP_CACHE_BYTES = 72 * 1024 * 1024 +OUTLINE_CACHE_BYTES = 20 * 1024 * 1024 def project(x: float, y: float, z: float, cam: float) -> Tuple[float, float, float]: @@ -58,9 +61,9 @@ def outline_surface(sprite: pygame.Surface, color: Color, thickness: int) -> pyg class SpriteCache: def __init__(self) -> None: - self.scaled = BoundedCache(C.SPRITE_CACHE_LIMIT) # reescalas, neblina e miniaturas - self.mips = BoundedCache(MIP_CACHE_LIMIT) # versões pré-reduzidas por sprite - self.outlines = BoundedCache(OUTLINE_CACHE_LIMIT) # alto contraste, em resolução cheia + self.scaled = BoundedCache(C.SPRITE_CACHE_LIMIT, SCALED_CACHE_BYTES) + self.mips = BoundedCache(MIP_CACHE_LIMIT, MIP_CACHE_BYTES) + self.outlines = BoundedCache(OUTLINE_CACHE_LIMIT, OUTLINE_CACHE_BYTES) self.fog_color: Color = (92, 54, 26) def put(self, key: tuple, value: pygame.Surface) -> None: diff --git a/dobramundo/engine/track_layer.py b/dobramundo/engine/track_layer.py new file mode 100644 index 0000000..d342980 --- /dev/null +++ b/dobramundo/engine/track_layer.py @@ -0,0 +1,284 @@ +"""Pista e margens do renderizador de reserva; sem regras de partida.""" + +from __future__ import annotations + +from typing import NamedTuple + +import pygame + +from .. import config as C +from ..content.biomes import Specs +from ..util import Color, clamp, haze_at, lerp_color, rgb, smoothstep +from .contracts import WorldStateView +from .sprites import project + +RIVER_NEGRO = rgb("2a1a10") # águas escuras do Rio Negro +RIVER_ENCOUNTER = rgb("b08452") +RIVER_CURB = rgb("e0c27a") # orla do rio limpo +ROAD_CURB = rgb("c9a04a") # meio-fio dourado do piso drenante +PURIFIED_ROAD = rgb("8bcf78") # Solimões (barrento) ao lado do Rio Negro, no despertar + + +class TrackPalette(NamedTuple): + even: Color + odd: Color + right_even: Color # metade direita do rio (Solimões) no encontro das águas + right_odd: Color + purified: Color + lane: Color + ground: Color + encounter: float # 0..1: quanto do encontro das águas aparece + wave_z: float # até onde a pista já foi purificada + + +class TrackLayer: + def piece( + self, screen: pygame.Surface, specs: Specs, seq: int, side: int, x: float, z: float, cam: float, grow: float + ) -> None: + """Peça das margens na ordem fixa da lista; grow < 1 = afundando ou crescendo.""" + if z < C.NEAR_CLIP_Z or grow < 0.04 or not specs: + return + offset = len(specs) // 2 if side > 0 else 0 + for step in range(len(specs)): + name, height = specs[(seq + offset + step) % len(specs)] + sprite = self.scenery.get(name) + if sprite is not None: + # Os sprites mostram o lado direito (vista 3/4): à direita da pista, espelhados. + self.blit_world(screen, sprite, ("scenery", name), side * x, 0, z, height * grow, side > 0, cam) + return + + @staticmethod + def theme_specs(world: WorldStateView, specs: Specs, stage: str) -> Specs: + """Bias existing regional scenery by published theme; stages stay authoritative.""" + theme = world.challenge_theme + if theme is None: + return specs + tags = set(theme.decorations) + names = [name.lower() for name, _ in specs] + selected = [] + if stage == "green" and "fruit_trees" in tags: + orchard = ("mangueira", "videira", "juazeiro") + selected = [item for item in specs if any(token in item[0].lower() for token in orchard)] + # Add existing orchard trees from the final-era list only; no solar + # equipment is introduced before the final stage. + if world.biome.key == "caatinga": + selected.extend( + item + for item in world.biome.solar_mid + if any(token in item[0].lower() for token in orchard) and item[0].lower() not in names + ) + elif stage == "industrial" and "boat" in tags: + tokens = ("porto", "balsa", "container") + selected = [item for item in specs if any(token in item[0].lower() for token in tokens)] + elif stage == "green" and "boat" in tags: + selected = [item for item in specs if any(token in item[0].lower() for token in ("palafita", "flutuante"))] + elif stage == "green" and "trees" in tags: + tree_tokens = ( + "arvore", + "samauma", + "acaizeiro", + "buriti", + "seringueira", + "juazeiro", + "mandacaru", + "carnauba", + "umbuzeiro", + ) + selected = [item for item in specs if any(token in item[0].lower() for token in tree_tokens)] + elif stage == "solar": + tokens = [] + if "solar" in tags: + tokens.extend(("solar", "usina")) + if "wind" in tags: + tokens.extend(("eolica", "aerogerador")) + if "boat" in tags: + tokens.append("barco") + if "trees" in tags: + tokens.extend( + ( + "samauma", + "acaizeiro", + "buriti", + "seringueira", + "juazeiro", + "mandacaru", + "carnauba", + "umbuzeiro", + ) + ) + if tokens: + selected = [item for item in specs if any(token in item[0].lower() for token in tokens)] + return list(specs) + selected if selected else specs + + def margins(self, screen: pygame.Surface, world: WorldStateView, seg: int, z: float) -> None: + """Duas fileiras por lado em cada trecho: fundo (z) e borda (z + 50).""" + self.ensure_scenery() + biome = self.biome + mid_cam = self.cam * C.MID_PARALLAX + margin_cam = self.cam * C.MARGIN_PARALLAX + border_z = z + 50.0 + green = world.segment_green(seg) + solar = world.segment_solar(seg) + keep = 1.0 - solar # a peça do estágio anterior afunda enquanto a nova cresce + industrial_mid = self.theme_specs(world, biome.industrial_mid, "industrial") + industrial_margin = self.theme_specs(world, biome.industrial_margin, "industrial") + green_mid = self.theme_specs(world, biome.green_mid, "green") + green_margin = self.theme_specs(world, biome.green_margin, "green") + solar_mid = self.theme_specs(world, biome.solar_mid, "solar") + solar_margin = self.theme_specs(world, biome.solar_margin, "solar") + for side in (-1, 1): + # quarteirões: a cada 6 trechos, 2 ficam vazios (num lado de cada vez), para o + # cenário ter blocos e respiros em vez de uma fila contínua de peças soltas + if (seg + (3 if side > 0 else 0)) % 6 in (4, 5): + continue + if green < 1.0 and keep > 0.0: + self.piece(screen, industrial_mid, seg, side, C.MID_ROW_X, z, mid_cam, (1.0 - green) * keep) + if green > 0.0 and keep > 0.0: + restored = seg % C.RESTORED_EVERY == C.RESTORED_REMAINDER + specs = biome.restored if restored else green_mid + index = seg // C.RESTORED_EVERY + (side > 0) if restored else seg + self.piece(screen, specs, index, side, C.MID_ROW_X, z, mid_cam, green * keep) + if solar > 0.0: + marco = seg % C.LANDMARK_EVERY == 4 and (seg // C.LANDMARK_EVERY + (side > 0)) % 2 == 0 + specs = [biome.landmark] if marco else solar_mid + self.piece(screen, specs, seg, side, C.MID_ROW_X, z, mid_cam, solar) + if border_z > C.MARGIN_MAX_Z or (seg + (side > 0)) % 2 or (seg // 2) % 4 == 3: + continue # a borda alterna de lado a cada trecho, tem vãos e some ao longe + if green < 1.0 and keep > 0.0: + self.piece( + screen, + industrial_margin, + seg // 2, + side, + C.MARGIN_X, + border_z, + margin_cam, + (1.0 - green) * keep, + ) + if green > 0.0 and keep > 0.0: + self.piece(screen, green_margin, seg // 2 + 3, side, C.MARGIN_X, border_z, margin_cam, green * keep) + if solar > 0.0: + self.piece( + screen, + solar_margin, + seg // 2 + (3 if side > 0 else 0), + side, + C.MARGIN_X, + border_z, + margin_cam, + solar, + ) + + def track_palette(self, world: WorldStateView) -> TrackPalette: + """Cores da pista no quadro (mistura dos estágios), calculadas uma vez.""" + a, b, t = world.visual_stage_pair() + river = self.biome.river + weight = self.encounter_weight(world) if river else 0.0 + if world.challenge_theme is not None and "river" in world.challenge_theme.decorations: + weight = min(1.0, weight * 1.15) + even = lerp_color(a.road_even, b.road_even, t) + odd = lerp_color(a.road_odd, b.road_odd, t) + return TrackPalette( + even=even, + odd=odd, + right_even=lerp_color(even, RIVER_ENCOUNTER, weight), + right_odd=lerp_color(odd, RIVER_ENCOUNTER, weight * 0.95), + purified=lerp_color(even, PURIFIED_ROAD, 0.2), + lane=lerp_color(a.lane_line, b.lane_line, t), + ground=lerp_color(a.ground, b.ground, t), + encounter=weight, + wave_z=180.0 + (world.visual / 100.0) ** 1.15 * 2150.0, # frente da pista purificada + ) + + def draw_track(self, screen: pygame.Surface, world: WorldStateView, flags) -> None: + """Pista (ou rio) trecho a trecho, do horizonte para o avião, com as margens.""" + pal = self.track_palette(world) + fog = self.sky.fog_color + biome = self.biome + cam = self.cam + half = C.ROAD_WIDTH / 2 + stretches = [] + for i in range(len(world.segments) - 1, -1, -1): + z = world.segments[i] + seg = world.segment_base + i + edges = ( + project(-half, 0, z, cam), + project(half, 0, z, cam), + project(-half, 0, z + C.SEGMENT_LENGTH, cam), + project(half, 0, z + C.SEGMENT_LENGTH, cam), + ) + haze = haze_at(z + 50.0) + if not self.ground.textures: # sem texturas: chão liso por trecho + ground = C.GRASS_FALLBACK[seg % 2] if world.segment_green(seg) > 0.0 else pal.ground + left1, right1, left2, right2 = edges + pygame.draw.polygon( + screen, + lerp_color(ground, fog, haze), + [(0, left2[1]), (C.WIDTH, right2[1]), (C.WIDTH, right1[1]), (0, left1[1])], + ) + stretches.append((i, seg, z, edges, haze)) + self.ground.draw( + screen, world, flags, cam, fog, ("concrete", biome.green_ground, biome.solar_ground), biome.solar_road + ) + solar_road = self.ground.has(biome.solar_road) + solar_flags = flags[1] + for i, seg, z, edges, haze in stretches: + solar = bool(solar_flags) and solar_flags[i] + self.draw_road(screen, pal, seg, z, edges, haze, solar and solar_road) + if biome.river and solar: + self.curbs(screen, edges, lerp_color(RIVER_CURB, fog, haze), 5) # orla dourada do rio limpo + self.draw_lanes(screen, pal, seg, z, haze) + self.margins(screen, world, seg, z) + + def draw_road( + self, screen: pygame.Surface, pal: TrackPalette, seg: int, z: float, edges, haze: float, paved: bool + ) -> None: + """Superfície de um trecho: piso drenante (só o meio-fio), rio com encontro das águas ou pista.""" + fog = self.sky.fog_color + left1, right1, left2, right2 = edges + if paved: # a textura do piso já foi desenhada pelo chão + self.curbs(screen, edges, lerp_color(ROAD_CURB, fog, haze), 6) + return + even = seg % 2 == 0 + river = self.biome.river + purify = smoothstep((pal.wave_z - z) / C.ROAD_PURIFY_BAND) if not river else 0.0 + base = lerp_color(pal.even if even else pal.odd, pal.purified, purify) + if river: # encontro das águas: o Negro fica escuro à esquerda + base = lerp_color(base, RIVER_NEGRO, pal.encounter * (0.9 if even else 1.0)) + color = lerp_color(base, fog, haze) + if river and pal.encounter > 0.01: + mid1, mid2 = project(0, 0, z, self.cam), project(0, 0, z + C.SEGMENT_LENGTH, self.cam) + right = lerp_color(pal.right_even if even else pal.right_odd, fog, haze) + pygame.draw.polygon(screen, color, [left1[:2], mid1[:2], mid2[:2], left2[:2]]) + pygame.draw.polygon(screen, right, [mid1[:2], right1[:2], right2[:2], mid2[:2]]) + else: + pygame.draw.polygon(screen, color, [left1[:2], right1[:2], right2[:2], left2[:2]]) + + def draw_lanes(self, screen: pygame.Surface, pal: TrackPalette, seg: int, z: float, haze: float) -> None: + """Divisórias das faixas; no rio, reflexos curtos que andam (água corrente).""" + lane = lerp_color(pal.lane, self.sky.fog_color, haze) + if self.biome.river: + if (seg + int(self.elapsed * 3)) % 3: + return + z0, z1, thickness = z + 20, z + 60, 3 + else: + z0, z1, thickness = z, z + C.SEGMENT_LENGTH, 4 + for divider in (-0.5, 0.5): + p1 = project(C.LANE_WIDTH * divider, 0, z0, self.cam) + p2 = project(C.LANE_WIDTH * divider, 0, z1, self.cam) + pygame.draw.line(screen, lane, p1[:2], p2[:2], max(1, int(thickness * p1[2]))) + + @staticmethod + def curbs(screen: pygame.Surface, edges, color, thickness: int) -> None: + left1, right1, left2, right2 = edges + width = max(1, int(thickness * left1[2])) + pygame.draw.line(screen, color, left1[:2], left2[:2], width) + pygame.draw.line(screen, color, right1[:2], right2[:2], width) + + @staticmethod + def encounter_weight(world: WorldStateView) -> float: + """Quanto do encontro das águas aparece: só no estágio do despertar (meio da fase).""" + value = world.visual + rise = clamp((value - C.ERA_SPAN * 0.8) / (C.ERA_SPAN * 0.4), 0.0, 1.0) + fall = clamp((value - C.ERA_SPAN * 1.8) / (C.ERA_SPAN * 0.5), 0.0, 1.0) + return rise * (1.0 - fall) diff --git a/dobramundo/engine/watercolor.py b/dobramundo/engine/watercolor.py index d498f41..a3a06a7 100644 --- a/dobramundo/engine/watercolor.py +++ b/dobramundo/engine/watercolor.py @@ -29,14 +29,33 @@ def __init__(self, assets: Assets) -> None: def load(self, biome: str) -> tuple: if biome not in self.backdrops: - images = self.assets.folder("watercolor", tuple(f"{biome}_{stage}" for stage in range(3))) - layers = [images.get(f"{biome}_{stage}") for stage in range(3)] - self.backdrops[biome] = ( - tuple(display_format(pygame.transform.smoothscale(image, (C.WIDTH + 32, C.HEIGHT))) - for image in layers) if all(image is not None for image in layers) else () - ) + names = tuple(f"{biome}_{stage}" for stage in range(3)) + prepared = self.assets.folder("watercolor_prepared", names) + layers = [prepared.get(name) for name in names] + if all(image is not None for image in layers): + result = tuple(display_format(image) for image in layers) + else: + original = self.assets.folder("watercolor", names) + layers = [original.get(name) for name in names] + result = ( + tuple( + display_format(pygame.transform.smoothscale(image, (C.WIDTH + 32, C.HEIGHT))) + for image in layers + ) + if all(image is not None for image in layers) + else () + ) + self.assets.release_folder("watercolor", names) + self.assets.release_folder("watercolor_prepared", names) + self.backdrops[biome] = result return self.backdrops[biome] + def release_biome(self, biome: str) -> None: + self.backdrops.pop(biome, None) + if self.composite_key is not None and self.composite_key[0] == biome: + self.composite_key = None + self.composite = None + @staticmethod def stage_mix(visual: float) -> tuple[int, int, int]: """Limiar real preservado: indústria < 1/3, despertar até 2/3, solar.""" diff --git a/dobramundo/engine/world_view.py b/dobramundo/engine/world_view.py index 8cfe61a..9625544 100644 --- a/dobramundo/engine/world_view.py +++ b/dobramundo/engine/world_view.py @@ -8,79 +8,34 @@ from __future__ import annotations -import math -from typing import Iterator, List, NamedTuple, Optional, Protocol, Tuple +from typing import Iterator, List, Optional, Tuple import pygame from .. import config as C -from ..content.biomes import Biome, Specs -from ..content.items import POWERUP_COLORS, WASTE_BY_KEY, ObstacleSpec -from ..content.planes import MANEUVER_STYLES -from ..game.entities import Beam, Entity, FloatingText, entity_hitbox -from ..game.player import Player -from ..game.world import World -from ..util import Color, clamp, haze_at, lerp_color, rgb, smoothstep +from ..content.biomes import Biome +from ..util import Color, clamp, lerp_color from .accessible_view import screen_point, viewport from .assets import Assets from .cache import BoundedCache +from .contracts import EntityView, FlightView, WorldStateView +from .contracts import PlaneLook as PlaneLook +from .entity_layer import EntityLayer from .ground import GroundRenderer from .paper_items import PaperItems +from .plane_layer import PlaneLayer from .plane_skin import PlaneSkin from .sky import SkyRenderer from .sprites import SpriteCache, fog_level, project +from .track_layer import TrackLayer from .watercolor import WatercolorWorld -RIVER_NEGRO = rgb("2a1a10") # águas escuras do Rio Negro -RIVER_ENCOUNTER = rgb("b08452") -RIVER_CURB = rgb("e0c27a") # orla do rio limpo -ROAD_CURB = rgb("c9a04a") # meio-fio dourado do piso drenante -PURIFIED_ROAD = rgb("8bcf78") # Solimões (barrento) ao lado do Rio Negro, no despertar -HC_PLANE = rgb("ffeb3b") -HC_OBSTACLE = rgb("ff3d00") -HC_DIM = (150, 150, 150) # escurecimento do fundo dessaturado -ROTATION_CACHE_LIMIT = 400 # rotações do avião guardadas +HC_DIM = (150, 150, 150) +ROTATION_CACHE_LIMIT = 400 -class FlightView(Protocol): - """O que o desenho lê de um voo (game.run.FlightRun cumpre isto); o motor não conhece as regras.""" - - world: World - player: Player - mode: str - invulnerable_timer: float - shield_timer: float - magnet_timer: float - beams: List[Beam] - floating: List[FloatingText] - - -class TrackPalette(NamedTuple): - even: Color - odd: Color - right_even: Color # metade direita do rio (Solimões) no encontro das águas - right_odd: Color - purified: Color - lane: Color - ground: Color - encounter: float # 0..1: quanto do encontro das águas aparece - wave_z: float # até onde a pista já foi purificada - - -class PlaneLook: - """O que o jogador escolheu para o avião (modelo, pintura, piloto).""" - - def __init__( - self, plane: str, color: str = "original", pattern: str = "jornal", pilot: Optional[dict] = None - ) -> None: - self.plane = plane - self.color = color - self.pattern = pattern - self.pilot = pilot - - -class WorldView: - def __init__(self, assets: Assets) -> None: +class WorldView(TrackLayer, EntityLayer, PlaneLayer): + def __init__(self, assets: Assets, font: Optional[pygame.font.Font] = None) -> None: self.assets = assets self.cache = SpriteCache() self.sky = SkyRenderer(assets) @@ -88,16 +43,18 @@ def __init__(self, assets: Assets) -> None: self.skin = PlaneSkin(assets) self.watercolor = WatercolorWorld(assets) self.paper_items = PaperItems() - self.scenery = assets.scenery + self.scenery = {} + self._scenery_loaded = False + self._biome_scenery_names = set() self.waste = assets.folder("waste_sprites") self.powerups = assets.folder("powerup_sprites") self.fx = assets.folder("era_final_fx") - self.shadows = BoundedCache(400) - self.rotations = BoundedCache(ROTATION_CACHE_LIMIT) - self.font = pygame.font.SysFont("segoeui,verdana,dejavusans", 20, bold=True) - self.text_cache = BoundedCache(64) + self.shadows = BoundedCache(400, 8 * 1024 * 1024) + self.rotations = BoundedCache(ROTATION_CACHE_LIMIT, 40 * 1024 * 1024) + self.font = font or pygame.font.SysFont("segoeui,verdana,dejavusans", 20, bold=True) + self.text_cache = BoundedCache(64, 4 * 1024 * 1024) self.biome: Optional[Biome] = None - self.world: Optional[World] = None + self.world: Optional[WorldStateView] = None self.cam = 0.0 self.elapsed = 0.0 self.mode = "normal" @@ -115,10 +72,148 @@ def __init__(self, assets: Assets) -> None: # ------------------------------------------------------------ preparo def set_biome(self, biome: Biome) -> None: if self.biome is not biome: + if self.biome is not None: + self.release_biome_cache(self.biome.key) self.biome = biome self.sky.set_biome(biome) + self._scenery_loaded = False + self.scenery = {} + self._biome_scenery_names = self.scenery_names(biome) self.warm_queue = self.warm_tasks() + @staticmethod + def scenery_names(biome: Biome) -> set: + names = set() + for specs in ( + biome.industrial_mid, + biome.industrial_margin, + biome.green_mid, + biome.green_margin, + biome.restored, + biome.solar_mid, + biome.solar_margin, + [biome.landmark], + ): + names.update(name for name, _ in specs) + for table in (biome.industrial_obstacles, biome.solar_obstacles): + for specs in table.values(): + names.update(spec.sprite for spec in specs) + return names + + def ensure_scenery(self) -> None: + if not self._scenery_loaded and self.biome is not None: + self.scenery = self.assets.scenery_for(self._biome_scenery_names) + self._scenery_loaded = True + + def release_biome_cache(self, biome_key: str) -> None: + """Solta superfícies temporárias do bioma após a cena deixar de usá-lo.""" + self.watercolor.release_biome(biome_key) + self.watercolor.route.release_biome(biome_key) + biome_names = set() + if self.biome is not None and self.biome.key == biome_key: + biome_names.update(self._biome_scenery_names) + biome_names.update(decor.sprite for decor in self.biome.sky_decor) + biome_names.add(self.biome.horizon_vehicle[0]) + if biome_names: + self.assets.release_scenery(biome_names) + if self.biome is not None and self.biome.key == biome_key: + self.scenery = {} + self._scenery_loaded = False + self._biome_scenery_names = set() + self.biome = None + self.world = None + self.warm_queue = None + self.sky.release_biome_cache() + self.cache = SpriteCache() + self.shadows.clear() + self.rotations.clear() + self.text_cache.clear() + + def cache_stats(self) -> dict: + """Unique surface-byte estimate for decoded assets and this renderer's owners.""" + seen = set() + owners = {} + + def measure(name, *values): + owners[name] = sum(BoundedCache.value_bytes(value, seen) for value in values) + + measure("assets", list(self.assets._loaded.values()), self.assets._scenery) + measure("scene_sprites", self.scenery, self.waste, self.powerups, self.fx) + measure("world_sprite_cache", self.cache.scaled, self.cache.mips, self.cache.outlines) + measure( + "world_transient", self.shadows, self.rotations, self.text_cache, self.gray_buffers, self.accessible_canvas + ) + measure( + "sky", + self.sky.panorama_base, + self.sky.panorama, + self.sky.clouds, + self.sky.skyline_cache, + self.sky.skyline_state, + self.sky.decor_sprites, + self.sky.gradients, + self.sky.decor_cache, + ) + measure("ground", self.ground.textures, self.ground.groups, self.ground.fog_cache) + route_ground = self.watercolor.route.ground + measure( + "watercolor", + self.watercolor.backdrops, + self.watercolor.composite, + self.watercolor.route.banks, + self.watercolor.route.cache.scaled, + self.watercolor.route.cache.mips, + self.watercolor.route.cache.outlines, + route_ground.textures if route_ground else None, + route_ground.source_rows if route_ground else None, + route_ground.line_buffers if route_ground else None, + self.watercolor.life.frames, + self.watercolor.life.cache.scaled, + self.watercolor.life.cache.mips, + self.watercolor.life.cache.outlines, + ) + pilots = self.skin.pilots + pilot_art = pilots.painted + planes = self.skin.painted_planes + measure( + "plane_skin", + self.skin.patterns, + self.skin.palettes, + self.skin.uv_indices, + self.skin.cache, + self.skin.thumbs, + planes._bases, + planes._paper_masks, + planes._patterns, + planes._cache, + pilots.cache, + pilots.expression_cache, + pilot_art.sprites, + pilot_art.hair_sprites, + pilot_art.mobility_sprites, + pilot_art.palette, + pilot_art.cache, + pilot_art.hair_cache, + pilot_art.mobility_cache, + ) + measure("paper_items", self.paper_items.canonical, self.paper_items._scaled, self.paper_items._shadows) + cache_items = { + "scaled": len(self.cache.scaled), + "mips": len(self.cache.mips), + "outlines": len(self.cache.outlines), + "rotations": len(self.rotations), + "ground_groups": len(self.ground.groups), + "asset_images": len(self.assets._loaded), + } + return { + "unique_retained_surface_bytes": sum(owners.values()), + "surface_bytes_by_owner": owners, + "cache_items": cache_items, + "estimate": ( + "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + ), + } + def warm_tasks(self) -> Iterator: """Preparo incremental (mip dos sprites e silhuetas) para a partida não engasgar.""" if self.biome and self.watercolor.load(self.biome.key) and self.watercolor.route.ready(self.biome.key): @@ -135,6 +230,7 @@ def warm_tasks(self) -> Iterator: biome = self.biome if biome is None: return + self.ensure_scenery() names = set() for specs in ( biome.industrial_mid, @@ -244,439 +340,12 @@ def text(self, text: str, color: Tuple[int, int, int]) -> pygame.Surface: self.text_cache[key] = surf return surf - # ------------------------------------------------------------- cenário - def piece( - self, screen: pygame.Surface, specs: Specs, seq: int, side: int, x: float, z: float, cam: float, grow: float - ) -> None: - """Peça das margens na ordem fixa da lista; grow < 1 = afundando ou crescendo.""" - if z < C.NEAR_CLIP_Z or grow < 0.04 or not specs: - return - offset = len(specs) // 2 if side > 0 else 0 - for step in range(len(specs)): - name, height = specs[(seq + offset + step) % len(specs)] - sprite = self.scenery.get(name) - if sprite is not None: - # Os sprites mostram o lado direito (vista 3/4): à direita da pista, espelhados. - self.blit_world(screen, sprite, ("scenery", name), side * x, 0, z, height * grow, side > 0, cam) - return - - def margins(self, screen: pygame.Surface, world: World, seg: int, z: float) -> None: - """Duas fileiras por lado em cada trecho: fundo (z) e borda (z + 50).""" - biome = self.biome - mid_cam = self.cam * C.MID_PARALLAX - margin_cam = self.cam * C.MARGIN_PARALLAX - border_z = z + 50.0 - green = world.segment_green(seg) - solar = world.segment_solar(seg) - keep = 1.0 - solar # a peça do estágio anterior afunda enquanto a nova cresce - for side in (-1, 1): - # quarteirões: a cada 6 trechos, 2 ficam vazios (num lado de cada vez), para o - # cenário ter blocos e respiros em vez de uma fila contínua de peças soltas - if (seg + (3 if side > 0 else 0)) % 6 in (4, 5): - continue - if green < 1.0 and keep > 0.0: - self.piece(screen, biome.industrial_mid, seg, side, C.MID_ROW_X, z, mid_cam, (1.0 - green) * keep) - if green > 0.0 and keep > 0.0: - restored = seg % C.RESTORED_EVERY == C.RESTORED_REMAINDER - specs = biome.restored if restored else biome.green_mid - index = seg // C.RESTORED_EVERY + (side > 0) if restored else seg - self.piece(screen, specs, index, side, C.MID_ROW_X, z, mid_cam, green * keep) - if solar > 0.0: - marco = seg % C.LANDMARK_EVERY == 4 and (seg // C.LANDMARK_EVERY + (side > 0)) % 2 == 0 - specs = [biome.landmark] if marco else biome.solar_mid - self.piece(screen, specs, seg, side, C.MID_ROW_X, z, mid_cam, solar) - if border_z > C.MARGIN_MAX_Z or (seg + (side > 0)) % 2 or (seg // 2) % 4 == 3: - continue # a borda alterna de lado a cada trecho, tem vãos e some ao longe - if green < 1.0 and keep > 0.0: - self.piece( - screen, - biome.industrial_margin, - seg // 2, - side, - C.MARGIN_X, - border_z, - margin_cam, - (1.0 - green) * keep, - ) - if green > 0.0 and keep > 0.0: - self.piece( - screen, biome.green_margin, seg // 2 + 3, side, C.MARGIN_X, border_z, margin_cam, green * keep - ) - if solar > 0.0: - self.piece( - screen, - biome.solar_margin, - seg // 2 + (3 if side > 0 else 0), - side, - C.MARGIN_X, - border_z, - margin_cam, - solar, - ) - - def track_palette(self, world: World) -> TrackPalette: - """Cores da pista no quadro (mistura dos estágios), calculadas uma vez.""" - a, b, t = world.visual_stage_pair() - river = self.biome.river - weight = self.encounter_weight(world) if river else 0.0 - even = lerp_color(a.road_even, b.road_even, t) - odd = lerp_color(a.road_odd, b.road_odd, t) - return TrackPalette( - even=even, - odd=odd, - right_even=lerp_color(even, RIVER_ENCOUNTER, weight), - right_odd=lerp_color(odd, RIVER_ENCOUNTER, weight * 0.95), - purified=lerp_color(even, PURIFIED_ROAD, 0.2), - lane=lerp_color(a.lane_line, b.lane_line, t), - ground=lerp_color(a.ground, b.ground, t), - encounter=weight, - wave_z=180.0 + (world.visual / 100.0) ** 1.15 * 2150.0, # frente da pista purificada - ) - - def draw_track(self, screen: pygame.Surface, world: World, flags) -> None: - """Pista (ou rio) trecho a trecho, do horizonte para o avião, com as margens.""" - pal = self.track_palette(world) - fog = self.sky.fog_color - biome = self.biome - cam = self.cam - half = C.ROAD_WIDTH / 2 - stretches = [] - for i in range(len(world.segments) - 1, -1, -1): - z = world.segments[i] - seg = world.segment_base + i - edges = ( - project(-half, 0, z, cam), - project(half, 0, z, cam), - project(-half, 0, z + C.SEGMENT_LENGTH, cam), - project(half, 0, z + C.SEGMENT_LENGTH, cam), - ) - haze = haze_at(z + 50.0) - if not self.ground.textures: # sem texturas: chão liso por trecho - ground = C.GRASS_FALLBACK[seg % 2] if world.segment_green(seg) > 0.0 else pal.ground - left1, right1, left2, right2 = edges - pygame.draw.polygon( - screen, - lerp_color(ground, fog, haze), - [(0, left2[1]), (C.WIDTH, right2[1]), (C.WIDTH, right1[1]), (0, left1[1])], - ) - stretches.append((i, seg, z, edges, haze)) - self.ground.draw( - screen, world, flags, cam, fog, ("concrete", biome.green_ground, biome.solar_ground), biome.solar_road - ) - solar_road = self.ground.has(biome.solar_road) - solar_flags = flags[1] - for i, seg, z, edges, haze in stretches: - solar = bool(solar_flags) and solar_flags[i] - self.draw_road(screen, pal, seg, z, edges, haze, solar and solar_road) - if biome.river and solar: - self.curbs(screen, edges, lerp_color(RIVER_CURB, fog, haze), 5) # orla dourada do rio limpo - self.draw_lanes(screen, pal, seg, z, haze) - self.margins(screen, world, seg, z) - - def draw_road( - self, screen: pygame.Surface, pal: TrackPalette, seg: int, z: float, edges, haze: float, paved: bool - ) -> None: - """Superfície de um trecho: piso drenante (só o meio-fio), rio com encontro das águas ou pista.""" - fog = self.sky.fog_color - left1, right1, left2, right2 = edges - if paved: # a textura do piso já foi desenhada pelo chão - self.curbs(screen, edges, lerp_color(ROAD_CURB, fog, haze), 6) - return - even = seg % 2 == 0 - river = self.biome.river - purify = smoothstep((pal.wave_z - z) / C.ROAD_PURIFY_BAND) if not river else 0.0 - base = lerp_color(pal.even if even else pal.odd, pal.purified, purify) - if river: # encontro das águas: o Negro fica escuro à esquerda - base = lerp_color(base, RIVER_NEGRO, pal.encounter * (0.9 if even else 1.0)) - color = lerp_color(base, fog, haze) - if river and pal.encounter > 0.01: - mid1, mid2 = project(0, 0, z, self.cam), project(0, 0, z + C.SEGMENT_LENGTH, self.cam) - right = lerp_color(pal.right_even if even else pal.right_odd, fog, haze) - pygame.draw.polygon(screen, color, [left1[:2], mid1[:2], mid2[:2], left2[:2]]) - pygame.draw.polygon(screen, right, [mid1[:2], right1[:2], right2[:2], mid2[:2]]) - else: - pygame.draw.polygon(screen, color, [left1[:2], right1[:2], right2[:2], left2[:2]]) - - def draw_lanes(self, screen: pygame.Surface, pal: TrackPalette, seg: int, z: float, haze: float) -> None: - """Divisórias das faixas; no rio, reflexos curtos que andam (água corrente).""" - lane = lerp_color(pal.lane, self.sky.fog_color, haze) - if self.biome.river: - if (seg + int(self.elapsed * 3)) % 3: - return - z0, z1, thickness = z + 20, z + 60, 3 - else: - z0, z1, thickness = z, z + C.SEGMENT_LENGTH, 4 - for divider in (-0.5, 0.5): - p1 = project(C.LANE_WIDTH * divider, 0, z0, self.cam) - p2 = project(C.LANE_WIDTH * divider, 0, z1, self.cam) - pygame.draw.line(screen, lane, p1[:2], p2[:2], max(1, int(thickness * p1[2]))) - - @staticmethod - def curbs(screen: pygame.Surface, edges, color, thickness: int) -> None: - left1, right1, left2, right2 = edges - width = max(1, int(thickness * left1[2])) - pygame.draw.line(screen, color, left1[:2], left2[:2], width) - pygame.draw.line(screen, color, right1[:2], right2[:2], width) - - @staticmethod - def encounter_weight(world: World) -> float: - """Quanto do encontro das águas aparece: só no estágio do despertar (meio da fase).""" - value = world.visual - rise = clamp((value - C.ERA_SPAN * 0.8) / (C.ERA_SPAN * 0.4), 0.0, 1.0) - fall = clamp((value - C.ERA_SPAN * 1.8) / (C.ERA_SPAN * 0.5), 0.0, 1.0) - return rise * (1.0 - fall) - - # ----------------------------------------------------------- objetos - def halo(self, screen: pygame.Surface, world: World, entity: Entity, size: float) -> None: - """Halo pulsante atrás do que se pode PEGAR, em todos os estágios e modos. - - O GDD pede distinguir resíduos de obstáculos: o halo marca o que se coleta e os - chevrons no chão (alert) marcam o que colide. - """ - halo = self.fx.get("halo_coletavel") - if halo is None: - return - pulse = (0.94, 1.0, 1.06)[int(self.elapsed * 4.0 + entity.z * 0.01) % 3] - h = size * C.FINAL_HALO_SCALE * pulse - self.blit_world(screen, halo, ("fx", "halo"), entity.x, entity.y - h / 2, entity.z + 1.0, h) - - def alert(self, screen: pygame.Surface, entity: Entity, spec: ObstacleSpec) -> None: - """Estágio solarpunk: chevrons âmbar no chão da faixa antes do que COLIDE.""" - alert = self.fx.get("alerta_chao") - if alert is None: - return - near, far = entity.z - C.FINAL_ALERT_DEPTH[1], entity.z - C.FINAL_ALERT_DEPTH[0] - if near < C.NEAR_CLIP_Z or fog_level(far) >= C.FOG_LEVELS: - return - half = min(spec.width, C.LANE_WIDTH) * 0.42 - x0, y_far, _ = project(entity.x - half, 0, far, self.cam) - x1, _, _ = project(entity.x + half, 0, far, self.cam) - x2, y_near, _ = project(entity.x - half, 0, near, self.cam) - x3, _, _ = project(entity.x + half, 0, near, self.cam) - w, h = int(max(x1 - x0, x3 - x2)), int(y_near - y_far) - if w < 4 or h < 2 or w > C.WIDTH * 2: - return - step = max(2, int(w * 0.05)) - size = (w - w % step + step, max(2, h - h % max(2, int(h * 0.05)) + 2)) - scaled = self.cache.get(alert, ("fx", "alerta"), size) - level = fog_level(far) - if level > 0: - scaled = self.cache.fogged(scaled, (("fx", "alerta"), size, False), level) - screen.blit(scaled, (int((x2 + x3) / 2 - size[0] / 2), int(y_far))) - - def draw_entity(self, screen: pygame.Surface, world: World, entity: Entity) -> None: - if self.watercolor.load(world.biome.key): - self.paper_items.draw(screen, entity, self.cam, self.high_contrast) - if self.show_hitboxes: - pygame.draw.rect(screen, rgb("ff1744"), self.hitbox_rect(entity_hitbox(entity)), 2) - return - hc = self.high_contrast - if entity.kind == "waste": - self.halo(screen, world, entity, 46.0) - self.shadow(screen, entity.x, entity.z, 50, 70) - sprite = self.waste.get(entity.sprite) - color = WASTE_BY_KEY[entity.sprite].color if entity.sprite in WASTE_BY_KEY else rgb("ffb300") - bob = math.sin(self.elapsed * 3.0 + entity.z * 0.02) * 3 - if sprite is not None: - self.blit_world( - screen, - sprite, - ("item", entity.sprite), - entity.x, - entity.y - 23 + bob, - entity.z, - 46, - outline=color if hc else None, - ) - else: - self.fallback_ball(screen, entity, color, 22) - elif entity.spec is None: # power-up - self.halo(screen, world, entity, 56.0) - self.shadow(screen, entity.x, entity.z, 46, 60) - sprite = self.powerups.get(entity.kind) - color = POWERUP_COLORS.get(entity.kind, (255, 255, 255)) - bob = math.sin(self.elapsed * 3.2 + entity.z * 0.015) * 4 - if sprite is not None: - self.blit_world( - screen, - sprite, - ("item", entity.kind), - entity.x, - entity.y - 26 + bob, - entity.z, - 56, - outline=color if hc else None, - ) - else: - self.fallback_ball(screen, entity, color, 20) - else: - spec = entity.spec - self.alert(screen, entity, spec) - sprite = self.scenery.get(spec.sprite) - if sprite is not None: - self.blit_world( - screen, - sprite, - ("scenery", spec.sprite), - entity.x, - 0, - entity.z, - spec.visual_height, - outline=HC_OBSTACLE if hc else None, - ) - else: - rect = self.hitbox_rect(entity_hitbox(entity)) - color = {"low": rgb("5d4037"), "gate": rgb("311b92"), "tower": rgb("3e2723")}[entity.kind] - pygame.draw.rect(screen, color, rect, 5 if entity.kind == "gate" else 0) - if self.show_hitboxes: - rect = self.hitbox_rect(entity_hitbox(entity)) - pygame.draw.rect(screen, rgb("00e676") if entity.kind == "waste" else rgb("ff1744"), rect, 2) - - def fallback_ball(self, screen: pygame.Surface, entity: Entity, color: Color, radius: float) -> None: - x, y, scale = project(entity.x, entity.y, entity.z, self.cam) - r = max(3, int(radius * max(0.08, scale))) - pygame.draw.circle(screen, color, (int(x), int(y)), r) - pygame.draw.circle(screen, (255, 255, 255), (int(x), int(y)), r, max(1, r // 6)) - - def hitbox_rect(self, box) -> pygame.Rect: - z = max(20.0, (box.z_min + box.z_max) / 2) - x0, y0, _ = project(box.x_min, min(box.y_max, 330.0), z, self.cam) - x1, y1, _ = project(box.x_max, box.y_min, z, self.cam) - return pygame.Rect(int(x0), int(y0), max(1, int(x1 - x0)), max(1, int(y1 - y0))) - - # ----------------------------------------------------------------- avião - def draw_player(self, screen: pygame.Surface, run: FlightView, look: PlaneLook) -> None: - player = run.player - self.shadow( - screen, - player.x, - C.PLAYER_Z, - C.PLANE_WIDTH * (1.1 - player.y / 800), - int(clamp(150 - player.y * 0.5, 40, 150)), - ) - blink = not self.reduce_motion and not self.high_contrast - if blink and run.invulnerable_timer > 0 and int(self.elapsed * 14) % 2: - return # pisca depois de uma colisão - bob = 0 if self.reduce_motion else math.sin(self.elapsed * 3.0) * 3.0 - sx, sy, scale = project(player.x, player.y + bob, C.PLAYER_Z, self.cam) - width = max(8, int(C.PLANE_WIDTH * scale)) - sprite = self.skin.surface(look.plane, "flight", look.color, look.pattern, look.pilot) - look_key = self.skin.look_key(look.plane, look.color, look.pattern, look.pilot) - if sprite is not None and self.high_contrast: - sprite = self.cache.outlined_source(sprite, ("plane", look_key), HC_PLANE) - look_key += "#hc" - pose = player.maneuver_pose() - if sprite is None: - self.player_rect = pygame.Rect(0, 0, width, max(24, round(width * 0.6))) - self.player_rect.center = round(sx), round(sy) - self.draw_paper_fallback(screen, int(sx), int(sy), width, player.roll + (pose[0] if pose else 0.0)) - return - aspect = sprite.get_height() / max(1, sprite.get_width()) - height = max(4, int(width * aspect)) - max_h = int(120 * scale) # piloto alto não cobre a tela - if height > max_h: - height = max_h - width = max(8, int(height / aspect)) - if pose is not None: - m_roll, m_pitch, m_dx, m_dy, m_dz = pose - style = MANEUVER_STYLES[player.maneuver] - sx += m_dx * style.sway * width - sy = max(C.MANEUVER_TOP_MARGIN, sy - m_dy * style.lift * width) - depth = 1.0 / max(0.4, 1.0 + style.depth * m_dz) - vertical = math.cos(math.radians(m_pitch)) - thickness = round(max(C.MANEUVER_MIN_THICKNESS, abs(vertical)) * 25) / 25 - # tamanho e ângulo em degraus: a manobra se repete e reaproveita as imagens prontas - size = (max(8, int(width * depth)) // 4 * 4, max(4, int(height * depth * thickness)) // 4 * 4) - angle = round((player.roll + m_roll) / 4.0) * 4.0 - key = ("manobra", look_key, size, angle, vertical < 0) - image = self.rotations.get(key) - if image is None: - img = self.cache.get(sprite, ("plane", look_key), size) - if vertical < 0: # de cabeça para baixo (topo do looping) - img = pygame.transform.flip(img, False, True) - image = self.remember_rotation(key, pygame.transform.rotozoom(img, angle, 1.0)) - width = size[0] - else: - # papel tremulando no ar e nariz que sobe ou desce com a velocidade vertical - # (em degraus, para reaproveitar as imagens giradas prontas) - flutter = 0 if self.reduce_motion else C.PAPER_FLUTTER_DEG * math.sin(self.elapsed * 7.0) - if not self.reduce_motion and self.celebration > 0: - flutter += 5 * math.sin(self.celebration * math.tau) * min(1.0, self.celebration) - pitch = clamp(player.vy / C.MAX_VERTICAL_SPEED, -1.0, 1.0) - height = max(4, int(height * (1.0 + round(pitch * C.PITCH_STRETCH * 25) / 25))) - base = self.cache.get(sprite, ("plane", look_key), (width, height)) - angle = round((player.roll + flutter) / 2.0) * 2.0 - key = (look_key, width, height, angle) - image = self.rotations.get(key) - if image is None: - image = self.remember_rotation(key, pygame.transform.rotozoom(base, angle, 1.0)) - self.player_rect = image.get_rect(center=(int(sx), int(sy))) - screen.blit(image, self.player_rect) - if run.shield_timer > 0: - pulse = 0.5 + 0.5 * math.sin(self.elapsed * 8.0) - pygame.draw.ellipse( - screen, - lerp_color(rgb("40c4ff"), (255, 255, 255), pulse * 0.4), - pygame.Rect(int(sx - width * 0.62), int(sy - width * 0.36), int(width * 1.24), int(width * 0.72)), - max(2, int(3 * scale)), - ) - if run.magnet_timer > 0: - pygame.draw.circle( - screen, - POWERUP_COLORS["magnet"], - (int(sx), int(sy)), - int(width * (0.7 + 0.05 * math.sin(self.elapsed * 10))), - 1, - ) - if self.show_hitboxes: - pygame.draw.rect(screen, rgb("40c4ff"), self.hitbox_rect(player.hitbox()), 2) - - @staticmethod - def splash(screen: pygame.Surface, center, color, progress: float, scale: float) -> None: - """Gotas que se abrem e somem (progress 0 -> 1), com um pingo claro no meio.""" - cx, cy = int(center[0]), int(center[1]) - pale = lerp_color(color, (255, 255, 255), 0.35) - for k in range(7): - angle = k * 0.9 + 0.3 - reach = (14 + 70 * progress) * scale - r = max(1, int((7 - 5 * progress) * scale)) - px, py = int(cx + math.cos(angle) * reach), int(cy + math.sin(angle) * reach * 0.7) - pygame.draw.circle(screen, color, (px, py), r) - core = max(1, int((22 - 20 * progress) * scale)) - pygame.draw.circle(screen, pale, (cx, cy), core) - if progress < 0.6: - pygame.draw.circle(screen, (255, 255, 255), (cx - core // 3, cy - core // 3), max(1, core // 3)) - - def remember_rotation(self, key: tuple, image: pygame.Surface) -> pygame.Surface: - """Guarda uma rotação do avião (descarte gradual, como o cache de sprites).""" - return self.rotations.put(key, image) - - @staticmethod - def draw_paper_fallback(screen: pygame.Surface, cx: int, cy: int, width: int, roll: float) -> None: - """Avião de papel desenhado por código (se os sprites faltarem).""" - h = width * 0.28 - angle = math.radians(roll) - - def rot(px: float, py: float) -> Tuple[int, int]: - return ( - int(cx + px * math.cos(angle) - py * math.sin(angle)), - int(cy + px * math.sin(angle) + py * math.cos(angle)), - ) - - left = [rot(0, -h * 0.35), rot(-width / 2, h * 0.25), rot(0, h * 0.1)] - right = [rot(0, -h * 0.35), rot(width / 2, h * 0.25), rot(0, h * 0.1)] - keel = [rot(0, -h * 0.35), rot(-width * 0.05, h * 0.6), rot(width * 0.05, h * 0.6)] - pygame.draw.polygon(screen, (232, 232, 226), left) - pygame.draw.polygon(screen, (250, 250, 246), right) - pygame.draw.polygon(screen, (180, 186, 190), keel) - pygame.draw.lines(screen, rgb("78909c"), True, left + right[1:], 1) - # ------------------------------------------------------------ quadro - def background(self, screen: pygame.Surface, world: World, cam: float) -> None: + def background(self, screen: pygame.Surface, world: WorldStateView, cam: float) -> None: """Céu, chão, pista e margens (tudo o que fica atrás dos objetos).""" - self.world = world self.cam = cam self.set_biome(world.biome) + self.world = world if self.watercolor.draw(screen, world, cam, self.reduce_motion): self.cache.fog_color = (231, 232, 217) if self.high_contrast: @@ -688,7 +357,7 @@ def background(self, screen: pygame.Surface, world: World, cam: float) -> None: self.sky.update_atmosphere(world.visual, horizon, world.biome.polluted_haze) self.cache.fog_color = self.sky.fog_sprite_color solar = world.solar_share() - self.sky.draw(screen, top, horizon, cam, world.distance, solar, self.elapsed) + self.sky.draw(screen, top, horizon, cam, world.distance, solar, self.elapsed, world.challenge_theme) pygame.draw.rect(screen, self.sky.fog_color, (0, C.HORIZON_Y, C.WIDTH, C.HEIGHT - C.HORIZON_Y)) self.draw_track(screen, world, world.stage_flags()) if self.high_contrast: @@ -719,8 +388,7 @@ def draw_run(self, screen: pygame.Surface, run: FlightView, look: PlaneLook, cel self.viewport = viewport(self.contrast_scale, self.player_rect.center, self.player_rect.size) # A ampliação mantém contornos nítidos e evita filtrar o quadro inteiro # outra vez; o fundo já recebeu a suavização de alto contraste. - pygame.transform.scale(self.accessible_canvas.subsurface(self.viewport), - screen.get_size(), screen) + pygame.transform.scale(self.accessible_canvas.subsurface(self.viewport), screen.get_size(), screen) else: self.viewport = pygame.Rect(0, 0, C.WIDTH, C.HEIGHT) self._draw_run(screen, run, look) @@ -733,7 +401,7 @@ def _draw_run(self, screen: pygame.Surface, run: FlightView, look: PlaneLook) -> world = run.world self.mode = run.mode self.background(screen, world, run.player.cam_x) - entities: List[Entity] = sorted(world.entities, key=lambda e: e.z, reverse=True) + entities: List[EntityView] = sorted(world.entities, key=lambda e: e.z, reverse=True) behind = [e for e in entities if e.z >= C.PLAYER_Z] ahead = [e for e in entities if e.z < C.PLAYER_Z] for entity in behind: @@ -741,7 +409,7 @@ def _draw_run(self, screen: pygame.Surface, run: FlightView, look: PlaneLook) -> self.draw_player(screen, run, look) for entity in ahead: self.draw_entity(screen, world, entity) - for beam in ([] if self.reduce_motion else run.beams): # respingo opcional + for beam in [] if self.reduce_motion else run.beams: # respingo opcional x, y, scale = project(beam.x, 90.0, max(C.NEAR_CLIP_Z, beam.z), self.cam) self.splash(screen, (x, y), beam.color, clamp(1.0 - beam.ttl / 0.55, 0.0, 1.0), scale) for text in run.floating: diff --git a/dobramundo/game/challenges.py b/dobramundo/game/challenges.py new file mode 100644 index 0000000..1144555 --- /dev/null +++ b/dobramundo/game/challenges.py @@ -0,0 +1,42 @@ +"""Desafios comunitários reproduzíveis com identidade de cada bioma.""" + +from __future__ import annotations + +from typing import NamedTuple, Optional, Tuple + +from .. import config as C + + +class ChallengeTheme(NamedTuple): + """Pista regional para render e geração; decorações são tags, não assets carregados.""" + + key: str + title: str + preferred_obstacle: str + decorations: Tuple[str, ...] + + +REGIONAL_CHALLENGES = { + "amazonia": ( + ChallengeTheme("encontro_das_aguas", "Encontro das águas", "gate", ("river", "boat")), + ChallengeTheme("porto_de_manaus", "Porto de Manaus", "low", ("boat", "river")), + ChallengeTheme("igarapes", "Igarapés", "gate", ("river", "trees")), + ChallengeTheme("trilha_da_floresta", "Trilha da floresta", "tower", ("trees", "fauna")), + ), + "caatinga": ( + ChallengeTheme("pomares_do_sao_francisco", "Pomares do São Francisco", "low", ("fruit_trees", "river")), + ChallengeTheme("ribeira_de_petrolina", "Ribeira de Petrolina", "gate", ("river", "tram")), + ChallengeTheme("energia_do_sertao", "Energia do sertão", "tower", ("solar", "wind")), + ChallengeTheme("travessia_da_caatinga", "Travessia da Caatinga", "low", ("trees", "river")), + ), +} + + +def challenge_theme_for(biome_key: str, seed: Optional[int]) -> Optional[ChallengeTheme]: + """Mapeia somente as sementes publicadas; sementes aleatórias não ganham rótulo regional.""" + if seed is None or seed not in C.COMMUNITY_CHALLENGE_SEEDS: + return None + themes = REGIONAL_CHALLENGES.get(biome_key) + if themes is None: + return None + return themes[C.COMMUNITY_CHALLENGE_SEEDS.index(seed)] diff --git a/dobramundo/game/entities.py b/dobramundo/game/entities.py index 936c1f9..8ccd19b 100644 --- a/dobramundo/game/entities.py +++ b/dobramundo/game/entities.py @@ -30,6 +30,10 @@ class Entity: def x(self) -> float: return self.lane * LANE_WIDTH + def hitbox(self) -> Hitbox: + """Caixa física usada pela colisão, compartilhada com a representação visual.""" + return entity_hitbox(self) + @dataclass class Beam: diff --git a/dobramundo/game/missions.py b/dobramundo/game/missions.py index ca42e95..f04ef26 100644 --- a/dobramundo/game/missions.py +++ b/dobramundo/game/missions.py @@ -9,8 +9,9 @@ from __future__ import annotations import random -from typing import Dict, NamedTuple, Optional +from typing import Dict, Mapping, NamedTuple, Optional +from .. import config as C from ..content.items import WASTE_BY_KEY, WASTE_KEYS KINDS = ("coletar", "desviar", "portal", "powerup") @@ -18,8 +19,10 @@ "normal": {"coletar": 2, "desviar": 3, "portal": 2, "powerup": 1}, "dificil": {"coletar": 6, "desviar": 6, "portal": 3, "powerup": 2}, } -FIRST_DELAY_S = 4.0 # a primeira meta aparece depois da decolagem +FIRST_DELAY_S = 4.0 # voo sem abertura didática NEXT_DELAY_S = 2.5 # pausa curta entre uma meta e a próxima +NO_SUPPLY_RETRY_S = 0.5 # não varre entidades em todos os quadros enquanto espera oferta +MISSION_TIMEOUT_S = 60.0 # metas não cumpridas saem sem prêmio ou punição BONUS_RESTORATION = 0.5 # transformação extra por meta cumprida BONUS_RESOURCES = 6 # recursos extras (do tipo da meta, ou um tipo qualquer) BONUS_POINTS = 50 @@ -44,27 +47,81 @@ def text(self, progress: int) -> str: class MissionTracker: """Sorteia e acompanha as metas de um voo (determinístico com a mesma semente).""" - def __init__(self, mode: str, rng: Optional[random.Random] = None) -> None: + def __init__( + self, + mode: str, + rng: Optional[random.Random] = None, + intro: bool = False, + preferred_waste: Optional[str] = None, + ) -> None: self.targets = TARGETS.get(mode, TARGETS["normal"]) self.rng = rng or random.Random() + self.intro = intro + self.preferred_waste = preferred_waste if preferred_waste in WASTE_KEYS else None self.current: Optional[Mission] = None self.progress = 0 self.completed = 0 - self.wait = FIRST_DELAY_S + self.expired = 0 + self.current_age = 0.0 + # Não compete com as quatro demonstrações iniciais; a primeira meta aparece + # depois do último ensino e só usa alvos presentes à frente do avião. + self.wait = C.INTRO_END_S + 0.5 if intro else FIRST_DELAY_S self.last_kind = "" - def update(self, dt: float) -> None: + def update(self, dt: float, available: Optional[Mapping[str, object]] = None) -> bool: + """Avança o tempo da meta; devolve True quando uma meta expira sem recompensa.""" + if self.current is not None: + self.current_age += dt + if self.current_age >= MISSION_TIMEOUT_S: + self.current = None + self.progress = 0 + self.current_age = 0.0 + self.expired += 1 + self.wait = NEXT_DELAY_S + return True + return False if self.current is None: self.wait -= dt if self.wait <= 0: - self.current = self.pick() - self.progress = 0 + mission = self.pick(available) if available is not None else self.pick() + if mission is not None: + self.current = mission + self.progress = 0 + self.current_age = 0.0 + return False + + def pick(self, available: Optional[Mapping[str, object]] = None) -> Optional[Mission]: + if available is None: + kind = self.rng.choice([k for k in KINDS if k != self.last_kind]) + waste = self.rng.choice(WASTE_KEYS) if kind == "coletar" else None + self.last_kind = kind + return Mission(kind, self.targets[kind], waste) - def pick(self) -> Mission: - kind = self.rng.choice([k for k in KINDS if k != self.last_kind]) # não repete o tipo seguido - self.last_kind = kind - waste = self.rng.choice(WASTE_KEYS) if kind == "coletar" else None - return Mission(kind, self.targets[kind], waste) + offered = [] + supplies = available.get("coletar", {}) + if isinstance(supplies, Mapping): + for waste in WASTE_KEYS: + count = int(supplies.get(waste, 0)) + if count > 0: + offered.append(Mission("coletar", min(self.targets["coletar"], count), waste)) + for kind in ("desviar", "portal", "powerup"): + count = int(available.get(kind, 0)) + if count > 0: + offered.append(Mission(kind, min(self.targets[kind], count))) + if not offered: + # Reavaliar no próximo quadro; não oferecer uma meta sem alvos no percurso. + self.wait = NO_SUPPLY_RETRY_S + return None + candidates = [mission for mission in offered if mission.kind != self.last_kind] + preferred = [ + mission for mission in candidates if mission.kind == "coletar" and mission.waste == self.preferred_waste + ] + if preferred and self.rng.random() < 0.5: + mission = self.rng.choice(preferred) + else: + mission = self.rng.choice(candidates or offered) + self.last_kind = mission.kind + return mission def record(self, kind: str, waste: Optional[str] = None) -> Optional[Mission]: """Conta um acontecimento; devolve a meta quando ela acaba de ser cumprida.""" @@ -76,6 +133,7 @@ def record(self, kind: str, waste: Optional[str] = None) -> Optional[Mission]: return None self.current = None self.completed += 1 + self.current_age = 0.0 self.wait = NEXT_DELAY_S return mission diff --git a/dobramundo/game/run.py b/dobramundo/game/run.py index 1f13368..0079d45 100644 --- a/dobramundo/game/run.py +++ b/dobramundo/game/run.py @@ -7,8 +7,10 @@ from __future__ import annotations +import hashlib import math import random +import secrets from typing import Dict, List, Mapping, Optional, Tuple from .. import config as C @@ -37,15 +39,52 @@ def __init__( rng: Optional[random.Random] = None, intro: bool = False, focus: bool = True, + seed: Optional[int] = None, + session_limit_s: int = 0, + exploration: bool = False, + predictable_assistance: bool = False, + community_challenge: bool = False, + mission_preferred_waste: Optional[str] = None, ) -> None: self.biome = biome self.mode = mode self.parts = dict(parts or {}) - self.world = World(biome, mode, rng, intro) + if seed is None: + if rng is None: + seed = secrets.randbits(32) + else: + # Deriva uma seed reproduzível do estado sem avançar o RNG fornecido. + state = repr(rng.getstate()).encode("ascii") + seed = int.from_bytes(hashlib.blake2s(state, digest_size=4).digest(), "big") + self.seed = int(seed) & 0xFFFFFFFF + self.intro = bool(intro) + self.world = World( + biome, + mode, + random.Random(self.seed), + self.intro, + challenge_seed=self.seed if community_challenge else None, + ) + self.community_challenge = self.world.challenge_theme is not None self.focus = FocusMoment(mode, focus) - self.missions = MissionTracker(mode, random.Random(self.world.rng.random())) + self.mission_preferred_waste = ( + mission_preferred_waste if mission_preferred_waste in WASTE_KEYS and self.community_challenge else None + ) + self.missions = MissionTracker( + mode, + random.Random(self.world.rng.random()), + intro=intro, + preferred_waste=self.mission_preferred_waste, + ) self.player = Player(plane_stats(self.parts), maneuvers) - self.lives = C.MAX_LIVES + self.exploration = bool(exploration) + self.predictable_assistance = bool(predictable_assistance) + self.max_lives = C.ASSISTED_MAX_LIVES if self.predictable_assistance else C.MAX_LIVES + self.invulnerable_duration = C.ASSISTED_INVULNERABLE_S if self.predictable_assistance else C.INVULNERABLE_S + self.lives = self.max_lives + requested_limit = max(0, int(session_limit_s)) + self.session_limit_s = requested_limit if requested_limit in C.SESSION_LIMITS_S else 0 + self.timeout = False self.score = 0 self.resources: Dict[str, int] = {k: 0 for k in WASTE_KEYS} self.combo = 1 @@ -77,6 +116,9 @@ def __init__( self.body_time = 0.0 # segundos com o corpo controlando self.last_command: Optional[Tuple[float, float]] = None self.hits = 0 + self.waste_collected = 0 + self.pause_count = 0 + self.pause_duration_s = 0.0 self.player.start_maneuver(START_MANEUVER) # --------------------------------------------------------------- regras @@ -123,6 +165,7 @@ def collect_waste(self, entity: Entity) -> None: if entity.collected: return entity.collected = True + self.waste_collected += 1 normal = self.mode == "normal" value = C.NORMAL_TRASH_POINTS if normal else C.HARD_TRASH_POINTS * self.combo self.score += value @@ -152,7 +195,7 @@ def collect_powerup(self, entity: Entity) -> None: elif entity.kind == "magnet": self.magnet_timer = max(self.magnet_timer, C.MAGNET_S) label = "ÍMÃ" - elif self.lives < C.MAX_LIVES: + elif self.lives < self.max_lives: self.lives += 1 label = "+1 VIDA" else: # reparo com vidas cheias: transforma a cidade @@ -170,13 +213,16 @@ def take_hit(self) -> None: return self.lives = max(0, self.lives - 1) self.hits += 1 - self.invulnerable_timer = C.INVULNERABLE_S + self.invulnerable_timer = self.invulnerable_duration self.hit_flash_timer = C.HIT_FLASH_S self.combo = 1 self.streak = 0 self.combo_timer = 0.0 self.emit("hit", self.lives) - if self.lives == 0: + if self.lives == 0 and self.exploration: + self.lives = self.max_lives + self.emit("exploration_continue", self.hits) + elif self.lives == 0: self.game_over = True self.finished = True self.emit("game_over", self.stars) @@ -195,6 +241,15 @@ def update(self, dt: float, ix: float = 0.0, iy: float = 0.0, target: Optional[T if self.finished: return real_dt = min(dt, C.MAX_DT) + if self.session_limit_s: + remaining = max(0.0, self.session_limit_s - self.flight_time) + if remaining <= 1e-9: + self.timeout = True + self.interrupted = not self.complete + self.finished = True + self.emit("session_end", self.flight_time) + return + real_dt = min(real_dt, remaining) self.flight_time += real_dt player = self.player aim = None if target is None else player.command_target(*target) @@ -218,7 +273,12 @@ def update(self, dt: float, ix: float = 0.0, iy: float = 0.0, target: Optional[T self.announce_lessons() self.check_collisions() self.count_passes() - self.missions.update(dt) + if self.missions.current is None and self.missions.wait <= dt: + expired = self.missions.update(dt, self.mission_supply()) + else: + expired = self.missions.update(dt) + if expired: + self.emit("mission_expired") self.world.prune() for beam in self.beams: beam.z -= self.speed * dt @@ -232,6 +292,29 @@ def update(self, dt: float, ix: float = 0.0, iy: float = 0.0, target: Optional[T self.complete_timer += dt if self.complete_timer >= COMPLETE_GLIDE_S: self.finished = True + if self.session_limit_s and self.flight_time >= self.session_limit_s - 1e-9 and not self.finished: + self.timeout = True + self.interrupted = not self.complete + self.finished = True + self.emit("session_end", self.flight_time) + + def mission_supply(self) -> Dict[str, object]: + """Oferta concreta à frente do avião para evitar metas sem alvo no percurso.""" + cutoff = C.PLAYER_Z + max(120.0, self.speed * 3.0) + supply: Dict[str, object] = {"coletar": {}, "desviar": 0, "portal": 0, "powerup": 0} + collect = supply["coletar"] + for entity in self.world.entities: + if entity.collected or entity.passed or entity.z <= cutoff: + continue + if entity.kind == "waste": + collect[entity.sprite] = collect.get(entity.sprite, 0) + 1 + elif entity.kind in ("shield", "magnet", "repair"): + supply["powerup"] += 1 + elif entity.spec is not None: + supply["desviar"] += 1 + if entity.kind == "gate": + supply["portal"] += 1 + return supply def announce_lessons(self) -> None: """Legenda de cada objeto da abertura didática, LESSON_LEAD_S antes de ele chegar.""" @@ -257,12 +340,30 @@ def summary(self) -> Dict[str, object]: return { "fase": self.biome.key, "modo": self.mode, + "abertura_didatica": int(self.intro), + "desafio_comunitario": int(self.community_challenge), + "material_preferido_missao": self.mission_preferred_waste or "", + "exploracao": int(self.exploration), + "assistencia_previsivel": int(self.predictable_assistance), + "limite_s": self.session_limit_s, + "semente": self.seed, + "tempo_esgotado": int(self.timeout), + "vidas_maximas": self.max_lives, + "vidas_finais": self.lives, "concluida": int(self.complete), "interrompida": int(self.interrupted), "transformacao": round(self.restoration, 1), "estrelas": self.stars, "pontos": self.score, "batidas": self.hits, + "coletas": self.waste_collected, + "recursos_total": sum(self.resources.values()), + "recurso_papel": self.resources["papel"], + "recurso_plastico": self.resources["plastico"], + "recurso_metal": self.resources["metal"], + "recurso_vidro": self.resources["vidro"], + "pausas": self.pause_count, + "pausa_s": round(self.pause_duration_s, 1), "foco_acertos": self.focus.successes, "foco_total": self.focus.total, "duracao_s": round(self.flight_time, 1), diff --git a/dobramundo/game/world.py b/dobramundo/game/world.py index 3e0b709..256616e 100644 --- a/dobramundo/game/world.py +++ b/dobramundo/game/world.py @@ -21,6 +21,7 @@ from ..content.items import OBSTACLE_KINDS, POWERUP_KINDS, WASTE_KEYS, ObstacleSpec from ..content.progress import plane_stats from ..util import clamp, smoothstep +from .challenges import ChallengeTheme, challenge_theme_for from .entities import Entity GOLDEN = 0.6180339887498949 # ordem espalhada em que os trechos viram verdes @@ -40,9 +41,7 @@ ROUTE_X_STEP = 10.0 ROUTE_Y_STEP = 11.0 ROUTE_Z_HALF = 16.0 + 27.0 -ROUTE_POSITION_RESPONSE = ( - 1.0 - math.exp(-C.POSITION_RESPONSE * C.MAX_DT) -) / C.MAX_DT +ROUTE_POSITION_RESPONSE = (1.0 - math.exp(-C.POSITION_RESPONSE * C.MAX_DT)) / C.MAX_DT def _route_grid() -> Tuple[List[float], List[float]]: @@ -60,9 +59,9 @@ def _route_grid() -> Tuple[List[float], List[float]]: # alturas em intervalos de x; multiplicá-las pela máscara y forma o retângulo. _ROUTE_X_MASKS = tuple( tuple( - (((1 << (_ROUTE_Y_COUNT * (end - start))) - 1) // ((1 << _ROUTE_Y_COUNT) - 1)) - << (_ROUTE_Y_COUNT * start) - if end > start else 0 + (((1 << (_ROUTE_Y_COUNT * (end - start))) - 1) // ((1 << _ROUTE_Y_COUNT) - 1)) << (_ROUTE_Y_COUNT * start) + if end > start + else 0 for end in range(len(_ROUTE_XS) + 1) ) for start in range(len(_ROUTE_XS) + 1) @@ -90,9 +89,7 @@ def _axis_reach_limit( distance = target_distance - min(target_distance, speed / position_response) * math.exp( -position_response * (elapsed - saturation_time) ) - velocity_distance = speed * ( - elapsed - (1.0 - math.exp(-velocity_response * elapsed)) / velocity_response - ) + velocity_distance = speed * (elapsed - (1.0 - math.exp(-velocity_response * elapsed)) / velocity_response) return min(distance, velocity_distance) @@ -109,9 +106,11 @@ def _axis_reachable( if abs(end - start) < 1e-9: return True direction = 1.0 if end > start else -1.0 - return abs(end - start) <= _axis_reach_limit( - start, direction, elapsed, speed, minimum, maximum, position_response, velocity_response - ) + 1e-9 + return ( + abs(end - start) + <= _axis_reach_limit(start, direction, elapsed, speed, minimum, maximum, position_response, velocity_response) + + 1e-9 + ) def find_reachable_route(entities: List[Entity], mode: str) -> Optional[List[Tuple[float, float]]]: @@ -128,20 +127,19 @@ def find_reachable_route(entities: List[Entity], mode: str) -> Optional[List[Tup half_w = C.PLANE_WIDTH * 0.42 * stats.hitbox half_h = C.PLANE_HEIGHT * 0.5 * stats.hitbox threats = [ - entity for entity in entities - if entity.spec is not None and not entity.collected and not entity.hit and not entity.dodged + entity + for entity in entities + if entity.spec is not None + and not entity.collected + and not entity.hit + and not entity.dodged and entity.z - C.PLAYER_Z >= -ROUTE_Z_HALF ] if not threats: return [] intervals = sorted( - [ - (entity.z - C.PLAYER_Z - ROUTE_Z_HALF, - entity.z - C.PLAYER_Z + ROUTE_Z_HALF, - entity) - for entity in threats - ], + [(entity.z - C.PLAYER_Z - ROUTE_Z_HALF, entity.z - C.PLAYER_Z + ROUTE_Z_HALF, entity) for entity in threats], key=lambda item: (item[0], item[1]), ) groups: List[Tuple[float, float, List[Entity]]] = [] @@ -185,14 +183,28 @@ def free_cells(members: List[Entity]) -> set[Tuple[int, int]]: if index == 0: available = max(0.0, start / worst_case_speed - movement_margin) reachable = { - (xi, yi) for xi, x in enumerate(_ROUTE_XS) for yi, y in enumerate(_ROUTE_YS) + (xi, yi) + for xi, x in enumerate(_ROUTE_XS) + for yi, y in enumerate(_ROUTE_YS) if _axis_reachable( - 0.0, x, available, move_x, -C.MAX_PLAYER_X, C.MAX_PLAYER_X, - position_response, velocity_response, + 0.0, + x, + available, + move_x, + -C.MAX_PLAYER_X, + C.MAX_PLAYER_X, + position_response, + velocity_response, ) and _axis_reachable( - C.START_ALTITUDE, y, available, move_y, C.MIN_ALTITUDE, C.MAX_ALTITUDE, - position_response, velocity_response, + C.START_ALTITUDE, + y, + available, + move_y, + C.MIN_ALTITUDE, + C.MAX_ALTITUDE, + position_response, + velocity_response, ) } current = {cell: None for cell in safe & reachable} @@ -213,12 +225,24 @@ def free_cells(members: List[Entity]) -> set[Tuple[int, int]]: cell not in current and cell in safe and _axis_reachable( - _ROUTE_XS[px], _ROUTE_XS[xi], available, move_x, - -C.MAX_PLAYER_X, C.MAX_PLAYER_X, position_response, velocity_response, + _ROUTE_XS[px], + _ROUTE_XS[xi], + available, + move_x, + -C.MAX_PLAYER_X, + C.MAX_PLAYER_X, + position_response, + velocity_response, ) and _axis_reachable( - _ROUTE_YS[py], _ROUTE_YS[yi], available, move_y, - C.MIN_ALTITUDE, C.MAX_ALTITUDE, position_response, velocity_response, + _ROUTE_YS[py], + _ROUTE_YS[yi], + available, + move_y, + C.MIN_ALTITUDE, + C.MAX_ALTITUDE, + position_response, + velocity_response, ) ): current.setdefault(cell, (px, py)) @@ -349,8 +373,11 @@ def try_add(self, entity: Entity, entity_global_z: float) -> bool: return False # preserva a ordem planejada; não reancora num estado inventado if last is not None and start <= last.end: group = self._extend( - last.start, max(last.end, end), last.members + [entity], - last.before_frontier, last.before_end, + last.start, + max(last.end, end), + last.members + [entity], + last.before_frontier, + last.before_end, ) else: group = self._extend(start, end, [entity], self.frontier, self.end) @@ -372,10 +399,12 @@ def __init__( rng: Optional[random.Random] = None, intro: bool = False, restoration: Optional[float] = None, + challenge_seed: Optional[int] = None, ) -> None: self.biome = biome self.mode = mode self.intro = intro # abertura didática: uma coisa por vez antes do sorteio + self.challenge_theme: Optional[ChallengeTheme] = challenge_theme_for(biome.key, challenge_seed) self.rng = rng or random.Random() self.route_planner = RoutePlanner(mode) self.restoration = C.START_RESTORATION # transformação real (jogabilidade) @@ -650,14 +679,23 @@ def spawn_pattern(self, z: float) -> None: if self.waste_allowed(): self.entities.append(Entity(z + 45.0, lane2, "waste", y2, self.next_waste())) if rng.random() < 0.35 + self.difficulty * 0.30: - roll = rng.random() - kind = "low" if roll < 0.45 else ("gate" if roll < 0.75 else "tower") + kind = self.choose_obstacle_kind(rng.random()) solar = self.spawn_is_solar(z) self.add_reachable_obstacle(z, rng.choice(available), kind, solar) if rng.random() < 0.13: kind = rng.choice(POWERUP_KINDS) self.entities.append(Entity(z + 30.0, rng.choice(lanes), kind, rng.choice(C.TRASH_HEIGHTS))) + def choose_obstacle_kind(self, roll: float) -> str: + """Desafios regionais inclinam a sequência sem remover variedades nem planner.""" + if self.challenge_theme is None: + return "low" if roll < 0.45 else ("gate" if roll < 0.75 else "tower") + preferred = self.challenge_theme.preferred_obstacle + alternatives = [kind for kind in OBSTACLE_KINDS if kind != preferred] + if roll < 0.55: + return preferred + return alternatives[0] if roll < 0.55 + 0.225 else alternatives[1] + # -------------------------------------------------------------- avanço def advance(self, dt: float, dz: float) -> None: """Move a pista dz unidades em direção ao avião e recicla os trechos que passaram.""" diff --git a/dobramundo/input/__init__.py b/dobramundo/input/__init__.py index 8b13789..49f5b66 100644 --- a/dobramundo/input/__init__.py +++ b/dobramundo/input/__init__.py @@ -1 +1,5 @@ +"""Entrada corporal e de supervisão. +Cenas usam a fachada estática ``input.api``; importar ``input.pose`` permanece +independente de pygame e de bibliotecas de câmera. +""" diff --git a/dobramundo/input/api.py b/dobramundo/input/api.py new file mode 100644 index 0000000..59149b0 --- /dev/null +++ b/dobramundo/input/api.py @@ -0,0 +1,11 @@ +"""Interface pública e estática de entrada para cenas e plataformas. + +Não abre câmera nem carrega MediaPipe. Sem importação dinâmica: compatível com +o contrato de módulos portáveis do console T-TEA. +""" + +from .floor import TARGETS, FloorMap +from .hub import FLIGHT_KEYS, InputHub +from .pose import SEGMENTS, BodyControl, FloorControl + +__all__ = ["FLIGHT_KEYS", "SEGMENTS", "TARGETS", "BodyControl", "FloorControl", "FloorMap", "InputHub"] diff --git a/dobramundo/input/hub.py b/dobramundo/input/hub.py index ad88d03..25e1293 100644 --- a/dobramundo/input/hub.py +++ b/dobramundo/input/hub.py @@ -301,9 +301,5 @@ def back_in_area(self) -> bool: return True body = self.body return ( - body is not None - and body.error is None - and body.calibrated - and body.visible - and body.seen_time >= RESUME_S + body is not None and body.error is None and body.calibrated and body.visible and body.seen_time >= RESUME_S ) diff --git a/dobramundo/input/pose.py b/dobramundo/input/pose.py index 85f8bac..da31103 100644 --- a/dobramundo/input/pose.py +++ b/dobramundo/input/pose.py @@ -157,6 +157,7 @@ def set_comfortable_extent(self, direction: str, points: Sequence[Point]) -> boo """Define o extremo confortável por direção, mantendo alcances assimétricos.""" if direction not in self.extents or self.base is None or len(points) < 3: return False + def distance(point: Point) -> float: if direction == "right": return point[0] - self.base[0] @@ -165,6 +166,7 @@ def distance(point: Point) -> float: if direction == "up": return self.base[1] - point[1] return point[1] - self.base[1] + value = median([distance(point) for point in points]) if value < 0.015: return False diff --git a/dobramundo/paths.py b/dobramundo/paths.py index 867e6ff..32d764d 100644 --- a/dobramundo/paths.py +++ b/dobramundo/paths.py @@ -50,13 +50,6 @@ def asset_dir_candidates(name: str) -> List[Path]: return candidates -def find_asset_dir(name: str) -> Optional[Path]: - for path in asset_dir_candidates(name): - if path.is_dir(): - return path - return None - - def find_asset_file(folder: str, filename: str) -> Optional[Path]: for path in asset_dir_candidates(folder): candidate = path / filename @@ -132,3 +125,13 @@ def legacy_data_dirs() -> List[Path]: if not is_frozen(): dirs.insert(0, app_dir() / "save") return dirs + + +def profiles_dir() -> Path: + """Slots adicionais de perfis desktop, sem tocar no perfil do console.""" + return user_data_dir() / "profiles" + + +def profiles_index_path() -> Path: + """Índice local dos slots (IDs aleatórios e slot ativo; sem nomes pessoais).""" + return user_data_dir() / "profiles.json" diff --git a/dobramundo/persistence.py b/dobramundo/persistence.py index dae862c..1a64c23 100644 --- a/dobramundo/persistence.py +++ b/dobramundo/persistence.py @@ -9,7 +9,11 @@ from __future__ import annotations import json +import os +import re +import uuid from dataclasses import asdict, dataclass, field +from datetime import datetime, timezone from pathlib import Path from typing import Dict, List, Optional @@ -28,9 +32,13 @@ ) from .content.progress import MAX_PART_LEVEL, PART_KEYS, VILLAGE_KEYS from .log import log -from .paths import legacy_data_dirs, user_data_dir +from .paths import legacy_data_dirs, profiles_dir, profiles_index_path, user_data_dir PROFILE_FILENAME = "dobramundo_perfil.json" +DEFAULT_PROFILE_SLOT = "principal" +PROFILE_INDEX_VERSION = 1 +PROFILE_SLOT_LIMIT = 8 +_READ_BLOCKED_SLOT_IDS = set() SCHEMA_VERSION = 1 GAME_MODES = ("normal", "dificil") MODE_LABELS = {"normal": "Normal", "dificil": "Difícil"} @@ -66,6 +74,10 @@ class Options: alvo_frente: float = 0.12 # cursor dos pés à frente dos dedos (fração da altura da imagem) permanencia_editor: float = 3.0 escala_contraste: float = 1.3 + modo_exploracao: bool = False + limite_voo_s: int = 0 + assistencia_previsivel: bool = False + semente_desafio: int = 0 @dataclass @@ -128,7 +140,8 @@ def normalize(self) -> Profile: self.padroes_comprados = sorted({p for p in self.padroes_comprados if p in PATTERN_PRICES}) self.vila = [k for k in VILLAGE_KEYS if k in set(self.vila)] self.pedidos_vila = { - str(k): str(v) for k, v in self.pedidos_vila.items() + str(k): str(v) + for k, v in self.pedidos_vila.items() if k in VILLAGE_KEYS and v in ("solicitada", "concluida") } self.pecas = {k: max(0, min(MAX_PART_LEVEL, int(self.pecas.get(k, 0)))) for k in PART_KEYS} @@ -148,6 +161,12 @@ def normalize(self) -> Profile: o.permanencia_editor = max(1.0, min(5.0, float(o.permanencia_editor))) o.escala_contraste = max(1.0, min(1.6, float(o.escala_contraste))) o.sensibilidade = max(0.5, min(2.0, float(o.sensibilidade))) + o.modo_exploracao = o.modo_exploracao if isinstance(o.modo_exploracao, bool) else False + o.limite_voo_s = o.limite_voo_s if type(o.limite_voo_s) is int and o.limite_voo_s in (0, 120, 180, 240) else 0 + o.assistencia_previsivel = o.assistencia_previsivel if isinstance(o.assistencia_previsivel, bool) else False + o.semente_desafio = ( + o.semente_desafio if type(o.semente_desafio) is int and 0 <= o.semente_desafio <= 0xFFFFFFFF else 0 + ) return self # ---------------------------------------------------------------- JSON @@ -169,6 +188,15 @@ def from_dict(cls, data: dict) -> Profile: if isinstance(options, dict): for name in profile.opcoes.__dataclass_fields__: if name in options: + if name in ("modo_exploracao", "assistencia_previsivel"): + if not isinstance(options[name], bool): + continue + elif name == "limite_voo_s": + if type(options[name]) is not int or options[name] not in (0, 120, 180, 240): + continue + elif name == "semente_desafio": + if type(options[name]) is not int or not 0 <= options[name] <= 0xFFFFFFFF: + continue _assign(profile.opcoes, name, options[name]) try: return profile.normalize() @@ -216,18 +244,371 @@ def _assign(target: object, name: str, value: object) -> None: pass -def profile_path() -> Path: - return user_data_dir() / PROFILE_FILENAME +@dataclass(frozen=True) +class ProfileSlot: + id: str + label: str + active: bool = False -def _read_json(path: Path) -> Optional[dict]: +def _valid_slot_id(slot_id: object) -> bool: + return slot_id == DEFAULT_PROFILE_SLOT or ( + isinstance(slot_id, str) and re.fullmatch(r"[0-9a-f]{32}", slot_id) is not None + ) + + +def profile_path(slot_id: str = DEFAULT_PROFILE_SLOT) -> Path: + """Caminho do slot; o principal permanece no arquivo legado para preservar dados.""" + if not _valid_slot_id(slot_id): + raise ValueError("identificador de perfil inválido") + if slot_id == DEFAULT_PROFILE_SLOT: + return user_data_dir() / PROFILE_FILENAME + return profiles_dir() / f"{slot_id}.json" + + +def _atomic_write(path: Path, raw: bytes) -> bool: + temp = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + with temp.open("wb") as stream: + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + temp.replace(path) + return True + except OSError as exc: + log.error("não foi possível gravar %s (%s)", path, exc) + return False + finally: + try: + temp.unlink() + except FileNotFoundError: + pass + except OSError: + log.warning("não foi possível remover o temporário %s", temp) + + +def _archive_corrupt(path: Path) -> Optional[Path]: + if not path.is_file(): + return None + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ") + first_copy = path.with_name(f"{path.stem}.corrompido{path.suffix}") + if not first_copy.exists(): + candidate = first_copy + else: + candidate = path.with_name(f"{path.stem}.corrompido.{stamp}{path.suffix}") + suffix = 1 + while candidate.exists(): + candidate = path.with_name(f"{path.stem}.corrompido.{stamp}.{suffix}{path.suffix}") + suffix += 1 + try: + path.replace(candidate) + return candidate + except OSError as exc: + log.error("não foi possível preservar o arquivo inválido %s (%s)", path, exc) + return None + + +def _backup_paths(path: Path) -> tuple[Path, Path]: + return path.with_name(path.name + ".bak"), path.with_name(path.name + ".bak.1") + + +def _rotate_backup(path: Path, raw: bytes, validator) -> bool: + backup, previous = _backup_paths(path) + if backup.is_file(): + try: + older = backup.read_bytes() + if validator(older) is not None and not _atomic_write(previous, older): + return False + except OSError as exc: + log.error("não foi possível ler o backup %s (%s)", backup, exc) + return False + return _atomic_write(backup, raw) + + +def _decode_json(raw: bytes) -> Optional[dict]: try: - data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): + data = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, ValueError): return None return data if isinstance(data, dict) else None +def _read_json(path: Path) -> Optional[dict]: + try: + return _decode_json(path.read_bytes()) + except OSError: + return None + + +def _profile_from_bytes(raw: bytes) -> Optional[Profile]: + data = _decode_json(raw) + if data is None: + return None + try: + return Profile.from_dict(data) + except (ProfileError, TypeError, ValueError, AttributeError, IndexError): + return None + + +def _registry_from_bytes(raw: bytes) -> Optional[dict]: + data = _decode_json(raw) + if data is None or data.get("version") != PROFILE_INDEX_VERSION: + return None + raw_slots = data.get("slots") + if not isinstance(raw_slots, list): + return None + slots = [] + for slot_id in raw_slots: + if _valid_slot_id(slot_id) and slot_id not in slots: + slots.append(slot_id) + if DEFAULT_PROFILE_SLOT not in slots: + slots.insert(0, DEFAULT_PROFILE_SLOT) + slots = slots[:PROFILE_SLOT_LIMIT] + active = data.get("active") + if active not in slots: + active = DEFAULT_PROFILE_SLOT + return {"version": PROFILE_INDEX_VERSION, "active": active, "slots": slots} + + +def _default_registry() -> dict: + return {"version": PROFILE_INDEX_VERSION, "active": DEFAULT_PROFILE_SLOT, "slots": [DEFAULT_PROFILE_SLOT]} + + +def _discover_profile_slot_ids() -> List[str]: + """Recupera arquivos nomeados por IDs válidos sem escolher nenhum como ativo.""" + found = [] + try: + candidates = profiles_dir().glob("*.json") + for path in candidates: + slot_id = path.stem + if not _valid_slot_id(slot_id) or slot_id == DEFAULT_PROFILE_SLOT: + continue + try: + raw = path.read_bytes() + except OSError: + continue + if _valid_profile_bytes(raw): + found.append(slot_id) + except OSError as exc: + log.warning("não foi possível procurar slots locais órfãos (%s)", exc) + return sorted(set(found))[: PROFILE_SLOT_LIMIT - 1] + + +def _registry_with_notice() -> tuple[dict, Optional[str]]: + path = profiles_index_path() + raw = None + missing = False + read_error = False + try: + raw = path.read_bytes() + except FileNotFoundError: + missing = True + except OSError as exc: + log.error("não foi possível ler o índice de perfis %s (%s)", path, exc) + read_error = True + registry = _registry_from_bytes(raw) if raw is not None else None + if registry is not None: + return registry, None + if not missing and not read_error: + log.warning("índice de perfis inválido: %s", path) + corrupt_copy = _archive_corrupt(path) + if corrupt_copy is None and path.exists(): + read_error = True + for backup in _backup_paths(path): + try: + backup_raw = backup.read_bytes() + except OSError: + continue + registry = _registry_from_bytes(backup_raw) + if registry is None: + continue + restored = _atomic_write(path, backup_raw) + log.warning("índice de perfis recuperado de %s", backup) + notice = "A lista de pilotos foi recuperada de um salvamento anterior." + if not restored: + notice = "Recuperei a lista de pilotos na memória, mas não consegui restaurar o arquivo do índice." + return registry, notice + recovered_slots = _discover_profile_slot_ids() + if recovered_slots: + registry = _default_registry() + registry["slots"].extend(recovered_slots) + notice = "Encontrei pilotos salvos sem a lista principal; confira os cartões antes de continuar." + return registry, notice + if missing and not read_error: + return _default_registry(), None + return _default_registry(), "A lista de pilotos estava danificada; mantive o perfil principal." + + +def list_profile_slots() -> List[ProfileSlot]: + registry, _ = _registry_with_notice() + return [ + ProfileSlot(slot_id, f"Piloto {index + 1}", slot_id == registry["active"]) + for index, slot_id in enumerate(registry["slots"]) + ] + + +def set_active_profile_slot(slot_id: str) -> bool: + registry, _ = _registry_with_notice() + if slot_id not in registry["slots"]: + return False + registry["active"] = slot_id + raw = json.dumps(registry, ensure_ascii=False, indent=2).encode("utf-8") + path = profiles_index_path() + if path.is_file(): + try: + current = path.read_bytes() + except OSError as exc: + log.error("não foi possível ler o índice antes da troca (%s)", exc) + return False + if _registry_from_bytes(current) is None or not _rotate_backup(path, current, _registry_from_bytes): + return False + return _atomic_write(path, raw) + + +def create_profile_slot() -> Optional[ProfileSlot]: + """Cria um slot anônimo com defaults; não altera o perfil ativo.""" + registry, _ = _registry_with_notice() + if len(registry["slots"]) >= PROFILE_SLOT_LIMIT: + return None + slot_id = uuid.uuid4().hex + if not save_profile(Profile(), slot_id): + return None + registry["slots"].append(slot_id) + raw = json.dumps(registry, ensure_ascii=False, indent=2).encode("utf-8") + path = profiles_index_path() + if path.is_file(): + try: + current = path.read_bytes() + except OSError as exc: + log.error("não foi possível ler o índice ao criar perfil (%s)", exc) + return None + if _registry_from_bytes(current) is None or not _rotate_backup(path, current, _registry_from_bytes): + return None + if not _atomic_write(path, raw): + return None + return ProfileSlot(slot_id, f"Piloto {len(registry['slots'])}", False) + + +def _load_profile_with_notice(slot_id: str, allow_legacy: bool) -> tuple[Profile, Optional[str]]: + path = profile_path(slot_id) + existed = path.exists() + try: + raw = path.read_bytes() + except FileNotFoundError: + raw = b"" + except OSError as exc: + log.error("não foi possível ler o perfil %s (%s)", path, exc) + _READ_BLOCKED_SLOT_IDS.add(slot_id) + return Profile(), "Não foi possível ler este perfil. Um perfil vazio foi aberto." + else: + profile = _profile_from_bytes(raw) + if profile is not None: + _READ_BLOCKED_SLOT_IDS.discard(slot_id) + return profile, None + if existed: + log.warning("perfil inválido: %s", path) + corrupt_copy = _archive_corrupt(path) + if corrupt_copy is None and path.exists(): + return Profile(), "O arquivo do perfil está danificado e não pôde ser preservado." + for backup in _backup_paths(path): + try: + backup_raw = backup.read_bytes() + except OSError: + continue + profile = _profile_from_bytes(backup_raw) + if profile is None: + continue + restored = _atomic_write(path, backup_raw) + if restored: + _READ_BLOCKED_SLOT_IDS.discard(slot_id) + else: + _READ_BLOCKED_SLOT_IDS.add(slot_id) + log.warning("perfil recuperado de %s", backup) + notice = "Recuperei o último salvamento íntegro. Confira se o progresso recente aparece." + if not restored: + notice = "Recuperei o último salvamento íntegro na memória, mas não consegui restaurar o arquivo." + return profile, notice + if existed: + notice = "O arquivo do perfil estava danificado; guardei uma cópia. Confira os dados carregados." + else: + notice = ( + "O arquivo deste piloto não foi encontrado; abri um perfil novo." + if slot_id != DEFAULT_PROFILE_SLOT + else None + ) + profile = Profile() + if allow_legacy: + import_legacy(profile) + return profile, notice + + +def load_profile_with_notice(slot_id: str = DEFAULT_PROFILE_SLOT) -> tuple[Profile, Optional[str]]: + if not _valid_slot_id(slot_id): + raise ValueError("identificador de perfil inválido") + return _load_profile_with_notice(slot_id, slot_id == DEFAULT_PROFILE_SLOT) + + +def peek_profile(slot_id: str) -> Optional[Profile]: + """Lê perfil para miniatura sem recuperação, arquivo de aviso ou qualquer escrita.""" + if not _valid_slot_id(slot_id): + return None + try: + raw = profile_path(slot_id).read_bytes() + except OSError: + return None + return _profile_from_bytes(raw) + + +def load_profile() -> Profile: + """Carrega o perfil legado/principal; a interface usa load_active_profile().""" + return load_profile_with_notice(DEFAULT_PROFILE_SLOT)[0] + + +def load_active_profile() -> tuple[Profile, str, Optional[str]]: + registry, registry_notice = _registry_with_notice() + slot_id = registry["active"] + profile, profile_notice = load_profile_with_notice(slot_id) + notices = [notice for notice in (registry_notice, profile_notice) if notice] + return profile, slot_id, " ".join(notices) or None + + +def profile_read_blocked(slot_id: str) -> bool: + """True quando uma leitura falhou nesta sessão e salvar poderia apagar dados.""" + return slot_id in _READ_BLOCKED_SLOT_IDS + + +def _valid_profile_bytes(raw: bytes) -> bool: + return _profile_from_bytes(raw) is not None + + +def save_profile(profile: Profile, slot_id: str = DEFAULT_PROFILE_SLOT) -> bool: + """Grava atomicamente, mantendo duas cópias válidas anteriores quando possível.""" + path = profile_path(slot_id) + if slot_id in _READ_BLOCKED_SLOT_IDS: + log.error("gravação bloqueada: a leitura do perfil %s falhou nesta sessão", slot_id) + return False + try: + raw = json.dumps(profile.to_dict(), ensure_ascii=False, indent=2).encode("utf-8") + except (TypeError, ValueError) as exc: + log.error("perfil não pôde ser serializado (%s)", exc) + return False + if path.is_file(): + try: + previous = path.read_bytes() + except OSError as exc: + log.error("não foi possível ler o perfil antes de salvar %s (%s)", path, exc) + return False + if _valid_profile_bytes(previous): + if not _rotate_backup(path, previous, _profile_from_bytes): + return False + else: + log.warning("preservando perfil inválido antes de salvar: %s", path) + if _archive_corrupt(path) is None: + return False + return _atomic_write(path, raw) + + def import_legacy(profile: Profile) -> bool: """Traz pontos, padrões comprados, pintura e avião do protótipo Eco Runner.""" imported = False @@ -257,36 +638,3 @@ def import_legacy(profile: Profile) -> bool: break profile.normalize() return imported - - -def load_profile() -> Profile: - path = profile_path() - data = _read_json(path) - if data is not None: - try: - return Profile.from_dict(data) - except ProfileError as exc: - log.warning("perfil descartado: %s", exc) - if path.is_file(): # ilegível ou inválido: guarda uma cópia antes de recomeçar o perfil - backup = path.with_name(path.stem + ".corrompido.json") - try: - path.replace(backup) - log.warning("perfil ilegível guardado em %s", backup) - except OSError: - log.error("não foi possível guardar a cópia do perfil ilegível %s", path) - profile = Profile() - import_legacy(profile) - return profile - - -def save_profile(profile: Profile) -> bool: - """Grava de forma atômica (arquivo temporário + troca). False se a pasta não aceitar.""" - path = profile_path() - temp = path.with_suffix(".tmp") - try: - temp.write_text(json.dumps(profile.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8") - temp.replace(path) - return True - except OSError as exc: - log.error("não foi possível gravar o perfil em %s (%s)", path, exc) - return False diff --git a/dobramundo/scenes/__init__.py b/dobramundo/scenes/__init__.py index c14275b..6602698 100644 --- a/dobramundo/scenes/__init__.py +++ b/dobramundo/scenes/__init__.py @@ -28,6 +28,7 @@ def make_scene(app, name: str, *args, **kwargs): from .options import OptionsScene # noqa: E402 from .pilot import PilotScene # noqa: E402 from .preparation import PreparationScene # noqa: E402 +from .profiles import ProfilesScene # noqa: E402 from .projection import ProjectionScene # noqa: E402 from .result import ResultScene # noqa: E402 from .tutorial import DwellPracticeScene, TutorialScene # noqa: E402 @@ -47,6 +48,7 @@ def make_scene(app, name: str, *args, **kwargs): "dwell_treino": DwellPracticeScene, "hangar": HangarScene, "piloto": PilotScene, + "perfis": ProfilesScene, "melhorias": UpgradesScene, "opcoes": OptionsScene, "preparar": PreparationScene, diff --git a/dobramundo/scenes/base.py b/dobramundo/scenes/base.py index 9a89879..339c9ee 100644 --- a/dobramundo/scenes/base.py +++ b/dobramundo/scenes/base.py @@ -35,8 +35,8 @@ def draw(self, screen: pygame.Surface, text: T.Text, center, width: int = 640) - box = pygame.Rect(0, 0, width, 54) box.center = center T.panel(screen, box, T.PAPER, T.ORANGE, 250, 14, 3) - size = T.SIZES["body"] if text.font(T.SIZES["body"], True).size(self.text)[0] < width - 30 else T.SIZES["small"] - text.blit(screen, self.text, box.center, size, T.INK, True, "center") + label, size = T.fit_text(text, self.text, width - 30, bold=True) + text.blit(screen, label, box.center, size, T.INK, True, "center") class Scene: @@ -75,20 +75,16 @@ def back(self) -> None: def fly(self, biome_key: str) -> None: """Decola: voo direto ou, com controle corporal ainda não calibrado, a calibração antes.""" - from . import make_scene - - flight = make_scene(self.app, "voo", biome_key) + flight = self.app.create_scene("voo", biome_key) body = self.app.input.body if body is not None and body.error is None and not body.calibrated: - flight = make_scene(self.app, "calibracao", return_to=flight) + flight = self.app.create_scene("calibracao", return_to=flight) self.app.save() self.app.go(flight) def goto(self, name: str, *args, **kwargs) -> None: """Troca para a cena registrada com esse nome (ver scenes/__init__.py).""" - from . import make_scene - - self.app.go(make_scene(self.app, name, *args, **kwargs)) + self.app.go(self.app.create_scene(name, *args, **kwargs)) def handle_event(self, event: pygame.event.Event) -> None: if event.type == pygame.KEYDOWN and event.key in (pygame.K_ESCAPE, pygame.K_BACKSPACE): @@ -113,6 +109,10 @@ def draw(self, screen: pygame.Surface) -> None: def text(self) -> T.Text: return self.app.text + def font(self, size="body", bold: bool = False, hand: bool = False) -> pygame.font.Font: + """Fonte comum por nome da escala visual ou tamanho explícito.""" + return self.text.font(T.SIZES[size] if isinstance(size, str) else size, bold, hand) + def button(self, rect, label: str, action: Callable[[], None], **kwargs) -> Button: return Button(pygame.Rect(rect), label, action, **kwargs) @@ -130,8 +130,8 @@ def dwell_time(self) -> float: def title(self, screen: pygame.Surface, title: str, subtitle: str = "") -> None: width = ( max( - self.text.font(T.SIZES["title"], True).size(title)[0], - self.text.font(T.SIZES["small"]).size(subtitle)[0], + self.font("title", True).size(title)[0], + self.font("small").size(subtitle)[0], ) + 70 ) diff --git a/dobramundo/scenes/calibration.py b/dobramundo/scenes/calibration.py index 0acd445..4193cb7 100644 --- a/dobramundo/scenes/calibration.py +++ b/dobramundo/scenes/calibration.py @@ -12,7 +12,7 @@ import pygame from .. import config as C -from ..input.pose import SEGMENTS +from ..input.api import SEGMENTS from ..ui import theme as T from ..ui.widgets import ring, row from .base import Scene @@ -42,9 +42,7 @@ def build(self) -> None: self.menu.set_buttons( [ self.button(rects[0], "Reiniciar", self.restart, key="recomecar"), - self.button( - rects[1], "Alcances", self.begin_guided, key="extremos", sublabel="Calibração guiada" - ), + self.button(rects[1], "Alcances", self.begin_guided, key="extremos", sublabel="Calibração guiada"), self.button(rects[2], "Segmento", self.options, key="segmento", sublabel="Trocar"), self.button(rects[3], "Teclado", self.keyboard, key="teclado"), self.button(rects[4], "Continuar", self.finish, key="continuar"), @@ -89,8 +87,10 @@ def capture_guided(self) -> None: self.guided_message = f"Agora mova-se para {labels[self.guided_index]} e confirme com Enter." def handle_event(self, event: pygame.event.Event) -> None: - if self.guided_index >= 0 and event.type == pygame.KEYDOWN and event.key in ( - pygame.K_RETURN, pygame.K_SPACE, pygame.K_KP_ENTER + if ( + self.guided_index >= 0 + and event.type == pygame.KEYDOWN + and event.key in (pygame.K_RETURN, pygame.K_SPACE, pygame.K_KP_ENTER) ): self.capture_guided() return @@ -216,9 +216,7 @@ def draw(self, screen: pygame.Surface) -> None: self.text.blit( screen, diagnostic, (card.centerx, card.bottom - 46), T.SIZES["small"], T.MUTED, anchor="midbottom" ) - self.text.blit( - screen, detail, (card.centerx, card.bottom - 25), T.SIZES["small"], T.MUTED, anchor="midbottom" - ) + self.text.blit(screen, detail, (card.centerx, card.bottom - 25), T.SIZES["small"], T.MUTED, anchor="midbottom") if self.guided_message: self.text.blit( screen, diff --git a/dobramundo/scenes/flight.py b/dobramundo/scenes/flight.py index 5b47eec..13f667f 100644 --- a/dobramundo/scenes/flight.py +++ b/dobramundo/scenes/flight.py @@ -3,6 +3,7 @@ from __future__ import annotations import math +import secrets from typing import Dict, List, Optional, Tuple import pygame @@ -12,7 +13,7 @@ from ..content.biomes import BIOMES from ..content.items import WASTE_TYPES from ..content.planes import load_maneuvers -from ..content.progress import PART_BY_KEY, STAR_THRESHOLDS, parts_ok +from ..content.progress import PART_BY_KEY, STAR_THRESHOLDS, VILLAGE_UPGRADES, parts_ok from ..engine.sprites import project from ..game.run import FlightRun from ..ui import theme as T @@ -64,13 +65,66 @@ def __init__( class FlightScene(Scene): idle_warm_up = False - def __init__(self, app, biome_key: str) -> None: + def __init__( + self, + app, + biome_key: str, + seed: Optional[int] = None, + mode: Optional[str] = None, + session_limit_s: Optional[int] = None, + exploration: Optional[bool] = None, + predictable_assistance: Optional[bool] = None, + intro_override: Optional[bool] = None, + community_challenge: Optional[bool] = None, + mission_preferred_waste: Optional[str] = None, + mission_preference_fixed: bool = False, + ) -> None: super().__init__(app) self.biome = BIOMES[biome_key] p = app.profile # abertura didática: sempre no Normal; no Difícil, só no primeiro voo da fase - intro = p.modo == "normal" or p.voos_fase.get(biome_key, 0) == 0 - self.run = FlightRun(self.biome, p.modo, p.pecas, maneuvers(), intro=intro, focus=app.options.momento_foco) + flight_mode = mode if mode in ("normal", "dificil") else p.modo + intro = ( + intro_override + if intro_override is not None + else flight_mode == "normal" or p.voos_fase.get(biome_key, 0) == 0 + ) + option_seed = app.options.semente_desafio + flight_seed = seed if seed is not None else option_seed if option_seed > 0 else secrets.randbits(32) + limit = app.options.limite_voo_s if session_limit_s is None else session_limit_s + explore = app.options.modo_exploracao if exploration is None else exploration + assisted = app.options.assistencia_previsivel if predictable_assistance is None else predictable_assistance + community = (seed is None and option_seed > 0) if community_challenge is None else community_challenge + if mission_preference_fixed: + preferred_waste = mission_preferred_waste + elif community: + next_build = next((item for item in VILLAGE_UPGRADES if item.key not in p.vila), None) + shortages = ( + { + key: amount - p.recursos.get(key, 0) + for key, amount in next_build.cost.items() + if p.recursos.get(key, 0) < amount + } + if next_build is not None + else {} + ) + preferred_waste = max(shortages, key=shortages.get) if shortages else None + else: + preferred_waste = None + self.run = FlightRun( + self.biome, + flight_mode, + p.pecas, + maneuvers(), + intro=intro, + focus=app.options.momento_foco, + seed=flight_seed, + session_limit_s=limit, + exploration=explore, + predictable_assistance=assisted, + community_challenge=community, + mission_preferred_waste=preferred_waste, + ) self.look = app.plane_look() self.paused = False self.auto_paused = False @@ -97,7 +151,12 @@ def enter(self) -> None: if not self.started: self.started = True self.app.audio.play("sfx_decolagem") - self.banners.append(Banner(f"{self.biome.city} — {self.biome.name}", texts.STAGE_MESSAGES[0], T.WHITE, 3.2)) + theme = self.run.world.challenge_theme + title = theme.title if theme is not None else f"{self.biome.city} — {self.biome.name}" + subtitle = ( + f"Desafio comunitário · semente {self.run.seed}" if theme is not None else texts.STAGE_MESSAGES[0] + ) + self.banners.append(Banner(title, subtitle, T.WHITE, 3.2)) # ------------------------------------------------------------- pausa def build(self) -> None: @@ -116,6 +175,7 @@ def pause(self, auto: bool = False) -> None: if self.paused or self.run.finished: return self.paused = True + self.run.pause_count += 1 self.auto_paused = auto self.countdown = 0.0 self.app.input.clear_keys() @@ -186,6 +246,7 @@ def update(self, dt: float) -> None: if not self.paused and hub.out_of_area(): self.pause(auto=True) if self.paused: + self.run.pause_duration_s += max(0.0, dt) if self.auto_paused and hub.back_in_area(): self.countdown += dt # retomada automática com contagem if self.countdown >= RESUME_COUNTDOWN: @@ -262,9 +323,21 @@ def handle_run_events(self) -> None: data.kind, "star" ) self.banners.append(Banner("Meta cumprida!", data.text(data.target), T.SUN, 2.4, action=action)) + elif name == "mission_expired": + self.banners.append( + Banner("Outra meta vem aí", "Esta não deu; nenhum recurso foi perdido.", T.TEAL, 2.4) + ) elif name == "complete": audio.play("sfx_fim_fase") self.banners.append(Banner(f"{self.biome.city} solarpunk!", "A cidade se transformou.", T.SUN, 3.0)) + elif name == "session_end": + self.banners.append( + Banner("Tempo combinado", "O voo ficou guardado para continuar depois.", T.TEAL, 2.5) + ) + elif name == "exploration_continue": + self.banners.append( + Banner("Vamos continuar", "No modo Explorar, as batidas não encerram o voo.", T.TEAL, 2.2) + ) elif name == "game_over": audio.play("sfx_game_over") @@ -321,11 +394,37 @@ def draw_hud(self, screen: pygame.Surface) -> None: star( screen, (x, bar.centery), 11, run.restoration >= limit - 1e-6 and (limit < 100 or run.stars >= 3), T.SUN ) + if run.session_limit_s: + clock = max(0, run.session_limit_s - int(run.flight_time)) + minutes, seconds = divmod(clock, 60) + timer_box = pygame.Rect(C.WIDTH // 2 - 62, 14, 124, 56) + T.panel(screen, timer_box, T.PAPER, T.TEAL, 245, 14, 2) + text.blit( + screen, "TEMPO", (timer_box.centerx, timer_box.top + 7), T.SIZES["small"], T.MUTED, True, "midtop" + ) + text.blit( + screen, + f"{minutes:02d}:{seconds:02d}", + (timer_box.centerx, timer_box.top + 28), + T.SIZES["label"], + T.NAVY, + True, + "midtop", + ) self.draw_mission(screen) - status = pygame.Rect(C.WIDTH - 164, 14, 146, 70) + status = pygame.Rect(C.WIDTH - 244, 14, 226, 70) T.panel(screen, status, T.PAPER, T.NAVY, 238, 16, 2) - for i in range(C.MAX_LIVES): - self.draw_life(screen, (status.left + 32 + i * 41, 48), i < run.lives) + spacing = 39 + start_x = status.left + (status.width - (run.max_lives - 1) * spacing) // 2 + life_y = 40 if run.exploration or run.predictable_assistance else 48 + for i in range(run.max_lives): + self.draw_life(screen, (start_x + i * spacing, life_y), i < run.lives) + label_anchor = (status.centerx, status.bottom - 24) + if run.exploration: + label = "EXPLORAR" + (" · APOIO" if run.predictable_assistance else "") + text.blit(screen, label, label_anchor, T.SIZES["small"], T.TEAL, True, "midtop") + elif run.predictable_assistance: + text.blit(screen, "APOIO", label_anchor, T.SIZES["small"], T.TEAL, True, "midtop") if run.shield_timer > 0 or run.magnet_timer > 0: # Ambos os benefícios têm um relógio visual próprio. A leitura de # segundos é auxiliar; o arco se esvazia sem piscar. @@ -338,8 +437,7 @@ def draw_hud(self, screen: pygame.Surface) -> None: pygame.draw.circle(screen, T.NAVY, center, 27, 2) screen.blit(T.icon_surface(active, 30, T.NAVY), (center[0] - 15, center[1] - 15)) arc = pygame.Rect(center[0] - 23, center[1] - 23, 46, 46) - pygame.draw.arc(screen, T.TEAL, arc, math.pi / 2, - math.pi / 2 + math.tau * min(1.0, timer / total), 5) + pygame.draw.arc(screen, T.TEAL, arc, math.pi / 2, math.pi / 2 + math.tau * min(1.0, timer / total), 5) elif run.invincible: text.blit( screen, @@ -365,9 +463,13 @@ def draw_focus(self, screen: pygame.Surface) -> None: pygame.draw.circle(screen, T.PAPER, center, 26) pygame.draw.circle(screen, T.NAVY, center, 26, 3) if ok: - pygame.draw.lines(screen, T.TEAL, False, - [(center[0] - 13, center[1]), (center[0] - 3, center[1] + 10), - (center[0] + 15, center[1] - 12)], 6) + pygame.draw.lines( + screen, + T.TEAL, + False, + [(center[0] - 13, center[1]), (center[0] - 3, center[1] + 10), (center[0] + 15, center[1] - 12)], + 6, + ) else: screen.blit(T.icon_surface("plane", 36, T.NAVY), (center[0] - 18, center[1] - 18)) self.text.blit( diff --git a/dobramundo/scenes/hangar.py b/dobramundo/scenes/hangar.py index 6cceeb9..3b2a378 100644 --- a/dobramundo/scenes/hangar.py +++ b/dobramundo/scenes/hangar.py @@ -210,8 +210,13 @@ def choose_pattern(self, key: str) -> None: # ------------------------------------------------------------ desenho def draw(self, screen: pygame.Surface) -> None: - app = self.app - profile = app.profile + self._draw_header(screen) + self._draw_plane_preview(screen) + self._draw_selection(screen) + self.toast.draw(screen, self.text, (C.WIDTH // 2 + 120, 600)) + + def _draw_header(self, screen: pygame.Surface) -> None: + profile = self.app.profile T.watercolor_backdrop(screen, "sky") self.title(screen, "Hangar de papel") wallet_box = pygame.Rect(C.WIDTH - 254, 18, 226, 50) @@ -226,6 +231,10 @@ def draw(self, screen: pygame.Surface) -> None: True, "midleft", ) + + def _draw_plane_preview(self, screen: pygame.Surface) -> None: + app = self.app + profile = app.profile card = pygame.Rect(24, 84, 516, 472) T.panel(screen, card, T.PAPER, T.NAVY, 250, 22, 2) skin = app.view.skin @@ -275,6 +284,9 @@ def draw(self, screen: pygame.Surface) -> None: screen, "desviar", (card.left + 176, card.bottom - 48), T.SIZES["small"], T.INK, anchor="midleft" ) + def _draw_selection(self, screen: pygame.Surface) -> None: + profile = self.app.profile + skin = self.app.view.skin self.text.blit( screen, dict(TABS)[self.tab], @@ -312,8 +324,7 @@ def draw(self, screen: pygame.Surface) -> None: else: self.text.blit(screen, "Liso", image_rect.center, T.SIZES["small"], T.INK, True, "center") label = pattern_label(key) - if self.text.font(T.SIZES["small"], True).size(label)[0] > button.rect.width - 12: - label = label[:17] + "…" + label = T.elide_text(label, self.font("small", True), button.rect.width - 12) self.text.blit( screen, label, @@ -343,4 +354,3 @@ def draw(self, screen: pygame.Surface) -> None: True, "center", ) - self.toast.draw(screen, self.text, (C.WIDTH // 2 + 120, 600)) diff --git a/dobramundo/scenes/intro.py b/dobramundo/scenes/intro.py index e07d772..5074165 100644 --- a/dobramundo/scenes/intro.py +++ b/dobramundo/scenes/intro.py @@ -19,6 +19,15 @@ from .. import config as C from ..content import texts +from ..content.story import ( + LAUNCH_CAPTION_S, + LAUNCH_FADE_S, + LAUNCH_GLIDE_S, + LOGO_APPEAR_S, + LOGO_FADE_S, + PAGE_DURATIONS, + PAGE_TURN_S, +) from ..engine import paper from ..ui import theme as T from ..util import clamp, lerp, lerp_color, rgb, smoothstep @@ -49,8 +58,8 @@ "flap_r": [(1.05, 0.55), (0, -0.85), (0.16, 0.42)], }, ] -PAGES = (3.4, 4.2, 6.2, 5.2) # duração de cada página (s) -TURN_S = 0.45 # virada de página +PAGES = PAGE_DURATIONS +TURN_S = PAGE_TURN_S SHEET_SCALE = 190 CHILD_FEET = (300, 560) HANDS = (335, 405) # onde as mãos da criança seguram a folha (página 2) @@ -317,7 +326,7 @@ def draw(self, screen: pygame.Surface) -> None: self.draw_child(screen, "menu", (150, 600), (220, 280), expression="focused") self.caption(screen, texts.INTRO_CAPTIONS[2], FOLD_STEPS[step]) else: - launch_alpha = 255 if reduced_motion else int(255 * clamp((PAGES[3] - t) / 0.6, 0.0, 1.0)) + launch_alpha = 255 if reduced_motion else int(255 * clamp((PAGES[3] - t) / LAUNCH_FADE_S, 0.0, 1.0)) self.draw_child( screen, # A animação do avião no céu é o gesto do lançamento; omite a @@ -327,7 +336,7 @@ def draw(self, screen: pygame.Surface) -> None: alpha=launch_alpha, expression="happy", ) - u = 1.0 if reduced_motion else smoothstep(t / 3.2) + u = 1.0 if reduced_motion else smoothstep(t / LAUNCH_GLIDE_S) x = lerp(440, C.WIDTH - 140, u) y = lerp(360, 120, u) - (0 if reduced_motion else math.sin(u * math.pi) * 90) if not self.trail or (abs(self.trail[-1][0] - x) > 6): @@ -353,11 +362,11 @@ def draw(self, screen: pygame.Surface) -> None: paper.sparkles( screen, pygame.Rect(0, 80, C.WIDTH, 400), elapsed_total, clamp((t - 1.5) / 2.0, 0.0, 1.0), T.SUN ) - self.caption(screen, texts.INTRO_CAPTIONS[4] if t > 2.4 else texts.INTRO_CAPTIONS[3]) - if t > 2.6: + self.caption(screen, texts.INTRO_CAPTIONS[4] if t > LAUNCH_CAPTION_S else texts.INTRO_CAPTIONS[3]) + if t > LOGO_APPEAR_S: logo = self.app.assets.sprite("ui", "logo") if logo is not None: - alpha = clamp((t - 2.6) / 1.0, 0.0, 1.0) + alpha = clamp((t - LOGO_APPEAR_S) / LOGO_FADE_S, 0.0, 1.0) img = self.scaled(logo, (520, 291)) img.set_alpha(int(255 * alpha)) screen.blit(img, img.get_rect(center=(C.WIDTH // 2, 250))) diff --git a/dobramundo/scenes/map.py b/dobramundo/scenes/map.py index 24c7b63..95e5345 100644 --- a/dobramundo/scenes/map.py +++ b/dobramundo/scenes/map.py @@ -151,18 +151,36 @@ def _part_icon(key: str, size: int = 36) -> pygame.Surface: pygame.draw.circle(icon, T.PAPER, (center, center), center - 1) pygame.draw.circle(icon, T.TEAL, (center, center), center - 1, 2) if key == "estabilizador": - shape = [(4, center - 3), (center - 3, 7), (center + 3, 7), (size - 4, center - 3), - (center + 4, center + 5), (center - 4, center + 5)] + shape = [ + (4, center - 3), + (center - 3, 7), + (center + 3, 7), + (size - 4, center - 3), + (center + 4, center + 5), + (center - 4, center + 5), + ] pygame.draw.polygon(icon, T.NAVY, shape) pygame.draw.line(icon, T.WHITE, (center, 9), (center, size - 9), 2) elif key == "leme": - shape = [(center - 4, size - 6), (center - 4, center - 1), (center - 8, 8), - (center + 8, 8), (center + 4, center - 1), (center + 4, size - 6)] + shape = [ + (center - 4, size - 6), + (center - 4, center - 1), + (center - 8, 8), + (center + 8, 8), + (center + 4, center - 1), + (center + 4, size - 6), + ] pygame.draw.polygon(icon, T.NAVY, shape) pygame.draw.polygon(icon, T.ORANGE, [(center + 4, 11), (size - 6, 7), (center + 4, 19)]) else: # quilha: a lâmina vertical no centro do avião - shape = [(center, 5), (center + 7, center - 2), (center + 4, size - 6), - (center, size - 11), (center - 4, size - 6), (center - 7, center - 2)] + shape = [ + (center, 5), + (center + 7, center - 2), + (center + 4, size - 6), + (center, size - 11), + (center - 4, size - 6), + (center - 7, center - 2), + ] pygame.draw.polygon(icon, T.NAVY, shape) pygame.draw.line(icon, T.WHITE, (center, 9), (center, size - 12), 2) pygame.draw.line(icon, T.ORANGE, (center - 9, center + 4), (center + 9, center + 4), 2) @@ -259,26 +277,33 @@ def set_mode(self, mode: str) -> None: self.build() def start(self, key: str) -> None: - from . import make_scene - - flight = make_scene(self.app, "voo", key) + flight = self.app.create_scene("voo", key) if not self.app.profile.tutorial_visto: - tutorial = make_scene( - self.app, + tutorial = self.app.create_scene( "tutorial", next_scene=flight, - return_to=make_scene(self.app, "mapa"), + return_to=self.app.create_scene("mapa"), ) flight = tutorial body = self.app.input.body if body is not None and body.error is None and not body.calibrated: - flight = make_scene(self.app, "calibracao", return_to=flight) + flight = self.app.create_scene("calibracao", return_to=flight) self.app.save() self.app.go(flight) def draw(self, screen: pygame.Surface) -> None: focused = self.menu.focused key = focused.key if focused is not None and focused.key in BIOMES else BIOME_ORDER[0] + self._draw_geography(screen, key) + self.title(screen, "Mapa dos biomas", "Escolha o destino e o ritmo do voo") + self.text.blit(screen, "Ritmo", (642, 68), T.SIZES["small"], T.WHITE, True) + self.menu.draw(screen, self.text, self.app.options.permanencia) + self._draw_destinations(screen) + self._draw_future_biomes(screen) + self._draw_speed_cues(screen) + self.menu.draw_pointer(screen, self.dwell_time, self.app.input.body_pointer() is not None) + + def _draw_geography(self, screen: pygame.Surface, key: str) -> None: self.app.backdrop(screen, self.last_dt, key, 5.0) T.veil(screen, (10, 18, 40), 110) T.panel(screen, MAP_RECT.inflate(20, 20), T.PAPER, T.NAVY, 240, 22, 3) @@ -306,9 +331,8 @@ def draw(self, screen: pygame.Surface) -> None: self.text.blit(screen, biome.city, (x + 18, y - 14), T.SIZES["label"], T.NAVY_DARK, True) for i in range(3): star(screen, (x + 30 + i * 22, y + 26), 10, i < self.app.profile.estrelas.get(k, 0)) - self.title(screen, "Mapa dos biomas", "Escolha o destino e o ritmo do voo") - self.text.blit(screen, "Ritmo", (642, 68), T.SIZES["small"], T.WHITE, True) - self.menu.draw(screen, self.text, self.app.options.permanencia) + + def _draw_destinations(self, screen: pygame.Surface) -> None: for key_city in BIOME_ORDER: biome = BIOMES[key_city] button = next(b for b in self.menu.buttons if b.key == key_city) @@ -385,6 +409,8 @@ def draw(self, screen: pygame.Surface) -> None: "midleft", ) x += 70 + + def _draw_future_biomes(self, screen: pygame.Surface) -> None: # Os biomas futuros ficam em duas colunas dentro de um painel legível. legend = pygame.Rect(635, 530, 440, 94) T.panel(screen, legend, T.PAPER, T.NAVY, 242, 14, 2) @@ -395,10 +421,11 @@ def draw(self, screen: pygame.Surface) -> None: cy = 563 + row * 29 pygame.draw.circle(screen, locked.color, (cx, cy + 8), 7) self.text.blit(screen, locked.name, (cx + 14, cy), T.SIZES["small"], T.INK, True) + + def _draw_speed_cues(self, screen: pygame.Surface) -> None: for mode, _, _, color, arrows in MODE_CARDS: button = next(b for b in self.menu.buttons if b.key == f"modo_{mode}") for k in range(arrows): # setas de velocidade: 1 no Normal, 3 no Difícil x = button.rect.centerx - arrows * 11 + k * 22 y = button.rect.bottom - 18 pygame.draw.polygon(screen, color, [(x, y - 10), (x + 14, y), (x, y + 10)]) - self.menu.draw_pointer(screen, self.app.options.permanencia, self.app.input.body_pointer() is not None) diff --git a/dobramundo/scenes/options.py b/dobramundo/scenes/options.py index 8f80499..4543a54 100644 --- a/dobramundo/scenes/options.py +++ b/dobramundo/scenes/options.py @@ -8,10 +8,9 @@ from .. import config as C from ..content import texts -from ..input.pose import SEGMENTS +from ..input.api import SEGMENTS from ..persistence import CONTROL_SEGMENTS, SURFACES from ..ui import theme as T -from . import make_scene from .base import Scene SEGMENT_LABELS = {"teclado": "Teclado e mouse", **{k: s.label for k, s in SEGMENTS.items()}} @@ -30,44 +29,52 @@ class OptionsScene(Scene): def build(self) -> None: - o = self.app.options - profile = self.app.profile - left, right = 24, 566 - width = 510 buttons = [] + self._build_controls(buttons) + self._build_surface(buttons) + self._build_audio(buttons) + self._build_accessibility(buttons) + self._build_footer(buttons) + self.menu.set_buttons(buttons) - def stepper( - x: int, y: int, key: str, label: str, value: str, minus: Callable, plus: Callable, w: int = width - ) -> None: - arrow = min(48, max(38, w // 5)) - buttons.append(self.button((x, y, arrow, ROW_H), "<", minus, key=f"{key}-")) - buttons.append( - self.button( - (x + arrow + 4, y, w - 2 * arrow - 8, ROW_H), - value, - plus, - sublabel=label, - size=T.SIZES["body"], - key=f"{key}=", - ) + def _stepper( + self, buttons, x: int, y: int, key: str, label: str, value: str, minus: Callable, plus: Callable, w: int = 510 + ) -> None: + arrow = min(48, max(38, w // 5)) + buttons.append(self.button((x, y, arrow, ROW_H), "<", minus, key=f"{key}-")) + buttons.append( + self.button( + (x + arrow + 4, y, w - 2 * arrow - 8, ROW_H), + value, + plus, + sublabel=label, + size=T.SIZES["body"], + key=f"{key}=", ) - buttons.append(self.button((x + w - arrow, y, arrow, ROW_H), ">", plus, key=f"{key}+")) + ) + buttons.append(self.button((x + w - arrow, y, arrow, ROW_H), ">", plus, key=f"{key}+")) - def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: int = width) -> None: - buttons.append( - self.button( - (x, y, w, ROW_H), - f"{label}: {'sim' if on else 'não'}", - action, - selected=on, - size=T.SIZES["body"], - key=key, - ) + def _toggle(self, buttons, x: int, y: int, key: str, label: str, on: bool, action: Callable, w: int = 510) -> None: + buttons.append( + self.button( + (x, y, w, ROW_H), + f"{label}: {'sim' if on else 'não'}", + action, + selected=on, + size=T.SIZES["body"], + key=key, ) + ) + def _build_controls(self, buttons) -> None: + o = self.app.options + left, width = 24, 510 + half = (width - GAP) // 2 + profile = self.app.profile y = 128 index = CONTROL_SEGMENTS.index(profile.controle) - stepper( + self._stepper( + buttons, left, y, "seg", @@ -101,7 +108,8 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: ) ) y += ROW_H + GAP - stepper( + self._stepper( + buttons, left, y, "sens", @@ -111,7 +119,8 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: lambda: self.adjust("sensibilidade", 0.1, 0.5, 2.0), ) y += ROW_H + GAP - stepper( + self._stepper( + buttons, left, y, "perm", @@ -121,7 +130,8 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: lambda: self.adjust("permanencia", 0.25, 1.0, 3.5), half, ) - stepper( + self._stepper( + buttons, left + half + GAP, y, "perm_editor", @@ -132,8 +142,15 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: half, ) y += ROW_H + GAP + + def _build_surface(self, buttons) -> None: + o = self.app.options + left, width = 24, 510 + half = (width - GAP) // 2 + y = 128 + 4 * (ROW_H + GAP) s_index = SURFACES.index(o.superficie) - stepper( + self._stepper( + buttons, left, y, "sup", @@ -155,7 +172,8 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: sublabel=f"Girar {o.rotacao}°" + (", espelhada" if o.espelhar else ""), ) ) - toggle( + self._toggle( + buttons, left + half + GAP, y, "centralizar", @@ -165,7 +183,21 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: half, ) y += ROW_H + GAP - toggle(left, y, "foco", "Momento de foco (câmera lenta)", o.momento_foco, lambda: self.flip("momento_foco")) + self._toggle( + buttons, + left, + y, + "foco", + "Momento de foco (câmera lenta)", + o.momento_foco, + lambda: self.flip("momento_foco"), + ) + + def _build_audio(self, buttons) -> None: + o = self.app.options + right, width = 566, 510 + half = (width - GAP) // 2 + desktop = self.app.platform == "desktop" y = 128 for key, label in ( ("volume_geral", "Volume geral"), @@ -173,7 +205,8 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: ("volume_efeitos", "Efeitos"), ): value = vars(o)[key] - stepper( + self._stepper( + buttons, right, y, key, @@ -183,11 +216,20 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: (lambda k=key: self.adjust(k, 0.1, 0.0, 1.0)), ) y += ROW_H + GAP - toggle(right, y, "silencio", texts.UI["silencio"], o.silencio, lambda: self.flip("silencio"), half) + self._toggle( + buttons, right, y, "silencio", texts.UI["silencio"], o.silencio, lambda: self.flip("silencio"), half + ) if desktop: - toggle(right + half + GAP, y, "tela", "Tela cheia", o.tela_cheia, self.fullscreen, half) + self._toggle(buttons, right + half + GAP, y, "tela", "Tela cheia", o.tela_cheia, self.fullscreen, half) y += ROW_H + GAP - toggle( + + def _build_accessibility(self, buttons) -> None: + o = self.app.options + right, width = 566, 510 + half = (width - GAP) // 2 + y = 128 + 4 * (ROW_H + GAP) + self._toggle( + buttons, right, y, "contraste", @@ -196,18 +238,30 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: lambda: self.flip("alto_contraste"), half, ) - stepper( - right + half + GAP, y, "escala_contraste", "Escala de contraste", + self._stepper( + buttons, + right + half + GAP, + y, + "escala_contraste", + "Escala de contraste", f"{o.escala_contraste:.1f}x", lambda: self.adjust("escala_contraste", -0.1, 1.0, 1.6), lambda: self.adjust("escala_contraste", 0.1, 1.0, 1.6), half, ) y += ROW_H + GAP - toggle( - right, y, "inverter", "Trocar cima/baixo", o.inverter_vertical, lambda: self.flip("inverter_vertical"), half + self._toggle( + buttons, + right, + y, + "inverter", + "Trocar cima/baixo", + o.inverter_vertical, + lambda: self.flip("inverter_vertical"), + half, ) - toggle( + self._toggle( + buttons, right + half + GAP, y, "inverter_lados", @@ -217,7 +271,8 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: half, ) y += ROW_H + GAP - toggle( + self._toggle( + buttons, right, y, "efeitos", @@ -225,6 +280,10 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: o.efeitos_fortes, lambda: self.flip("efeitos_fortes"), ) + + def _build_footer(self, buttons) -> None: + o = self.app.options + width = 510 footer = ( (texts.UI["voltar"], lambda: self.goto("vila"), "voltar"), ("História", self.intro, "abertura"), @@ -242,15 +301,26 @@ def toggle(x: int, y: int, key: str, label: str, on: bool, action: Callable, w: icon=T.icon_surface("stabilizer", 28, T.GREEN) if key == "preparar" else None, ) ) - toggle( - 24, 562, "movimento", "Movimento reduzido", o.reduzir_movimento, - lambda: self.flip("reduzir_movimento"), width, + self._toggle( + buttons, + 24, + 562, + "movimento", + "Movimento reduzido", + o.reduzir_movimento, + lambda: self.flip("reduzir_movimento"), + width, ) - toggle( - 566, 562, "auto_abertura", "Abertura automática", o.abertura_automatica, - lambda: self.flip("abertura_automatica"), width, + self._toggle( + buttons, + 566, + 562, + "auto_abertura", + "Abertura automática", + o.abertura_automatica, + lambda: self.flip("abertura_automatica"), + width, ) - self.menu.set_buttons(buttons) # ------------------------------------------------------------ ações def changed(self) -> None: @@ -291,18 +361,18 @@ def fullscreen(self) -> None: self.changed() def calibrate(self) -> None: - self.goto("calibracao", return_to=make_scene(self.app, "opcoes")) + self.goto("calibracao", return_to=self.app.create_scene("opcoes")) def intro(self) -> None: self.goto("abertura") def replay_tutorial(self) -> None: - return_to = make_scene(self.app, "opcoes") - self.goto("tutorial", next_scene=return_to, return_to=make_scene(self.app, "opcoes")) + return_to = self.app.create_scene("opcoes") + self.goto("tutorial", next_scene=return_to, return_to=self.app.create_scene("opcoes")) def replay_dwell(self) -> None: - return_to = make_scene(self.app, "opcoes") - self.goto("dwell_treino", next_scene=return_to, return_to=make_scene(self.app, "opcoes")) + return_to = self.app.create_scene("opcoes") + self.goto("dwell_treino", next_scene=return_to, return_to=self.app.create_scene("opcoes")) def prepare(self) -> None: self.goto("preparar") diff --git a/dobramundo/scenes/preparation.py b/dobramundo/scenes/preparation.py index 40d5cc7..48e4d7f 100644 --- a/dobramundo/scenes/preparation.py +++ b/dobramundo/scenes/preparation.py @@ -6,14 +6,20 @@ from .. import config as C from ..ui import theme as T -from . import make_scene from .base import Scene class PreparationScene(Scene): """Presets persistentes, calibragem e rotas rápidas para a supervisão.""" + def __init__(self, app) -> None: + super().__init__(app) + self.page = "main" + def build(self) -> None: + if self.page == "meu_voo": + self._build_my_flight() + return o = self.app.options body = self.app.input.body can_calibrate = body is not None and body.error is None @@ -28,9 +34,8 @@ def build(self) -> None: ) buttons = [] for rect, label, detail, action, key in cards: - selected = ( - (key == "calmo" and o.reduzir_movimento and not o.efeitos_fortes) - or (key == "visivel" and o.alto_contraste and o.escala_contraste >= 1.3) + selected = (key == "calmo" and o.reduzir_movimento and not o.efeitos_fortes) or ( + key == "visivel" and o.alto_contraste and o.escala_contraste >= 1.3 ) buttons.append( self.button( @@ -55,16 +60,103 @@ def build(self) -> None: ), self.button( (389, 500, 322, 58), - "Seleção", + "Meu voo", + self.open_my_flight, + key="meu_voo", + icon=T.icon_surface("plane", 34, T.NAVY), + ), + self.button( + (744, 500, 152, 58), + "Mirar", self.practice_selection, - key="selecao", + key="mirar", icon=T.icon_surface("next", 34, T.NAVY), ), - self.button((744, 500, 322, 58), "Opções", self.back, key="opcoes"), + self.button((929, 500, 137, 58), "Opções", self.back, key="opcoes"), ] ) self.menu.set_buttons(buttons) + def _build_my_flight(self) -> None: + o = self.app.options + durations = C.SESSION_LIMITS_S + duration_index = durations.index(o.limite_voo_s) if o.limite_voo_s in durations else 0 + duration = durations[duration_index] + duration_label = "Sem limite" if not duration else f"{duration // 60} minutos" + seeds = (0,) + C.COMMUNITY_CHALLENGE_SEEDS + seed_index = seeds.index(o.semente_desafio) if o.semente_desafio in seeds else -1 + seed = o.semente_desafio if seed_index < 0 else seeds[seed_index] + challenge_label = ( + "Voo aleatório" + if seed == 0 + else f"Desafio comunitário {seed_index} · semente {seed}" + if seed_index >= 0 + else f"Semente personalizada · {seed}" + ) + buttons = [ + self.button( + (34, 160, 332, 230), + duration_label, + lambda: self.set_option("limite_voo_s", durations[(duration_index + 1) % len(durations)]), + sublabel="Mire para escolher", + size=T.SIZES["title"], + key="duracao_voo", + icon=T.icon_surface("clock", 58, T.TEAL), + ), + self.button( + (384, 160, 332, 230), + "Explorar" if o.modo_exploracao else "Com vidas", + lambda: self.set_option("modo_exploracao", not o.modo_exploracao), + sublabel="Sem eliminação · batidas contam" if o.modo_exploracao else "Vidas normais · 3 corações", + size=T.SIZES["title"], + key="exploracao", + selected=o.modo_exploracao, + icon=T.icon_surface("village", 58, T.GREEN if o.modo_exploracao else T.NAVY), + ), + self.button( + (734, 160, 332, 230), + "Com apoio" if o.assistencia_previsivel else "Sem apoio", + lambda: self.set_option("assistencia_previsivel", not o.assistencia_previsivel), + sublabel="5 vidas · proteção de 2 s" if o.assistencia_previsivel else "3 vidas · proteção de 1,25 s", + size=T.SIZES["body"], + key="assistencia", + selected=o.assistencia_previsivel, + icon=T.icon_surface("shield", 58, T.TEAL if o.assistencia_previsivel else T.NAVY), + ), + self.button( + (34, 418, 700, 132), + challenge_label, + lambda: self.set_option("semente_desafio", seeds[(seed_index + 1) % len(seeds)]), + sublabel="Próximo desafio · a região vem do mapa", + size=T.SIZES["title"], + key="desafio_comunitario", + icon=T.icon_surface("portal", 50, T.ORANGE), + ), + self.button((750, 418, 316, 132), "Voltar", self.open_main, key="voltar"), + ] + self.menu.set_buttons(buttons) + + def set_option(self, name: str, value) -> None: + if name == "limite_voo_s": + self.app.options.limite_voo_s = int(value) + elif name == "modo_exploracao": + self.app.options.modo_exploracao = bool(value) + elif name == "assistencia_previsivel": + self.app.options.assistencia_previsivel = bool(value) + elif name == "semente_desafio": + self.app.options.semente_desafio = int(value) + else: + raise ValueError(f"opção de voo desconhecida: {name}") + self._save_preset("Preferências do voo salvas") + + def open_my_flight(self) -> None: + self.page = "meu_voo" + self.build() + + def open_main(self) -> None: + self.page = "main" + self.build() + def back(self) -> None: self.goto("opcoes") @@ -98,21 +190,25 @@ def calibrate(self) -> None: if body is None or body.error is not None: self.open_options() return - self.goto("calibracao", return_to=make_scene(self.app, "preparar"), guided=True) + self.goto("calibracao", return_to=self.app.create_scene("preparar"), guided=True) def practice_selection(self) -> None: self.goto( "dwell_treino", - next_scene=make_scene(self.app, "preparar"), - return_to=make_scene(self.app, "preparar"), + next_scene=self.app.create_scene("preparar"), + return_to=self.app.create_scene("preparar"), ) def draw(self, screen: pygame.Surface) -> None: self.app.backdrop(screen, self.last_dt, None, 20.0) T.veil(screen, (10, 18, 40), 150) - self.title(screen, "Preparar", "Atalhos para ajustar a experiência") + if self.page == "meu_voo": + self.title(screen, "Meu voo", "Escolhas previsíveis para esta aventura") + else: + self.title(screen, "Preparar", "Atalhos para ajustar a experiência") self.draw_menu(screen) - self._draw_icons(screen) + if self.page == "main": + self._draw_icons(screen) self.toast.draw(screen, self.text, (C.WIDTH // 2, 614), 520) def _draw_icons(self, screen: pygame.Surface) -> None: diff --git a/dobramundo/scenes/profiles.py b/dobramundo/scenes/profiles.py new file mode 100644 index 0000000..f0c055b --- /dev/null +++ b/dobramundo/scenes/profiles.py @@ -0,0 +1,139 @@ +"""Seleção local de pilotos anônimos para computadores compartilhados.""" + +from __future__ import annotations + +import math + +import pygame + +from .. import config as C +from ..engine.paper_pilot import draw_pilot +from ..persistence import PROFILE_SLOT_LIMIT, peek_profile +from ..ui import theme as T +from ..util import rgb +from .base import Scene + +_BADGE_COLORS = ( + rgb("eeaa58"), + rgb("4fae9b"), + rgb("7e8ecf"), + rgb("d8758e"), + rgb("87aa58"), + rgb("a57bc5"), + rgb("cf8848"), + rgb("4c9bc2"), +) + + +def _pilot_badge(profile, index: int, active: bool, painted=None) -> pygame.Surface: + badge = pygame.Surface((96, 112), pygame.SRCALPHA) + color = _BADGE_COLORS[index % len(_BADGE_COLORS)] + pygame.draw.ellipse(badge, (color[0], color[1], color[2], 90), (8, 4, 80, 104)) + # O anel pontilhado identifica o slot mesmo quando o avatar ainda não foi montado. + for angle in range(index % 4, 360, 45): + x = 48 + int(43 * math.cos(math.radians(angle))) + y = 54 + int(53 * math.sin(math.radians(angle))) + pygame.draw.circle(badge, color, (x, y), 3 + (1 if angle // 45 == index % 8 else 0)) + if profile is not None: + portrait = painted if painted is not None else draw_pilot("menu", profile.piloto) + badge.blit(pygame.transform.smoothscale(portrait, (72, 96)), (12, 8)) + else: + pygame.draw.circle(badge, color, (48, 40), 15) + pygame.draw.ellipse(badge, color, (22, 56, 52, 39)) + if active: + pygame.draw.circle(badge, T.GREEN, (82, 14), 8) + return badge + + +class ProfilesScene(Scene): + music = "musica_vila" + + def __init__(self, app) -> None: + super().__init__(app) + self.page = 0 + self.error = "" + + def build(self) -> None: + slots = self.app.list_profiles() + page_count = max(1, (len(slots) + 3) // 4) + self.page = min(self.page, page_count - 1) + visible = slots[self.page * 4 : (self.page + 1) * 4] + buttons = [] + for index, slot in enumerate(visible, self.page * 4): + x = 70 + (index % 2) * 490 + y = 130 + ((index % 4) // 2) * 175 + stored = peek_profile(slot.id) + portrait = self.app.view.skin.pilots.compose("menu", stored.piloto) if stored is not None else None + buttons.append( + self.button( + (x, y, 430, 145), + slot.label, + lambda selected=slot: self._select(selected.id), + sublabel="Piloto atual" if slot.active else "Abrir este piloto", + icon=_pilot_badge(stored, index, slot.active, portrait), + selected=slot.active, + size=T.SIZES["title"], + key=f"perfil-{slot.id}", + ) + ) + if len(slots) < PROFILE_SLOT_LIMIT: + buttons.append( + self.button( + (70, 485, 300, 76), + "Novo piloto", + self._create, + sublabel="Começar do início", + key="perfil-novo", + size=T.SIZES["label"], + ) + ) + if page_count > 1: + buttons.append( + self.button( + (390, 485, 90, 76), + "", + lambda: self._page(-1), + icon=T.icon_surface("back", 54), + enabled=self.page > 0, + key="perfil-pagina-anterior", + ) + ) + buttons.append( + self.button( + (500, 485, 90, 76), + "", + lambda: self._page(1), + icon=T.icon_surface("next", 54), + enabled=self.page + 1 < page_count, + key="perfil-pagina-proxima", + ) + ) + buttons.append(self.button((800, 485, 220, 76), "Voltar", lambda: self.goto("vila"), key="perfil-voltar")) + self.menu.set_buttons(buttons) + + def _page(self, direction: int) -> None: + self.page += direction + self.error = "" + self.build() + + def _select(self, slot_id: str) -> None: + if slot_id == self.app.profile_slot: + self.goto("vila") + return + if not self.app.select_profile(slot_id): + self.error = self.app.storage_notice or "Não consegui abrir este piloto." + + def _create(self) -> None: + if not self.app.create_profile(): + self.error = self.app.storage_notice or "Não consegui criar um piloto agora." + + def draw(self, screen: pygame.Surface) -> None: + screen.fill(T.PAPER) + self.title(screen, "Quem vai voar?", "Cada piloto guarda seu próprio progresso") + self.menu.draw(screen, self.text, self.dwell_time) + self.menu.draw_pointer(screen, self.dwell_time, self.app.input.body_pointer() is not None) + if self.error: + box = pygame.Rect(80, C.HEIGHT - 54, C.WIDTH - 160, 42) + T.panel(screen, box, T.PAPER, T.ORANGE, 245, 12, 3) + label, size = T.fit_text(self.text, self.error, box.width - 24, T.SIZES["small"], bold=True) + self.text.blit(screen, label, box.center, size, T.INK, True, "center") diff --git a/dobramundo/scenes/projection.py b/dobramundo/scenes/projection.py index 6f24f58..96a2c98 100644 --- a/dobramundo/scenes/projection.py +++ b/dobramundo/scenes/projection.py @@ -16,7 +16,7 @@ from .. import config as C from ..content import texts from ..engine.orientation import ROTATIONS, standing, unrotate_point -from ..input.floor import TARGETS, FloorMap +from ..input.api import TARGETS, FloorMap from ..ui import theme as T from ..ui.widgets import row from .base import Scene diff --git a/dobramundo/scenes/result.py b/dobramundo/scenes/result.py index 410d46e..13f4b90 100644 --- a/dobramundo/scenes/result.py +++ b/dobramundo/scenes/result.py @@ -115,7 +115,25 @@ def retry_save(self) -> None: self.build() def again(self) -> None: - self.fly(self.run.biome.key) + + flight = self.app.create_scene( + "voo", + self.run.biome.key, + seed=self.run.seed, + mode=self.run.mode, + session_limit_s=self.run.session_limit_s, + exploration=self.run.exploration, + predictable_assistance=self.run.predictable_assistance, + intro_override=self.run.intro, + community_challenge=self.run.community_challenge, + mission_preferred_waste=self.run.mission_preferred_waste, + mission_preference_fixed=True, + ) + body = self.app.input.body + if body is not None and body.error is None and not body.calibrated: + flight = self.app.create_scene("calibracao", return_to=flight) + self.app.save() + self.app.go(flight) def draw(self, screen: pygame.Surface) -> None: run = self.run @@ -137,6 +155,8 @@ def draw(self, screen: pygame.Surface) -> None: title = f"{run.biome.city} floresceu!" elif run.game_over: title = "Seu avião precisa de reparos" + elif run.timeout: + title = "Tempo combinado: voo guardado" elif run.interrupted: title = "Voo encerrado por agora" else: @@ -184,8 +204,26 @@ def draw(self, screen: pygame.Surface) -> None: True, "midtop", ) - self.text.blit(screen, "Recursos para a vila", (card.left + 38, card.top + 213), T.SIZES["body"], T.NAVY, True) - cells = row(pygame.Rect(card.left + 32, card.top + 242, card.width - 64, 66), 4, 12) + details = [f"Semente {run.seed}"] + if run.world.challenge_theme is not None: + details.append(run.world.challenge_theme.title) + if run.session_limit_s: + details.append(f"tempo combinado {run.session_limit_s // 60} min") + if run.exploration: + details.append("Explorar") + if run.predictable_assistance: + details.append("assistência previsível") + self.text.blit( + screen, + " · ".join(details), + (card.centerx, card.top + 199), + T.SIZES["small"], + T.TEAL, + True, + "midtop", + ) + self.text.blit(screen, "Recursos para a vila", (card.left + 38, card.top + 222), T.SIZES["body"], T.NAVY, True) + cells = row(pygame.Rect(card.left + 32, card.top + 251, card.width - 64, 66), 4, 12) for waste, rect in zip(WASTE_TYPES, cells): T.panel(screen, rect, T.PAPER, waste.color, 250, 14, 2) icon = self.app.assets.sprite("waste_sprites", waste.sprite) @@ -200,10 +238,10 @@ def draw(self, screen: pygame.Surface) -> None: True, ) self.text.blit(screen, waste.name, (rect.left + 62, rect.top + 39), T.SIZES["small"], T.MUTED) - self.draw_next_build(screen, pygame.Rect(card.left + 32, card.top + 322, 468, 92)) - self.draw_missing_parts(screen, pygame.Rect(card.left + 520, card.top + 322, card.width - 552, 92)) + self.draw_next_build(screen, pygame.Rect(card.left + 32, card.top + 331, 468, 92)) + self.draw_missing_parts(screen, pygame.Rect(card.left + 520, card.top + 331, card.width - 552, 92)) if self.app.save_failed: - warn = pygame.Rect(card.left + 32, card.top + 424, card.width - 64, 84) + warn = pygame.Rect(card.left + 32, card.top + 427, card.width - 64, 82) T.panel(screen, warn, T.PAPER, T.RED, 250, 16, 3) self.text.blit( screen, @@ -215,11 +253,11 @@ def draw(self, screen: pygame.Surface) -> None: "center", ) else: - self.text.blit(screen, "Curiosidade", (card.left + 38, card.top + 425), T.SIZES["small"], T.TEAL, True) + self.text.blit(screen, "Curiosidade", (card.left + 38, card.top + 428), T.SIZES["small"], T.TEAL, True) self.text.paragraph( screen, self.fact, - pygame.Rect(card.left + 38, card.top + 448, card.width - 76, 58), + pygame.Rect(card.left + 38, card.top + 451, card.width - 76, 56), T.SIZES["small"], T.INK, spacing=1.1, diff --git a/dobramundo/scenes/tutorial.py b/dobramundo/scenes/tutorial.py index 0bf1fbc..56dba9b 100644 --- a/dobramundo/scenes/tutorial.py +++ b/dobramundo/scenes/tutorial.py @@ -13,10 +13,9 @@ from ..engine.sprites import project from ..game.entities import Entity from ..game.run import FlightRun -from ..input.hub import FLIGHT_KEYS +from ..input.api import FLIGHT_KEYS from ..ui import theme as T from ..ui.widgets import ring -from . import make_scene from .base import Scene MOVE_DISTANCE = 36.0 @@ -98,7 +97,7 @@ def begin_exit(self) -> None: self.build() def finish(self) -> None: - target = self.next_scene or self.return_to or make_scene(self.app, "vila") + target = self.next_scene or self.return_to or self.app.create_scene("vila") self.app.go(target) def back(self) -> None: @@ -354,11 +353,11 @@ def skip(self) -> None: def finish(self) -> None: self.app.profile.tutorial_visto = True self.app.save() - next_scene = self.next_scene or make_scene(self.app, "vila") + next_scene = self.next_scene or self.app.create_scene("vila") self.app.go(next_scene) def back(self) -> None: - self.app.go(self.return_to or make_scene(self.app, "mapa")) + self.app.go(self.return_to or self.app.create_scene("mapa")) def resume(self) -> None: self.paused = False @@ -392,9 +391,7 @@ def draw(self, screen: pygame.Surface) -> None: if self.feedback > 0.0: feedback_y = 250 if player_y > 360 else 430 T.panel(screen, pygame.Rect(390, feedback_y, 320, 72), T.PAPER, T.GREEN, 245, 18, 3) - self.text.blit( - screen, "Muito bem!", (550, feedback_y + 36), T.SIZES["label"], T.GREEN, True, "center" - ) + self.text.blit(screen, "Muito bem!", (550, feedback_y + 36), T.SIZES["label"], T.GREEN, True, "center") if self.paused: T.veil(screen, (10, 18, 40), 170) T.panel(screen, pygame.Rect(330, 198, 440, 230), T.PAPER, T.NAVY, 250, 24, 4) @@ -405,8 +402,10 @@ def draw(self, screen: pygame.Surface) -> None: def _step_icon(self, kind: str) -> pygame.Surface: if kind == "collect": sprite = self.app.assets.sprite("waste_sprites", "papel") - icon = self.scaled(sprite, (52, 52), ("tutorial", "papel")) if sprite is not None else T.icon_surface( - "paper", 52, T.TEAL + icon = ( + self.scaled(sprite, (52, 52), ("tutorial", "papel")) + if sprite is not None + else T.icon_surface("paper", 52, T.TEAL) ) surface = pygame.Surface((72, 72), pygame.SRCALPHA) surface.blit(icon, (0, 10)) diff --git a/dobramundo/scenes/village.py b/dobramundo/scenes/village.py index 79a633e..9730f77 100644 --- a/dobramundo/scenes/village.py +++ b/dobramundo/scenes/village.py @@ -453,6 +453,24 @@ def build(self) -> None: self.button((922, 12, 130, 48), "Sobre", lambda: self.goto("sobre"), key="sobre"), ] ) + if self.app.platform == "desktop": + self.menu.buttons.append( + self.button( + (730, 80, 322, 56), + "Trocar de piloto", + lambda: self.goto("perfis"), + icon=destination_icon("piloto"), + key="perfis", + ) + ) + if self.app.storage_notice and not self.app.save_failed: + self.menu.buttons.append( + self.button((895, 438, 157, 60), "Entendi", self.dismiss_storage_notice, key="aviso_dados") + ) + + def dismiss_storage_notice(self) -> None: + self.app.dismiss_storage_notice() + self.build() def back(self) -> None: """ESC abre (ou fecha) a pergunta de saída, em vez de trocar de tela.""" @@ -476,7 +494,7 @@ def draw(self, screen: pygame.Surface) -> None: painted = any(backgrounds.get(name) is not None for name in ("village_start_v2", "village_start")) plane_size = (225, 150) if painted else (250, 170) img = self.scaled(plane, plane_size, key) - bob = math.sin(self.time * 2.2) * 6 + bob = 0.0 if app.options.reduzir_movimento else math.sin(self.time * 2.2) * 6 paper.shadow(screen, (SQUARE[0], SQUARE[1] + 3), int(img.get_width() * 0.88) - int(bob * 3), 34, 60) screen.blit(img, img.get_rect(center=(SQUARE[0], int((340 if painted else 330) + bob)))) progress = village_progress(profile) @@ -497,6 +515,12 @@ def draw(self, screen: pygame.Surface) -> None: pygame.draw.rect(screen, T.PAPER, bar, border_radius=8) pygame.draw.rect(screen, T.TEAL, (bar.left, bar.top, int(bar.width * progress), bar.height), border_radius=8) self.resource_bar(screen, right=710, top=16) + if app.storage_notice and not app.save_failed: + notice = pygame.Rect(16, 430, 860, 76) + T.panel(screen, notice, T.PAPER, T.ORANGE, 248, 12, 3) + self.text.paragraph( + screen, app.storage_notice, notice.inflate(-28, -16), T.SIZES["body"], T.INK, spacing=1.1 + ) if app.save_failed: warn = pygame.Rect(16, 466, C.WIDTH - 32, 38) T.panel(screen, warn, T.PAPER, T.RED, 240, 12, 3) @@ -518,7 +542,7 @@ def draw(self, screen: pygame.Surface) -> None: ) self.text.blit( screen, - "O progresso já está salvo.", + "Há progresso ainda não salvo." if app.save_failed else "O progresso já está salvo.", (card.centerx, card.top + 88), T.SIZES["body"], T.MUTED, diff --git a/dobramundo/selftest.py b/dobramundo/selftest.py index 11d4ef0..fb6aae5 100644 --- a/dobramundo/selftest.py +++ b/dobramundo/selftest.py @@ -9,6 +9,7 @@ import json import random +import re import sys import time from typing import Dict, List @@ -48,9 +49,29 @@ def pose_check() -> dict: result["detector"] = f"bibliotecas ausentes ({exc.name})" except Exception as exc: # modelo corrompido, runtime do MediaPipe etc. result["detector"] = f"erro ({exc.__class__.__name__})" + # PyInstallerImportError esconde a causa do OSError. Preserve o nome da + # biblioteca/erro para o CI, mas não caminhos absolutos do executor. + detail = _safe_error_detail(exc) + if detail: + result["detector_detalhe"] = detail return result +def _safe_error_detail(exc: Exception) -> str: + """Detalhe diagnóstico sem diretórios locais ou traceback no relatório público.""" + message = str(exc) + cause = exc.__cause__ + if cause is not None: + message = f"{message}; causa {cause.__class__.__name__}: {cause}" + # Reduz caminhos absolutos Windows/POSIX ao nome final (por ex. libxyz.so). + message = re.sub( + r"(?i)(?:[a-z]:[\\/]|/)[^'\"\r\n;:]+", + lambda match: match.group(0).replace("\\", "/").rsplit("/", 1)[-1], + message, + ) + return message[:240] + + REQUIRED_SPRITES = ( "biome_sprites", "era_final_sprites", diff --git a/dobramundo/ui/theme.py b/dobramundo/ui/theme.py index c5d4bd2..c0288fe 100644 --- a/dobramundo/ui/theme.py +++ b/dobramundo/ui/theme.py @@ -5,7 +5,8 @@ import math import random -from typing import Dict, List, Optional, Tuple +from functools import lru_cache +from typing import Dict, List, Tuple import pygame @@ -37,12 +38,43 @@ SHADOW = (31, 44, 80) # sombra azulada dos cartões (tinta diluída) +def elide_text(value: str, font: pygame.font.Font, max_width: int) -> str: + """Mantém texto inteiro se couber, ou corta em limite medido com reticências.""" + if max_width <= 0: + return "" + if font.size(value)[0] <= max_width: + return value + suffix = "…" + if font.size(suffix)[0] > max_width: + return "" + low, high = 0, len(value) + while low < high: + middle = (low + high + 1) // 2 + if font.size(value[:middle].rstrip() + suffix)[0] <= max_width: + low = middle + else: + high = middle - 1 + return value[:low].rstrip() + suffix + + +def fit_text( + text: Text, value: str, max_width: int, size: int = 20, minimum: int = 16, bold: bool = False +) -> Tuple[str, int]: + """Reduz até um piso legível e então abrevia; devolve (texto, tamanho).""" + minimum = max(1, min(minimum, size)) + for candidate in range(size, minimum - 1, -1): + font = text.font(candidate, bold) + if font.size(value)[0] <= max_width: + return value, candidate + return elide_text(value, text.font(minimum, bold), max_width), minimum + + class Text: """Fontes por tamanho e superfícies de texto em cache (o HUD não re-renderiza a cada quadro).""" def __init__(self) -> None: - self.fonts: Dict[Tuple[int, bool], pygame.font.Font] = {} - self.cache = BoundedCache(600) # superfícies de texto prontas + self.fonts: Dict[Tuple[int, bool, bool], pygame.font.Font] = {} + self.cache = BoundedCache(600, 16 * 1024 * 1024) # superfícies de texto prontas self.wrapped = BoundedCache(200) # quebras de linha por (texto, largura, tamanho) def font(self, size: int, bold: bool = False, hand: bool = False) -> pygame.font.Font: @@ -138,25 +170,23 @@ def paragraph( _panels: Dict[tuple, pygame.Surface] = {} -_grain: Optional[pygame.Surface] = None SHADOW_OFFSET = 5 +@lru_cache(maxsize=1) def paper_grain() -> pygame.Surface: """Grão de papel (ruído claro, multiplicado sobre os cartões), feito uma vez.""" - global _grain - if _grain is None: - rng = random.Random(7) - size = 256 - _grain = pygame.Surface((size, size)) - _grain.fill((255, 255, 255)) - px = pygame.PixelArray(_grain) - for y in range(size): - for x in range(size): - v = 255 - rng.randrange(0, 14) - px[x, y] = (v, v, v) - del px - return _grain + rng = random.Random(7) + size = 256 + grain = pygame.Surface((size, size)) + grain.fill((255, 255, 255)) + px = pygame.PixelArray(grain) + for y in range(size): + for x in range(size): + v = 255 - rng.randrange(0, 14) + px[x, y] = (v, v, v) + del px + return grain def panel( @@ -259,6 +289,20 @@ def points(values): pygame.draw.polygon(surface, ink, points([(-15, -12), (15, -12), (15, 12), (-15, 12)]), 3) pygame.draw.line(surface, TEAL, points([(-12, -4)])[0], points([(12, -4)])[0], 2) pygame.draw.line(surface, ORANGE, points([(-12, 3)])[0], points([(8, 3)])[0], 2) + elif kind == "clock": + pygame.draw.circle(surface, ink, (cx, cy), int(16 * s), max(2, int(3 * s))) + pygame.draw.lines(surface, ink, False, points([(0, -10), (0, 0), (9, 5)]), max(2, int(3 * s))) + elif kind == "back": + pygame.draw.polygon(surface, ink, points([(17, -6), (-4, -6), (-4, -15), (-19, 0), (-4, 15), (-4, 6), (17, 6)])) + elif kind == "plane": + pygame.draw.polygon(surface, PAPER, points([(-19, 13), (17, -15), (8, 18), (-2, 7)])) + pygame.draw.polygon(surface, ink, points([(-19, 13), (17, -15), (8, 18), (-2, 7)]), max(2, int(2 * s))) + pygame.draw.line(surface, ORANGE, points([(-2, 7)])[0], points([(17, -15)])[0], max(2, int(3 * s))) + elif kind == "map": + route = points([(-15, 13), (-8, 0), (4, 6), (14, -13)]) + pygame.draw.lines(surface, ink, False, route, max(2, int(3 * s))) + for point in (route[0], route[-1]): + pygame.draw.circle(surface, ORANGE, point, max(3, int(5 * s))) elif kind in {"dodge", "desviar", "next"}: pygame.draw.polygon(surface, ink, points([(-17, -6), (4, -6), (4, -15), (19, 0), (4, 15), (4, 6), (-17, 6)])) elif kind in {"portal", "gate"}: @@ -270,22 +314,27 @@ def points(values): 2 * math.pi, max(3, int(5 * s)), ) - pygame.draw.line(surface, ink, points([(-17, 0)])[0], points([(-17, 15)])[0], max(3, int(5*s))) - pygame.draw.line(surface, ink, points([(17, 0)])[0], points([(17, 15)])[0], max(3, int(5*s))) - pygame.draw.line(surface, TEAL, points([(-17, 14)])[0], points([(17, 14)])[0], max(2, int(3*s))) + pygame.draw.line(surface, ink, points([(-17, 0)])[0], points([(-17, 15)])[0], max(3, int(5 * s))) + pygame.draw.line(surface, ink, points([(17, 0)])[0], points([(17, 15)])[0], max(3, int(5 * s))) + pygame.draw.line(surface, TEAL, points([(-17, 14)])[0], points([(17, 14)])[0], max(2, int(3 * s))) elif kind == "magnet": - pygame.draw.lines(surface, ink, False, points([(-12, -15), (-12, 7), (-6, 15), (6, 15), (12, 7), (12, -15)]), - max(5, int(8 * s))) - pygame.draw.line(surface, ORANGE, points([(-12, -15)])[0], points([(-12, -5)])[0], max(5, int(8*s))) - pygame.draw.line(surface, TEAL, points([(12, -15)])[0], points([(12, -5)])[0], max(5, int(8*s))) + pygame.draw.lines( + surface, + ink, + False, + points([(-12, -15), (-12, 7), (-6, 15), (6, 15), (12, 7), (12, -15)]), + max(5, int(8 * s)), + ) + pygame.draw.line(surface, ORANGE, points([(-12, -15)])[0], points([(-12, -5)])[0], max(5, int(8 * s))) + pygame.draw.line(surface, TEAL, points([(12, -15)])[0], points([(12, -5)])[0], max(5, int(8 * s))) elif kind in {"powerup", "shield", "repair"}: pygame.draw.polygon(surface, ink, points([(0, -18), (16, -11), (13, 7), (0, 18), (-13, 7), (-16, -11)])) - pygame.draw.line(surface, (255, 255, 255), points([(0, -10)])[0], points([(0, 9)])[0], max(2, int(3*s))) + pygame.draw.line(surface, (255, 255, 255), points([(0, -10)])[0], points([(0, 9)])[0], max(2, int(3 * s))) if kind == "repair": - pygame.draw.line(surface, (255, 255, 255), points([(-8, 0)])[0], points([(8, 0)])[0], max(2, int(3*s))) + pygame.draw.line(surface, (255, 255, 255), points([(-8, 0)])[0], points([(8, 0)])[0], max(2, int(3 * s))) elif kind in {"stabilizer", "keel", "rudder", "part"}: pygame.draw.polygon(surface, ink, points([(-18, 9), (0, -13), (18, 9), (0, 4)])) - pygame.draw.line(surface, (255, 255, 255), points([(0, -10)])[0], points([(0, 8)])[0], max(2, int(3*s))) + pygame.draw.line(surface, (255, 255, 255), points([(0, -10)])[0], points([(0, 8)])[0], max(2, int(3 * s))) if kind == "rudder": pygame.draw.polygon(surface, ORANGE, points([(0, 5), (12, -14), (13, 8)])) elif kind in {"star", "reward"}: @@ -304,7 +353,7 @@ def points(values): max(2, int(3 * s)), ) for ox, oy, shade in ((-8, -5, ORANGE), (3, -8, TEAL), (9, 3, SUN), (-4, 8, GREEN)): - pygame.draw.circle(surface, shade, (cx + int(ox*s), cy + int(oy*s)), max(2, int(4*s))) + pygame.draw.circle(surface, shade, (cx + int(ox * s), cy + int(oy * s)), max(2, int(4 * s))) elif kind == "pattern": rect = pygame.Rect(cx - int(15 * s), cy - int(15 * s), int(30 * s), int(30 * s)) pygame.draw.rect(surface, ink, rect, max(2, int(3 * s)), border_radius=max(2, int(5 * s))) @@ -324,10 +373,10 @@ def points(values): ink, points([(-18, -2), (0, -17), (18, -2), (14, -2), (14, 15), (-14, 15), (-14, -2)]), ) - pygame.draw.rect(surface, PAPER, pygame.Rect(cx - int(4*s), cy + int(2*s), int(8*s), int(13*s))) + pygame.draw.rect(surface, PAPER, pygame.Rect(cx - int(4 * s), cy + int(2 * s), int(8 * s), int(13 * s))) else: pygame.draw.polygon(surface, ink, points([(-17, 0), (14, -12), (7, 0), (14, 12)])) - pygame.draw.line(surface, PAPER, points([(-3, 0)])[0], points([(2, -1)])[0], max(2, int(2*s))) + pygame.draw.line(surface, PAPER, points([(-3, 0)])[0], points([(2, -1)])[0], max(2, int(2 * s))) _icons[key] = surface return surface diff --git a/docs/ANALISE_BASE_1_5.md b/docs/ANALISE_BASE_1_5.md new file mode 100644 index 0000000..fbd60f4 --- /dev/null +++ b/docs/ANALISE_BASE_1_5.md @@ -0,0 +1,59 @@ +# Análise consolidada — experiência, desempenho e entrega + +Base: revisão da main `4a650b2`, análise externa `analise-repositorio-dobramundo.md` fornecida pelo usuário em 25/10/2026 e teste relatado com webcam. A análise externa foi usada como evidência a conferir; suas estimativas não são resultados desta implementação. + +## P0 autorizados nesta entrega + +| Item | Escopo de implementação e aceite | +|---|---| +| Câmera robusta | Encerrar sem bloquear a interface, manter fonte até liberação, reabrir sem duas capturas concorrentes; testar falha/desconexão. | +| Latência mensurável | Tempos de leitura, inferência, publicação, idade/cadência; relatório local sem imagens nem landmarks. Timestamp de retorno da leitura não equivale ao instante físico do sensor. | +| Recompensa ao interromper | Resultado parcial, crédito uma única vez, histórico, fechamento normal e tentativa de salvar novamente; sem conceder conclusão/estrela que não foi conquistada. | +| Orçamento de quadro | Medir componentes e memória; corrigir carregamento do piloto, custo do terreno, composição de horizonte, buffers e aquecimento. Comparar CPU sem câmera e com câmera disponível. | +| Sequências alcançáveis | Geração e auditoria determinística sob limites explícitos de manobra/reação; preservar variedade. Alcance matemático não prova conforto motor de cada pessoa. | +| Conforto sem compras | Sensibilidade, zona morta, resposta e tolerância disponíveis independentemente dos recursos. Peças preservam coleções, saves e requisitos de progressão, com textos coerentes. | + +## Achados do anexo incorporados + +Os seis P0 acima foram implementados. A entrega passou por 446 testes, CI em Python 3.8/3.12, auditoria de 4.000 sementes e medição com webcam local. As [notas e métricas da versão 1.5](ENTREGA_1_5.md) registram picos, carregamento inicial, memória acumulada e o aceite presencial ainda necessário. + +| Achado | Conferência / encaminhamento | +|---|---| +| Piloto decodifica toda a pasta aquarela | Confirmado: 39 imagens, 245.378.820 bytes de superfícies dessa pasta na abertura. Baseline local: 2.793,9 ms para criar App e incremento de RSS de 377.925.632 bytes. Corrigido com seleção explícita das camadas do piloto. | +| Chão é o maior custo recorrente | Baseline instrumentado: mediana de 4,697 ms no chão de Manaus normal. Otimizar sem interromper avanço nem congelar faixas entre quadros. | +| Fundos opacos tratados como RGBA | Confirmado no loader. Detectar opacidade real uma vez e conservar alfa em sprites com transparência, inclusive furos interiores. | +| Composição da transição | Recalcular apenas região visível acima do terreno quando há percurso pintado; ignorar alfa zero e copiar diretamente alfa cheio. O fallback mantém composição integral. | +| Alto contraste | A escala rápida da sprint3 já está na main. Reutilizar buffers cinza; não cachear indefinidamente um fundo que está se movendo. | +| README e release difíceis de encontrar | Reorganizar a entrada do projeto, preservar manual/histórico em documentos próprios e identificar a entrega como 1.5.0. | +| Lint divergente | Excluir ferramentas legadas do escopo ativo e alinhar comando da CI ao README. A formatação global permanece separada das correções funcionais. | +| Python do console | SDK instalado confirma `requires-python >=3.14`; código portável continua testado em 3.8/3.12. São contratos distintos, agora descritos explicitamente. | +| Repositório público | Confirmado com GitHub CLI nesta revisão; nenhum ajuste de visibilidade foi feito. | + +As medições do anexo (inclusive ganhos previstos de 30–50%, 240 MB e imagens de 20–25 MB) permanecem atribuídas à análise externa. Só o relatório desta entrega pode confirmar ganhos obtidos aqui. + +## P1 — experiência e engenharia a seguir + +- Sessões curtas, exploração sem eliminação e assistência opcional com mudanças previsíveis. +- Coordenar a primeira missão com as lições iniciais e garantir oferta dos objetivos sorteados. +- Balancear economia por tempo real, erros e interrupções; a simulação invencível não basta. +- Validar profundidade/vãos/altura e compreensão sem leitura na projeção e nos seis controles. +- Preparação de assets por tamanho de uso; memória por cena e descarte seletivo medido. +- Recuperação de último save válido e perfis de desktop compartilhado. +- Testes longos, latência no equipamento de destino, desconexão física e uso mediado com crianças. + +## P2 — manutenção e evolução incorporadas do anexo + +- Refatorar funções longas por camada e seção; manter a cadeia pintado → papel → lógico como fallback documentado. Imports locais nem sempre são ciclos: alguns evitam dependências opcionais no console. +- Auditar referências antes de remover funções apontadas como mortas. Não apagar renderizadores de reserva. +- Consolidar fontes, ajuste de texto, constantes e interface pública de entrada; documentar contratos do motor. +- Organizar testes por comportamento, reduzir helpers duplicados e medir cobertura sem usar percentual como prova de qualidade. +- Fixar dependências de CI por versão de Python. **Não aplicar cegamente `constraints-build.txt` a Python 3.8:** o conjunto do build 3.12 contém pacotes incompatíveis com o piso antigo. +- Formatação global em mudança própria, seguida de verificação na CI; build automatizado em Windows/Linux e cache de dependências. +- Testar suporte real do console antes de converter para WebP/JPEG. Menor tamanho comprimido não significa menor superfície decodificada em RAM. +- Atlas, pivôs e resolução de uso padronizados; preservar originais e manifestos de procedência. Não reescrever o histórico Git para recuperar espaço. +- Ajustar descrição, tópicos e prévia social se desejado. Exclusão de branches/releases históricas e configuração de exclusão automática ficam fora desta correção P0. +- Variações regionais de percurso, usos comunitários e desafios com sementes reproduzíveis. + +## Critério de conclusão + +Código testado, documentação coerente, pacotes identificados e rastreáveis. Testes automatizados, captura instrumentada e benchmark de CPU serão distinguidos do aceite presencial. Não será declarada latência física de movimento, eficácia terapêutica ou 60 fps garantidos em outro equipamento a partir de testes sintéticos. diff --git a/docs/ANALISE_CONSOLIDADA.md b/docs/ANALISE_CONSOLIDADA.md index fbd60f4..837733f 100644 --- a/docs/ANALISE_CONSOLIDADA.md +++ b/docs/ANALISE_CONSOLIDADA.md @@ -1,59 +1,40 @@ -# Análise consolidada — experiência, desempenho e entrega - -Base: revisão da main `4a650b2`, análise externa `analise-repositorio-dobramundo.md` fornecida pelo usuário em 25/10/2026 e teste relatado com webcam. A análise externa foi usada como evidência a conferir; suas estimativas não são resultados desta implementação. - -## P0 autorizados nesta entrega - -| Item | Escopo de implementação e aceite | -|---|---| -| Câmera robusta | Encerrar sem bloquear a interface, manter fonte até liberação, reabrir sem duas capturas concorrentes; testar falha/desconexão. | -| Latência mensurável | Tempos de leitura, inferência, publicação, idade/cadência; relatório local sem imagens nem landmarks. Timestamp de retorno da leitura não equivale ao instante físico do sensor. | -| Recompensa ao interromper | Resultado parcial, crédito uma única vez, histórico, fechamento normal e tentativa de salvar novamente; sem conceder conclusão/estrela que não foi conquistada. | -| Orçamento de quadro | Medir componentes e memória; corrigir carregamento do piloto, custo do terreno, composição de horizonte, buffers e aquecimento. Comparar CPU sem câmera e com câmera disponível. | -| Sequências alcançáveis | Geração e auditoria determinística sob limites explícitos de manobra/reação; preservar variedade. Alcance matemático não prova conforto motor de cada pessoa. | -| Conforto sem compras | Sensibilidade, zona morta, resposta e tolerância disponíveis independentemente dos recursos. Peças preservam coleções, saves e requisitos de progressão, com textos coerentes. | - -## Achados do anexo incorporados - -Os seis P0 acima foram implementados. A entrega passou por 446 testes, CI em Python 3.8/3.12, auditoria de 4.000 sementes e medição com webcam local. As [notas e métricas da versão 1.5](ENTREGA_1_5.md) registram picos, carregamento inicial, memória acumulada e o aceite presencial ainda necessário. - -| Achado | Conferência / encaminhamento | -|---|---| -| Piloto decodifica toda a pasta aquarela | Confirmado: 39 imagens, 245.378.820 bytes de superfícies dessa pasta na abertura. Baseline local: 2.793,9 ms para criar App e incremento de RSS de 377.925.632 bytes. Corrigido com seleção explícita das camadas do piloto. | -| Chão é o maior custo recorrente | Baseline instrumentado: mediana de 4,697 ms no chão de Manaus normal. Otimizar sem interromper avanço nem congelar faixas entre quadros. | -| Fundos opacos tratados como RGBA | Confirmado no loader. Detectar opacidade real uma vez e conservar alfa em sprites com transparência, inclusive furos interiores. | -| Composição da transição | Recalcular apenas região visível acima do terreno quando há percurso pintado; ignorar alfa zero e copiar diretamente alfa cheio. O fallback mantém composição integral. | -| Alto contraste | A escala rápida da sprint3 já está na main. Reutilizar buffers cinza; não cachear indefinidamente um fundo que está se movendo. | -| README e release difíceis de encontrar | Reorganizar a entrada do projeto, preservar manual/histórico em documentos próprios e identificar a entrega como 1.5.0. | -| Lint divergente | Excluir ferramentas legadas do escopo ativo e alinhar comando da CI ao README. A formatação global permanece separada das correções funcionais. | -| Python do console | SDK instalado confirma `requires-python >=3.14`; código portável continua testado em 3.8/3.12. São contratos distintos, agora descritos explicitamente. | -| Repositório público | Confirmado com GitHub CLI nesta revisão; nenhum ajuste de visibilidade foi feito. | - -As medições do anexo (inclusive ganhos previstos de 30–50%, 240 MB e imagens de 20–25 MB) permanecem atribuídas à análise externa. Só o relatório desta entrega pode confirmar ganhos obtidos aqui. - -## P1 — experiência e engenharia a seguir - -- Sessões curtas, exploração sem eliminação e assistência opcional com mudanças previsíveis. -- Coordenar a primeira missão com as lições iniciais e garantir oferta dos objetivos sorteados. -- Balancear economia por tempo real, erros e interrupções; a simulação invencível não basta. -- Validar profundidade/vãos/altura e compreensão sem leitura na projeção e nos seis controles. -- Preparação de assets por tamanho de uso; memória por cena e descarte seletivo medido. -- Recuperação de último save válido e perfis de desktop compartilhado. -- Testes longos, latência no equipamento de destino, desconexão física e uso mediado com crianças. - -## P2 — manutenção e evolução incorporadas do anexo - -- Refatorar funções longas por camada e seção; manter a cadeia pintado → papel → lógico como fallback documentado. Imports locais nem sempre são ciclos: alguns evitam dependências opcionais no console. -- Auditar referências antes de remover funções apontadas como mortas. Não apagar renderizadores de reserva. -- Consolidar fontes, ajuste de texto, constantes e interface pública de entrada; documentar contratos do motor. -- Organizar testes por comportamento, reduzir helpers duplicados e medir cobertura sem usar percentual como prova de qualidade. -- Fixar dependências de CI por versão de Python. **Não aplicar cegamente `constraints-build.txt` a Python 3.8:** o conjunto do build 3.12 contém pacotes incompatíveis com o piso antigo. -- Formatação global em mudança própria, seguida de verificação na CI; build automatizado em Windows/Linux e cache de dependências. -- Testar suporte real do console antes de converter para WebP/JPEG. Menor tamanho comprimido não significa menor superfície decodificada em RAM. -- Atlas, pivôs e resolução de uso padronizados; preservar originais e manifestos de procedência. Não reescrever o histórico Git para recuperar espaço. -- Ajustar descrição, tópicos e prévia social se desejado. Exclusão de branches/releases históricas e configuração de exclusão automática ficam fora desta correção P0. -- Variações regionais de percurso, usos comunitários e desafios com sementes reproduzíveis. - -## Critério de conclusão - -Código testado, documentação coerente, pacotes identificados e rastreáveis. Testes automatizados, captura instrumentada e benchmark de CPU serão distinguidos do aceite presencial. Não será declarada latência física de movimento, eficácia terapêutica ou 60 fps garantidos em outro equipamento a partir de testes sintéticos. +# Análise consolidada — estado de implementação + +Esta lista atualiza as prioridades após as entregas P0/P1/P2 no código da versão 1.6.0. “Implementado” descreve código e validação técnica, não aceite de participantes. As evidências, condições e limites estão na [entrega 1.6](ENTREGA_1_6.md), no [relatório de desempenho](validacao-v1.6/desempenho.md) e na [simulação econômica](validacao-v1.6/economia/sintese.md). + +A análise e o inventário completos que precederam a sprint estão preservados em [ANALISE_BASE_1_5.md](ANALISE_BASE_1_5.md); esta atualização resume estado e pendências sem apagar proveniência nem o backlog histórico. + +## Checklist + +| Frente | Estado no código | Validação ainda necessária | +|---|---|---| +| Liquidação e encerramento | Resultado completo/parcial idempotente por voo; fechamento normal liquida apenas voo iniciado; retry de save e histórico, cobertos por testes. | Confirmação de comportamento no equipamento de destino. Encerramento forçado do processo não é recuperável. | +| Câmera e controle | Pausa por leitura inválida/envelhecida, recuperação supervisionada, controles configuráveis e captura/inferência reais medidas localmente. | Reconexão física, latência ponta a ponta e conforto por segmento. | +| Acessibilidade de sessão | Permanência, contraste, exploração, duração, assistência previsível e treino estão implementados. | Compreensão sem leitura e alcance confortável com crianças e configurações distintas. | +| Missões e desafios | Metas selecionadas a partir dos alvos disponíveis; seeds efetivas registradas; desafios comunitários repetíveis; economia simulada com erros, pausas e interrupções. | Balanceamento percebido por participantes; a simulação não representa crianças. | +| Perfis e saves | Slots locais anônimos, save legado preservado, gravação atômica, cópias rotativas, recuperação e bloqueio em falha de leitura. | Testes de interrupção no sistema operacional e recuperação em máquina/disco de destino. | +| Fábrica de cenas e separação de plataforma | Criação injetável preserva fábrica padrão; armazenamento por jogador do T-TEA continua separado; contratos de integração testados. | Execução no console físico. | +| Render e desempenho | Loader seletivo, composição aquarelada, camadas separadas, cache com descarte e orçamento cooperativo. Benchmarks e ensaio prolongado publicados junto à entrega. | Picos de quadro ainda observados, sobretudo com webcam; medir no hardware de destino. Nenhum FPS ou latência física é garantido aqui. | +| Artefatos de release | CI com testes e builds nativos Windows/Linux, detector obrigatório e dependências Linux verificadas. Artefatos e hashes vinculados à entrega. | Instalação e uso nas máquinas de destino, além do console físico. | + +## P0 — segurança de fluxo e confiabilidade + +As prioridades foram liquidação de recompensa, fechamento normal, falhas de câmera, medição de latência, caminho seguro e independência do conforto em relação a compras. Campos de peças e requisitos de estrelas foram preservados. A liquidação é idempotente dentro da instância do voo; não equivale a checkpoint após encerramento abrupto ou perda física do disco. + +## P1 — experiência e manutenção + +- Implementados: exploração sem eliminação, limites curtos, assistência previsível, sementes para replay, recuperação de perfil e perfis desktop compartilhados com dados anônimos. +- Implementados: seleção de missões conforme entidades no percurso, registro explícito do resíduo coletado para o balanço e fábrica de cenas injetável. +- Validação pendente: duração confortável, compreensão da assistência, economia percebida e fluxo sem dependência de leitura. +- Aceite presencial: webcam, seis controles, projeção no chão a 2–3 m, movimento reduzido, alto contraste, sessões curtas e troca de piloto. Ver [roteiro presencial](VALIDACAO_PRESENCIAL.md). + +## P2 — arquitetura e processo + +- Implementados no código: APIs explícitas para entrada e cenas, separação progressiva das camadas do mundo, ferramentas de preparação/auditoria de assets e contrato entre render e simulação. +- Cobertura medida sem meta artificial; lint e formatação globais, CI por versão de Python e builds nativos com self-test. A entrega registra a execução conferida e o manifesto da release identifica as revisões. +- Revisões de desempenho devem registrar equipamento e condições; testes sintéticos não demonstram ergonomia individual, eficácia terapêutica ou latência física da projeção. +- Preservar geradores/fallbacks e compatibilidade do cartucho até validação no console real. A distribuição PNG não prova orçamento de memória no hardware T-TEA. + +## Critério para fechar a entrega + +Manter as evidências de CI/build e medições vinculadas à versão correspondente em [ENTREGA_1_6.md](ENTREGA_1_6.md). O aceite presencial continua distinto; não converter capturas estáticas ou simulações em resultado de usuário. diff --git a/docs/ENTREGA_1_6.md b/docs/ENTREGA_1_6.md new file mode 100644 index 0000000..82c0101 --- /dev/null +++ b/docs/ENTREGA_1_6.md @@ -0,0 +1,49 @@ +# Entrega 1.6.0 — sessões, progressão, perfis e manutenção + +**Escopo:** itens técnicos P1/P2 implementados na versão `1.6.0`, preservando os P0. O aceite com participantes, projetor e console físico continua pendente. [PR #12](https://github.com/lapsin-maker/dobramundo/pull/12) · [Release, pacotes e hashes](https://github.com/lapsin-maker/dobramundo/releases/tag/v1.6.0). + +## Resultado implementado + +- Perfis desktop locais anônimos, com slots independentes para progresso, piloto, opções e consentimento. O save legado permanece no slot `principal`; a tela de perfis não pede nome real. O console T-TEA continua usando o armazenamento por jogador do SDK. +- Gravação atômica com cópias anteriores validadas, tentativa de recuperação de perfis/índice e preservação de arquivos inválidos. Erros de leitura bloqueiam gravação que poderia apagar progresso; a interface informa quando recuperou apenas em memória. +- Preparação para sessões livres ou de 120, 180 e 240 segundos, modo exploração, assistência previsível e sementes de desafios publicadas. O resultado registra a semente efetiva e as opções necessárias ao replay. +- Encerramento parcial e completo idempotentes no fluxo normal: credita ganhos já obtidos, mantém histórico e permite nova tentativa de salvar. Encerrar pelo limite, pela pausa ou por colisão final não concede conclusão de fase que não ocorreu. +- Metas curtas são escolhidas conforme alvos presentes, após as lições iniciais, e dão lugar a outra oferta após 60 segundos ativos do mundo sem penalidade. Repetir o voo conserva a preferência de material, além da semente e dos modos. +- Ponto de troca custa 8 papel/8 plástico; Horta, 24 papel/16 vidro. As duas primeiras obras ficaram acessíveis mais cedo por decisão de produto; os demais preços foram preservados. A [simulação econômica](validacao-v1.6/economia/sintese.md) inclui colisões, reação, erros, pausas e interrupções, sem representar jogadores humanos. +- Oito temas regionais usam sementes publicadas. A auditoria de 32 combinações de bioma, modo, introdução e semente encontrou rotas iniciais e manteve a geração por 25 segundos simulados em cada caso. +- Treze variantes PNG preparadas para a resolução de uso: seis fundos e sete atlas de aviões. O catálogo registra hashes, dimensões, vistas e pivôs; os 39 originais permanecem disponíveis. PNG e os renderizadores de reserva foram preservados. +- Caches têm limites de quantidade e bytes; a troca de bioma libera fundos, margens e sprites de céu. As métricas discriminam donos de superfícies e RSS, que também inclui bibliotecas e memória do processo. +- Desenho de pista, entidades, avião e piloto separado por camada; o motor recebe contratos de leitura sem importar regras de voo. Fontes e ajuste de texto são comuns, e todas as cenas usam a fábrica injetável. +- Testes agrupados por comportamento, helpers compartilhados, dependências fixadas por versão de Python, cobertura, builds nativos Windows/Linux e self-test dos executáveis. A formatação foi isolada no commit `b9b3c4e`: 152 árvores sintáticas comparadas sem mudança semântica. + +## Resultados de validação + +- A revisão técnica `d47035c` passou na [matriz de testes e builds](https://github.com/lapsin-maker/dobramundo/actions/runs/40236396562). A revisão final da PR e o manifesto anexado à release identificam os commits de fonte e build dos downloads. +- Suíte local principal: **515 testes passaram**, 197,48 s, Python 3.12, antes de acrescentar os três casos finais de diagnóstico/empacotamento. Os quatro testes finais de diagnóstico/empacotamento também passaram. Testes usam perfil sintético isolado. +- CI Python 3.8/3.12: a execução acima passou com 516 testes e dois filtros gráficos opcionais pulados. NumPy foi então fixado separadamente por versão de Python para incluir esses filtros na verificação final da PR, totalizando 518 casos. Lint e formatação fazem parte da matriz. +- Cobertura da execução identificada: **78,95% de linhas e 66,26% de ramos** no pacote `dobramundo`; [contagens e escopo](validacao-v1.6/cobertura.json). Percentual não comprova qualidade ou comportamento em equipamento físico. +- Builds Windows e Ubuntu 24.04: executáveis testados com `--self-test 1200 --exigir-camera`. O detector foi carregado sem abrir a webcam. No Linux, `libegl1 libgles2` são dependências do sistema, e a CI verifica `libmediapipe.so` com `ldd`. +- Self-test local do fonte: **14 telas e 1.200 quadros por bioma**, detector carregado, sem falhas. [Relatório sem caminhos locais](validacao-v1.6/selftest-fonte.json). A auditoria verificou os hashes dos **39 originais e 13 variantes preparadas**. +- T-TEA: `tsdk check` validou **527 arquivos portáveis** com o SDK em Python 3.14.8. O cartucho e seus hashes acompanham a release; console físico continua pendente. +- Capturas sintéticas: **15 telas**, sem botões fora da área ou sobrepostos. As quatro imagens de voo removem somente as partículas transitórias no quadro final, para mostrar o piloto; não constituem teste de usabilidade. +- Benchmark e webcam: [relatório com dados completos](validacao-v1.6/desempenho.md). Comparação sem avatar: incremento de RSS na abertura de **160,7 para 87,2 MiB**; maior amostra ao fim dos cenários de **532,1 para 258,9 MiB**. Com avatar e webcam houve pico de **67,459 ms** por quadro. Não se afirma ganho geral de CPU ou 60 fps constantes. +- Ensaio prolongado: **30 ciclos, 1.215,5 segundos simulados e nenhuma falha**; 72 mil quadros de voo com trocas de cenas, biomas e aparências. RSS final de 542,5 MiB, máximo amostrado de 559,6 MiB; últimos dez ciclos entre 537,3 e 555,0 MiB. [Dados completos](validacao-v1.6/soak.json). + +A galeria, os dois pacotes desktop, o cartucho, `SHA256SUMS.txt` e `release-manifest.json` ficam na release. As duas revisões listadas no manifesto devem ter a mesma árvore de arquivos; o executável e seu diretório de bibliotecas são distribuídos juntos. Os relatórios históricos das versões anteriores permanecem preservados. + +## Aceite presencial — pendente + +Usar o [roteiro de validação presencial](VALIDACAO_PRESENCIAL.md) em equipamento e com participantes. Ainda precisam ser observados controle por webcam, seis segmentos, projeção no chão a 2–3 m, legibilidade sem leitura, compreensão de sessão curta, exploração/assistência, transformação da vila, reconexão e troca de perfil. Capturas e testes automatizados não equivalem a esse aceite. + +## Limites e recuperação + +- Perfis são arquivos locais, não contas sincronizadas. Não se solicitam nomes reais; os slots não constituem controle de acesso ou proteção contra leitura por outros usuários do mesmo sistema operacional. +- Cópias rotativas protegem contra corrupção e interrupções durante gravações cobertas pelo mecanismo. Não recuperam alteração perdida antes da rotação, falha do disco, exclusão de todos os arquivos, encerramento forçado antes de salvar nem corrupção simultânea de todas as cópias. +- Liquidação idempotente vale durante a vida da instância do voo e para seu fechamento normal. Não é diário transacional/checkpoint que reconstrua uma execução depois de queda abrupta do processo. +- Os limites de sessão são limites do tempo contabilizado pelo voo, não prescrição clínica. Exploração mantém o jogo após perda de vidas; colisões continuam registradas. A assistência previsível tem parâmetros fixos no voo e não demonstra que o desafio está confortável para uma pessoa específica. +- A semente permite repetir a geração do desafio com as mesmas configurações e versão do código. Não garante identidade entre versões, plataformas ou alterações futuras no algoritmo. +- Simulação de equilíbrio não prova duração real, eficácia terapêutica, segurança clínica ou adequação motora. Nenhuma dessas conclusões é afirmada nesta entrega. + +## Documentação relacionada + +[Guia do jogo](GUIA_DO_JOGO.md) · [Arquitetura](arquitetura.md) · [Análise consolidada](ANALISE_CONSOLIDADA.md) · [Histórico](../CHANGELOG.md) diff --git a/docs/GUIA_DO_JOGO.md b/docs/GUIA_DO_JOGO.md index e382a81..dcd7aad 100644 --- a/docs/GUIA_DO_JOGO.md +++ b/docs/GUIA_DO_JOGO.md @@ -4,11 +4,11 @@ Detalhes de jogabilidade, controles e operação. Para baixar, veja o [README](. ## O jogo -O Dobramundo é um exergame sério de voo, com proposta terapêutica. A criança pilota um avião de papel reciclado sobre cidades brasileiras poluídas e, a cada voo, as transforma em cidades solarpunk integradas à natureza do seu bioma. O nome une a dobradura de papel à transformação do mundo, como na canção *Aquarela*, popularizada por Toquinho. +O Dobramundo é um jogo de voo com atividade corporal e tema de sustentabilidade. A criança pilota um avião de papel reciclado sobre cidades brasileiras e contribui para transformá-las em cidades solarpunk integradas à natureza do bioma. O nome une a dobradura de papel à transformação do mundo, como na canção *Aquarela*, popularizada por Toquinho. O jogo não tem eficácia terapêutica demonstrada; conforto e adequação precisam de validação com participantes. O jogo atende ao console T-TEA, com projeção no chão e controle pelos pés, mas não se restringe a ele: pode ser projetado em mesas e paredes ou exibido em monitores, e o controle pode ser feito pelos pés, pelo tronco, por uma das mãos ou pela cabeça. Destina-se a crianças neurodiversas e com deficiências motoras, visuais, sensoriais ou do neurodesenvolvimento, oferecendo a cada uma um modo de interação compatível. -Projeto da Liga de Psiquiatria e Neurociências – CENSUPEG, desenvolvido para a 3ª ExerGame JAM LARVA/UDESC 2026. Versão 1.5.0. +Projeto da Liga de Psiquiatria e Neurociências – CENSUPEG, desenvolvido para a 3ª ExerGame JAM LARVA/UDESC 2026. Versão 1.6.0. ### Tema e objetivo @@ -48,11 +48,11 @@ A versão atual tem duas fases, cada uma numa cidade brasileira do seu bioma: ## Como se joga -Cada partida segue o ciclo **vila-base, mapa, voo e resultado**. Na vila, a criança escolhe a fase e o modo no mapa. No voo, o avião decola da vila, coleta resíduos e power-ups, desvia de obstáculos e acumula transformação. No resultado, estrelas e recursos vão para o perfil, e a criança volta à vila para construir melhorias e peças. +Cada partida segue o ciclo **vila-base, mapa, voo e resultado**. Na vila, a criança escolhe a fase e o modo no mapa. No voo, o avião decola da vila, coleta resíduos e power-ups, desvia de obstáculos e acumula transformação. No resultado, estrelas e recursos obtidos vão para o perfil, e a criança volta à vila para construir melhorias e peças. Uma sessão pode terminar pelo limite escolhido ou ser encerrada na pausa; o resumo parcial não concede conclusão ou estrelas ainda não conquistadas. ### Primeira execução -Na primeira execução, o **aviso ao supervisor** e a **calibração corporal**, quando necessários, preparam a interação. Um treino opcional ensina mirar, esperar e sair do alvo. A criança então começa com um **piloto neutro**, escolhe sua aparência e chega à **vila**. Na primeira decolagem pelo mapa, outro treino opcional ensina movimento, coleta e os três desvios com pictogramas e prática sem perda de vidas. Ambos podem ser pulados ou repetidos em Opções. A história fica disponível em Opções, e o personagem pode ser modificado pelo botão Piloto da vila. +Na primeira execução, o **aviso ao supervisor** e a **calibração corporal**, quando necessários, preparam a interação. Um treino opcional ensina mirar, esperar e sair do alvo. A criança então começa com um **piloto neutro**, escolhe sua aparência e chega à **vila**. Na primeira decolagem pelo mapa, outro treino opcional ensina movimento, coleta e os três desvios com pictogramas e prática sem perda de vidas. Ambos podem ser pulados ou repetidos em Opções. A história fica disponível em Opções, e o personagem pode ser modificado pelo botão Piloto da vila. No desktop, a tela **Pilotos** permite criar e selecionar slots locais independentes; nomes e perfis pessoais não são solicitados. A abertura é um livro ilustrado de quatro páginas: uma cidade industrial colorida, com fumaça e resíduos; uma criança que encontra um jornal na rua; a dobradura do avião sobre uma mesa de trabalho, com setas e legenda de cada dobra; e o lançamento, com um rastro de aquarela nas cores da logo. @@ -116,11 +116,11 @@ A dificuldade é a primeira escolha do mapa, em dois cartões grandes: **Normal* O combo zera se a criança passar 2,2 segundos sem coletar ou ao colidir. Nos dois modos, a dificuldade cresce ao longo de 240 segundos: a frequência de obstáculos aumenta e a velocidade sobe até 30 unidades/s no Difícil (metade no Normal); a transformação acrescenta até mais 30. -Com a criança pegando 4 de cada 10 resíduos, uma fase dura cerca de 3,7 minutos no Normal e 3,8 no Difícil, e tudo da vila e do avião fica comprado em cerca de 11 voos no Normal e 5 no Difícil (simulação em `tools/balance.py`). +O tempo e o número de voos para completar o conteúdo variam com a coleta, assistência, exploração, pausas e modo. A simulação em `tools/balance.py` é sintética e não prevê o tempo individual. Em **Opções → Preparar**, a sessão pode ser livre ou limitada a 120, 180 ou 240 segundos; ao atingir o limite, o voo termina com resultado parcial. **Exploração** mantém o voo após esgotar vidas; colisões continuam registradas. **Assistência previsível** oferece regras de ajuda estáveis durante o voo. As opções são independentes da dificuldade. ### Metas curtas -Durante o voo aparece uma meta por vez, de 20 a 60 segundos: coletar resíduos de um tipo, desviar de obstáculos na faixa do avião, passar por baixo de portais ou pegar power-ups. No Normal os alvos são menores (por exemplo, 2 resíduos ou 3 desvios; no Difícil, 6 e 6). Cada meta cumprida rende 0,5% de transformação, 6 recursos e 50 pontos. +Durante o voo aparece uma meta por vez: coletar resíduos de um tipo, desviar de obstáculos na faixa do avião, passar por baixo de portais ou pegar power-ups. Ela começa após as lições iniciais e usa alvos presentes à frente. No Normal os alvos são menores (até 2 resíduos ou 3 desvios; no Difícil, 6 e 6). Cada meta cumprida rende 0,5% de transformação, 6 recursos e 50 pontos. Após 60 segundos ativos do mundo sem conclusão, a meta dá lugar a outra oferta, sem perder pontos ou recursos; pausas não contam nesse prazo. ### Vila-base @@ -128,8 +128,8 @@ A vila tem oito melhorias, compradas com recursos. Cada uma aparece no seu lugar | Melhoria | Custo | Descrição | |---|---|---| -| Ponto de troca | 72 papel, 72 plástico | Separa os resíduos e os transforma em recursos | -| Horta urbana | 96 papel, 72 vidro | Alimento fresco plantado no meio da vila | +| Ponto de troca | 8 papel, 8 plástico | Separa os resíduos e os transforma em recursos | +| Horta urbana | 24 papel, 16 vidro | Alimento fresco plantado no meio da vila | | Painéis solares | 144 metal, 120 vidro | Microgeração de energia limpa nos telhados | | Compostor | 96 plástico, 72 metal | Restos orgânicos viram adubo para a horta | | Cisterna | 120 plástico, 96 metal | Guarda a água da chuva para regar e beber | @@ -139,7 +139,7 @@ A vila tem oito melhorias, compradas com recursos. Cada uma aparece no seu lugar ### Peças do avião -As peças são reaproveitadas de resíduos. Cada uma tem dois níveis e completa a coleção da expedição. Desde a versão 1.5, conforto, resposta, velocidade e tolerância de colisão são comuns a todos, independentemente de compras. Os níveis continuam necessários quando a fase os exige para a terceira estrela. +As peças são reaproveitadas de resíduos. Cada uma tem dois níveis e completa a coleção da expedição. Conforto, resposta, velocidade e tolerância de colisão são comuns a todos, independentemente de compras. Os níveis continuam necessários quando a fase os exige para a terceira estrela. | Peça | Nível 1 | Nível 2 | |---|---|---| @@ -192,7 +192,7 @@ Em Opções, a opção **Controle do avião** escolhe o modo: - **Recentralizar:** desligado por padrão na sprint 3. Quando ligado, cabeça, mãos e tronco refazem a postura neutra depois de 3 segundos sem o segmento. Uma preferência já salva continua valendo; a calibração explícita permite definir também quatro alcances confortáveis na sessão. - **Trocar lados:** inverte esquerda e direita, para câmeras que não espelham a imagem. - No console T-TEA, os mesmos segmentos usam os pontos da câmera do console (veja [Console T-TEA (cartucho)](#console-t-tea-cartucho)). -- **Menus:** um cursor acompanha o segmento. A permanência geral é de 2 s (ajustável de 1 a 3,5 s); Piloto e Hangar usam 3 s (ajustável de 1 a 5 s). Depois de confirmar, saia do alvo para repetir. Sem rastreamento válido a contagem pausa brevemente e depois é cancelada. +- **Menus:** um cursor acompanha o segmento. A permanência geral é de 2 s (ajustável de 1 a 3,5 s); o editor de aparência usa 3 s por padrão (ajustável de 1 a 5 s). Depois de confirmar, saia do alvo para repetir. Sem rastreamento válido, a contagem pausa brevemente e depois é cancelada. - **Sensibilidade:** de 0,5 a 2,0 vezes (padrão 1,0). Valores maiores exigem um movimento menor. - **Pausa automática:** se o segmento sai da área de captura por 1 segundo durante o voo, o jogo pausa. Ao voltar, espera a presença estável por 1,2 segundo e faz uma contagem de 3 segundos antes de retomar. - Sem webcam, sem as bibliotecas ou sem o modelo de pose, o jogo segue com teclado e mouse. Se a câmera falhar com um segmento selecionado, o motivo aparece em Opções e na calibração. @@ -320,7 +320,7 @@ O script procura o Python 3, cria o ambiente `.venv`, instala `requirements-webc ./build_linux.sh ``` -O script segue a mesma sequência com `python3` e gera `dist/Dobramundo/Dobramundo` (modo de pasta). Ele confere se o relatório do self-test contém `"status": "ok"`. No Debian ou no Ubuntu, instale antes o pacote `python3-venv`. +O script segue a mesma sequência com `python3` e gera `dist/Dobramundo/Dobramundo` (modo de pasta). Ele confere se o relatório do self-test contém `"status": "ok"`. No Debian ou no Ubuntu, instale antes `python3-venv`, `libegl1` e `libgles2`. O detector MediaPipe carrega `libEGL.so.1` e `libGLESv2.so.2`, dependências de sistema que não são embutidas no pacote; o build com `--exigir-camera` verifica essas bibliotecas e falha com instrução se alguma estiver ausente. Quem receber o pacote Linux também precisa dos dois runtimes instalados. ### Especificação e assets diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..20ce003 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,32 @@ +# Documentação do Dobramundo + +## Entrega atual + +- [Entrega 1.6](ENTREGA_1_6.md): recursos implementados, validação e limites. +- [Desempenho e webcam](validacao-v1.6/desempenho.md): medições, picos e memória. +- [Economia e rotas comunitárias](validacao-v1.6/economia/sintese.md): modelo sintético e resultados. + +## Jogar e operar + +- [Guia do jogo](GUIA_DO_JOGO.md): fluxo, controles, opções e superfícies. +- [GDD v10](GDD_Dobramundo_v10.pdf): proposta e requisitos de design. +- [Aceite presencial](VALIDACAO_PRESENCIAL.md): roteiro para equipamento e participantes. + +## Desenvolver e validar + +- [Arquitetura](arquitetura.md): plataformas, contratos e ciclo de um quadro. +- [Análise consolidada](ANALISE_CONSOLIDADA.md): diagnóstico e encaminhamento dos achados. +- [P1/P2](SPRINT_P1_P2.md): escopo e critérios da implementação 1.6. +- [Ferramentas](../tools/README.md): capturas, desempenho, rotas, economia e build. +- [Contribuição](../CONTRIBUTING.md): dependências, testes e convenções. + +## Histórico preservado + +Os relatórios abaixo descrevem suas versões e condições de teste; não são uma +declaração do comportamento de toda versão futura. Seus caminhos foram mantidos +para preservar links de releases e revisões anteriores. + +- [Entrega 1.5](ENTREGA_1_5.md) e [métricas 1.5](validacao-1.5.0.json). +- [Sprint 3](ENTREGA_SPRINT3.md), [plano](SPRINT3.md) e [métricas](validacao-sprint3.json). +- [Sprint 2](ENTREGA_SPRINT2.md) e [métricas](validacao-sprint2.json). +- [Direção em aquarela](DIRECAO_AQUARELA.md) e [validação inicial](validacao-aquarela.json). diff --git a/docs/SPRINT_P1_P2.md b/docs/SPRINT_P1_P2.md new file mode 100644 index 0000000..c0c78b5 --- /dev/null +++ b/docs/SPRINT_P1_P2.md @@ -0,0 +1,35 @@ +# P1 e P2 — meta e critérios de entrega + +Base: `f80294b` (1.5.0). Branch `codex/p1-p2-experiencia-e-manutencao`. +Solicitação: implementar os itens P1/P2 da análise consolidada, preservando os P0. + +## Frentes de implementação + +| Frente | Critério verificável | +|---|---| +| Sessões, exploração e assistência | Escolhas explícitas antes do voo; término curto preserva conquistas; exploração permite erros sem eliminação; assistência não muda sem aviso. | +| Missões e economia | Primeiro objetivo compatível com o tutorial; oportunidades correspondentes presentes; simulação com erros, pausas e interrupções. | +| Percursos regionais | Semente registrada e repetível, variações coerentes com o bioma e desafios comunitários sem ranking obrigatório. | +| Saves e pilotos | Recuperação de backup válido, escrita atômica, perfis independentes, legado preservado e falhas visíveis. | +| Assets e memória | Preparação na resolução de uso, orçamento e descarte seletivo medidos; originais e fallback preservados. | +| Manutenção | Funções divididas por responsabilidade, remoção só de referências comprovadamente mortas, fachada de entrada e texto compartilhado. | +| Testes e builds | Nomes por comportamento, helpers comuns, cobertura medida, versões fixadas por Python, builds nativos Windows/Linux e self-test do executável. | +| Entrega | Documentação, fontes e pacotes rastreáveis, validação local e CI, merge na main. | + +## Aceite presencial distinto + +Compreensão a 2–3 m, conforto nos seis controles, uso com crianças, desconexão física +e instalação no console não são demonstrados por screenshots ou testes sintéticos. +O roteiro em `VALIDACAO_PRESENCIAL.md` terá resultados explicitamente pendentes +quando o equipamento ou participantes não estiverem disponíveis. + +O console mantém PNG como formato de distribuição. A compatibilidade de um codec +no desktop não autoriza substituir os formatos no dispositivo de destino. + +## Histórico e escopo + +Não apagar branches, releases anteriores ou histórico Git. A limpeza do código +preserva os renderizadores de reserva. A formatação global será um commit próprio, +executado após as frentes paralelas terminarem. Descrição/tópicos do repositório +podem ser atualizados; prévia social será preparada como artefato se a API não +permitir aplicá-la. Não gravar imagens de câmera nem landmarks nos relatórios. diff --git a/docs/VALIDACAO_PRESENCIAL.md b/docs/VALIDACAO_PRESENCIAL.md new file mode 100644 index 0000000..6e455e4 --- /dev/null +++ b/docs/VALIDACAO_PRESENCIAL.md @@ -0,0 +1,44 @@ +# Roteiro de aceite no equipamento de destino + +Este documento não registra um ensaio já realizado. Os testes automatizados +exercitam coordenadas, projeção, estado, renderização e falhas sintéticas. As +linhas abaixo exigem observação no equipamento e com participantes disponíveis. +Não preencher como aprovado a partir do self-test ou de captura estática. + +## Preparar uma sessão + +Escolher um slot de piloto de teste, o segmento de controle e uma duração curta. +Calibrar a postura neutra e os quatro extremos confortáveis. Registrar apenas +modelo do computador/projetor, resolução, superfície, iluminação, versão, +modo de contraste, duração e resultado agregado. Não gravar vídeo, landmarks, +nome ou diagnóstico da criança nesta ficha. + +| Ensaio | Observar | Critério de aceite | Estado | +|---|---|---|---| +| Chão, mesa, parede e monitor | Avião, resíduos, obstáculos e cenário a 2–3 m | Participante distingue o que coletar, evitar e usar como passagem sem ler legenda | Pendente presencial | +| Profundidade e altura | Resíduo perto/longe, obstáculo baixo e passagem sob portal | Gesto e efeito correspondem; nenhuma colisão parece ocorrer fora do objeto | Pendente presencial | +| Seis controles | Pés, tronco em pé/sentado, mão direita/esquerda, cabeça | Alcance confortável chega aos quatro extremos e a todos os botões; perda de rastreamento pausa | Pendente presencial | +| Projeção | Quatro rotações, espelho e calibração dos cantos | Posição projetada coincide com área de interação; bordas não cortam avião | Pendente presencial | +| Webcam | Virar cabeça e sair/voltar ao enquadramento; retirar/reconectar cabo pelo operador | Sem movimento fantasma, interface responsiva, reabertura única, recalibração clara | Pendente físico | +| Exploração e assistência | Erros, pausas e término curto | Ajuda permanece previsível; sem eliminação no modo exploração; conquistas preservadas | Pendente com participante | +| Menus | Escolher aparência, trocar opções e retirar o cursor | Nenhuma confirmação involuntária em sequência; alvo e progresso de permanência compreensíveis | Pendente com participante | +| Transformação | Estado industrial colorido, etapa intermediária, solarpunk | Participante reconhece a relação entre coleta/obra e a mudança na vila | Pendente com participante | +| Uso prolongado | 20–30 min no equipamento de destino, alternando biomas e alto contraste | Sem aumento contínuo de memória, congelamentos ou perda de salvamento | Pendente físico | +| Console T-TEA | Instalar cartucho, abrir, trocar cena, concluir e reabrir sessão | Assets PNG decodificados, perfil do SDK preservado, resumo registrado uma vez | Pendente console | + +Se uma etapa falhar, registrar o gesto/situação e a semente exibida no resultado, +sem dados pessoais. Repetir a mesma rota com as mesmas opções ajuda a separar +problemas do desenho do percurso de limitações do rastreamento ou da projeção. + +## Evidência técnica disponível + +Os comandos de `tools/README.md` geram relatório de desempenho, estabilidade, +rotas e economia em pasta isolada. `benchmark_camera.py` mede captura e inferência +reais sem armazenar pixels; a medição começa após aquecimento. O timestamp de +retorno da leitura não mede a exposição do sensor, e canvas pronto não mede o +instante de luz emitida pelo projetor. Portanto, esses números não comprovam +latência física ponta a ponta nem o conforto de uma criança. + +Codecs opcionais: o suporte depende da compilação do SDL_image, conforme a +[documentação do pygame](https://www.pygame.org/docs/ref/image.html). A entrega +continua em PNG; converter no desktop não comprova suporte no console. diff --git a/docs/arquitetura.md b/docs/arquitetura.md index 3f77f65..cb6b113 100644 --- a/docs/arquitetura.md +++ b/docs/arquitetura.md @@ -215,13 +215,15 @@ No fallback, `PilotRenderer.mount` escala o corpo para a caixa do avião (com o A pintura legada do avião usa a camada `paint` e seu mapa UV, em que o verde (G) é a linha e o vermelho (R) é a coluna da textura de 256 x 256 pixels. A rota preferida da sprint usa a máscara de papel de `PaintedPlanes`. -## 9. Perfil versionado e migração +## 9. Perfis, persistência e migração -O perfil fica num único JSON (`dobramundo_perfil.json`) e é modelado pela dataclass `Profile` em `persistence.py`. Ele tem o campo `versao`, com `SCHEMA_VERSION = 1`. +`Profile` em `persistence.py` mantém o formato JSON legado (`dobramundo_perfil.json`) como slot `principal`, preservando migrações anteriores. No desktop, um índice (`profiles.json`) registra até oito slots e os demais arquivos ficam em `profiles/`; cada slot contém progresso, personalização, opções e consentimento. Os cartões são anônimos (“Piloto 1” etc.) e a prévia não ativa nem regrava o slot. O console T-TEA continua usando o armazenamento por jogador do SDK, sem substituí-lo por perfis desktop. -- **Gravação:** `save_profile` escreve um arquivo temporário (`.tmp`) e troca pelo arquivo final, de forma atômica. -- **Leitura:** `Profile.from_dict` lê campo a campo, só aceita valores do tipo esperado e ignora campos desconhecidos. Depois `normalize()` limita valores (volumes, permanência, sensibilidade, estrelas, recursos) e descarta opções que não existem mais (aviões, padrões, segmentos, melhorias). Se algo falhar, o resultado é o perfil padrão. -- **Migração:** não há migração por versão. O campo `versao` é gravado, mas não é lido. Para uma mudança incompatível, é preciso aumentar `SCHEMA_VERSION`, criar o tratamento em `from_dict` e cobrir o caso em `tests/test_progress.py`. +- **Gravação:** arquivo temporário, flush/fsync e substituição atômica. Antes de substituir um perfil ou índice válido, rotaciona até duas cópias `.bak`/`.bak.1` validadas. O limite é recuperação de arquivo: não é journal nem checkpoint de execução. +- **Leitura e recuperação:** valida tipos e normaliza faixas; arquivo ausente ou inválido tenta cópias anteriores. Índices recuperáveis podem restaurar slots órfãos válidos sem ativá-los automaticamente. Arquivo corrompido é preservado com sufixo `.corrompido`; erro de leitura bloqueia gravação ao slot na sessão para evitar sobrescrever dados que não foram lidos. +- **Falha de recuperação:** se a cópia íntegra só puder ser aberta em memória, o jogo apresenta aviso e não afirma que a restauração em disco ocorreu. A interface permite reconhecer o aviso; falhas de gravação no perfil ativo precisam ser resolvidas antes de trocar de piloto. +- **Compatibilidade:** `SCHEMA_VERSION` permanece 1; campos opcionais novos recebem padrões e perfis antigos seguem legíveis. Para uma mudança incompatível, aumentar versão, adicionar migração explícita e cobrir o legado em testes. A opção antiga `girar` continua migrada para `rotacao`. +- **Opções de sessão:** limites 0/120/180/240 segundos, exploração, assistência previsível e semente comunitária são validados antes do uso. A semente `0` escolhe uma rota aleatória por voo; o resultado registra a semente efetiva para replay. - **Importação do protótipo:** se não houver perfil, `import_legacy` lê `eco_runner_recorde.json` e `eco_runner_config.json` das pastas do protótipo (ver `legacy_data_dirs` em `paths.py`). - **Versão 1.2:** `voos_fase` e `historico` entram no perfil sem mudar `SCHEMA_VERSION` (continua 1). Campos ausentes em perfis antigos recebem o valor padrão. - **Versão 1.3:** a opção booleana `girar` vira `rotacao` (0, 90, 180 ou 270). Perfis com `girar` verdadeiro viram `rotacao = 180` (`persistence.py`). `SCHEMA_VERSION` continua 1, e campos novos, como `chao_pontos`, `alvo_frente` e `centralizar_sozinho`, recebem o valor padrão em perfis antigos. @@ -336,7 +338,17 @@ Os itens abaixo registram a implementação anterior à sprint aquarelada. Os fl - **Voo, opções e padrões**: HUD mais fino em `scenes/flight.py`; `DEFAULT_PATTERN = "liso"` em `content/planes.py`; permanência padrão de 2,0 s, com faixa de 1,0 a 3,5 s em `persistence.py` e `scenes/options.py`. -## Entrega 1.5 — confiabilidade e orçamento de recursos +## Entrega 1.6 — sessão e recuperação + +`GameCore.create_scene` fornece a fachada da fábrica de cenas, com implementação padrão e injeção opcional usada em testes. `App` e `ConsoleCore` preservam argumentos existentes e aceitam fábrica ao final da assinatura. + +`FlightRun` encerra por conclusão, colisão final, limite escolhido ou pedido de encerramento. `scenes/result.py` liquida recursos, pontos e histórico de modo idempotente por instância; encerramentos parciais não criam conclusão ou estrela. Sementes efetivas e opções selecionadas permitem abrir novamente o mesmo desafio. Isso não recupera processo encerrado à força antes de uma gravação. + +`MissionTracker` consulta alvos existentes antes de oferecer meta e espera uma nova oferta quando não há suprimento; desafios comunitários têm sementes publicadas e temas associados. Exploração evita eliminação, mas colisões continuam contando. Assistência previsível altera ajuda de forma fixa durante o voo; não é uma garantia de adequação individual. + +`WorldView` delega chão, entidades e avião a `track_layer.py`, `entity_layer.py` e `plane_layer.py`, ligados por Protocols somente de leitura em `contracts.py`; a camada de render não importa os módulos de simulação. `set_biome` descarta o cache específico do bioma anterior. O código gerado/preparado mantém fallback procedural quando o asset preparado não está disponível. + +## Entrega 1.5 — confiabilidade e orçamento de recursos (histórico) `PaintedPilot` solicita apenas suas camadas, sem decodificar cenários. O loader detecta fundos completamente opacos uma vez e conserva alfa em sprites com transparência. `WatercolorWorld` compõe apenas o horizonte visível quando o terreno cobre o restante; o fallback segue integral. `PaintedGround` usa faixas de 3 pixels e uma passagem de solo na Caatinga. Alto contraste reutiliza seus buffers; o conteúdo continua atualizado a cada desenho. @@ -352,4 +364,4 @@ A câmera desktop mantém a fonte enquanto ela encerra, permite reabertura poste `plane_stats` entrega o mesmo conforto independentemente das peças. Os campos/níveis existentes são preservados para progressão e terceira estrela. A calibração e a zona morta não são modificadas por compras. -[Análise consolidada](ANALISE_CONSOLIDADA.md) e [validação da entrega](ENTREGA_1_5.md) detalham o escopo e os limites. +[Análise consolidada](ANALISE_CONSOLIDADA.md), [notas da entrega 1.6](ENTREGA_1_6.md) e [roteiro presencial](VALIDACAO_PRESENCIAL.md) detalham o escopo e os limites. A [entrega 1.5](ENTREGA_1_5.md) é histórica. diff --git a/docs/screenshots/v160-manaus.png b/docs/screenshots/v160-manaus.png new file mode 100644 index 0000000..2478456 Binary files /dev/null and b/docs/screenshots/v160-manaus.png differ diff --git a/docs/screenshots/v160-petrolina.png b/docs/screenshots/v160-petrolina.png new file mode 100644 index 0000000..0dd0013 Binary files /dev/null and b/docs/screenshots/v160-petrolina.png differ diff --git a/docs/validacao-v1.6/auditoria-assets.txt b/docs/validacao-v1.6/auditoria-assets.txt new file mode 100644 index 0000000..e48e76b --- /dev/null +++ b/docs/validacao-v1.6/auditoria-assets.txt @@ -0,0 +1 @@ +OK: 39 originals and 13 prepared variants verified diff --git a/docs/validacao-v1.6/baseline-current-runtime.json b/docs/validacao-v1.6/baseline-current-runtime.json new file mode 100644 index 0000000..696698b --- /dev/null +++ b/docs/validacao-v1.6/baseline-current-runtime.json @@ -0,0 +1,232 @@ +{ + "conditions": "CPU; SDL dummy; no camera; 1100x650; fresh process; 60 warmup frames per case", + "pacing": "uncapped stress", + "python": "3.12.10", + "platform": "Windows-11-10.0.26200-SP0", + "camera_clock_resolution_ms": 15.625, + "startup_ms": 2771.95, + "rss_before_bytes": 41447424, + "rss_after_bytes": 209985536, + "rss_delta_bytes": 168538112, + "startup_watercolor_count": 6, + "startup_watercolor_bytes": 37748428, + "flights": { + "amazonia_normal": { + "frame": { + "median_ms": 8.163, + "p95_ms": 11.58, + "p99_ms": 13.907, + "max_ms": 15.116 + }, + "scene_setup_ms": 19.973, + "warmup": { + "median_ms": 9.474, + "p95_ms": 14.3, + "p99_ms": 671.14, + "max_ms": 671.14 + }, + "first_frame_ms": 671.14, + "frames_measured": 600, + "within_60fps_budget_fraction": 1.0, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 1.733, + "p99_ms": 2.492, + "max_ms": 3.187 + }, + "ground": { + "median_ms": 4.158, + "p95_ms": 6.378, + "p99_ms": 7.806, + "max_ms": 10.049 + }, + "background": { + "median_ms": 6.047, + "p95_ms": 9.215, + "p99_ms": 10.853, + "max_ms": 13.229 + }, + "world": { + "median_ms": 6.968, + "p95_ms": 10.143, + "p99_ms": 12.201, + "max_ms": 14.035 + }, + "present": { + "median_ms": 0.308, + "p95_ms": 0.656, + "p99_ms": 0.816, + "max_ms": 0.94 + } + }, + "rss_bytes": 463044608 + }, + "amazonia_contrast": { + "frame": { + "median_ms": 10.564, + "p95_ms": 13.933, + "p99_ms": 16.11, + "max_ms": 19.912 + }, + "scene_setup_ms": 5.444, + "warmup": { + "median_ms": 9.916, + "p95_ms": 12.699, + "p99_ms": 40.127, + "max_ms": 40.127 + }, + "first_frame_ms": 40.127, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.9933, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 0.986, + "p99_ms": 2.248, + "max_ms": 2.812 + }, + "ground": { + "median_ms": 4.093, + "p95_ms": 5.473, + "p99_ms": 6.994, + "max_ms": 8.635 + }, + "desaturate": { + "median_ms": 1.801, + "p95_ms": 2.74, + "p99_ms": 3.395, + "max_ms": 3.976 + }, + "background": { + "median_ms": 7.279, + "p95_ms": 9.953, + "p99_ms": 11.636, + "max_ms": 13.742 + }, + "world": { + "median_ms": 9.373, + "p95_ms": 12.337, + "p99_ms": 14.703, + "max_ms": 17.194 + }, + "present": { + "median_ms": 0.282, + "p95_ms": 0.635, + "p99_ms": 0.741, + "max_ms": 0.931 + } + }, + "rss_bytes": 479715328 + }, + "caatinga_normal": { + "frame": { + "median_ms": 5.585, + "p95_ms": 7.705, + "p99_ms": 9.132, + "max_ms": 10.476 + }, + "scene_setup_ms": 7.102, + "warmup": { + "median_ms": 4.87, + "p95_ms": 6.863, + "p99_ms": 325.474, + "max_ms": 325.474 + }, + "first_frame_ms": 325.474, + "frames_measured": 600, + "within_60fps_budget_fraction": 1.0, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 1.51, + "p99_ms": 2.212, + "max_ms": 2.771 + }, + "ground": { + "median_ms": 1.753, + "p95_ms": 2.631, + "p99_ms": 2.998, + "max_ms": 4.911 + }, + "background": { + "median_ms": 3.588, + "p95_ms": 5.69, + "p99_ms": 6.793, + "max_ms": 7.342 + }, + "world": { + "median_ms": 4.426, + "p95_ms": 6.622, + "p99_ms": 7.909, + "max_ms": 8.681 + }, + "present": { + "median_ms": 0.276, + "p95_ms": 0.616, + "p99_ms": 0.806, + "max_ms": 0.91 + } + }, + "rss_bytes": 545624064 + }, + "caatinga_contrast": { + "frame": { + "median_ms": 8.962, + "p95_ms": 12.515, + "p99_ms": 14.688, + "max_ms": 16.512 + }, + "scene_setup_ms": 8.089, + "warmup": { + "median_ms": 7.638, + "p95_ms": 10.546, + "p99_ms": 10.669, + "max_ms": 10.669 + }, + "first_frame_ms": 10.669, + "frames_measured": 600, + "within_60fps_budget_fraction": 1.0, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 1.878, + "p99_ms": 2.406, + "max_ms": 2.659 + }, + "ground": { + "median_ms": 1.803, + "p95_ms": 2.77, + "p99_ms": 3.393, + "max_ms": 4.292 + }, + "desaturate": { + "median_ms": 1.845, + "p95_ms": 2.983, + "p99_ms": 3.371, + "max_ms": 3.602 + }, + "background": { + "median_ms": 5.686, + "p95_ms": 8.405, + "p99_ms": 10.092, + "max_ms": 10.852 + }, + "world": { + "median_ms": 7.708, + "p95_ms": 11.155, + "p99_ms": 13.306, + "max_ms": 14.595 + }, + "present": { + "median_ms": 0.286, + "p95_ms": 0.59, + "p99_ms": 0.752, + "max_ms": 0.791 + } + }, + "rss_bytes": 557965312 + } + }, + "status": "ok" +} \ No newline at end of file diff --git a/docs/validacao-v1.6/camera-local.json b/docs/validacao-v1.6/camera-local.json new file mode 100644 index 0000000..08b359d --- /dev/null +++ b/docs/validacao-v1.6/camera-local.json @@ -0,0 +1,37 @@ +{ + "status": "ok", + "reason": null, + "device": 0, + "requested_seconds": 8.0, + "elapsed_seconds": 14.969, + "warmup_timeout_seconds": 15.0, + "time_to_first_result_seconds": 5.781, + "measurement_seconds": 8.032, + "measurement_window_complete": true, + "minimum_samples": 5, + "samples_in_window": 211, + "resolution": [ + 640, + 480 + ], + "frames_read": 212, + "inferences": 211, + "published": 211, + "published_total": 213, + "stale_dropped": 0, + "read_failures": 0, + "capture_fps": 26.39, + "inference_fps": 26.27, + "last_inference_ms": 94.0, + "startup_ms": 5766.0, + "capture_interval_ms": 94.0, + "inference_interval_ms": 94.0, + "last_result_age_ms": 94.0, + "last_published_age_ms": 1172.0, + "error_count": 0, + "error": null, + "thread_still_running_after_stop": false, + "age_basis": "monotonic time immediately after VideoCapture.read returns", + "sensor_exposure_timestamp_available": false, + "image_or_landmarks_saved": false +} diff --git a/docs/validacao-v1.6/capturas.json b/docs/validacao-v1.6/capturas.json new file mode 100644 index 0000000..33f4b39 --- /dev/null +++ b/docs/validacao-v1.6/capturas.json @@ -0,0 +1,22 @@ +{ + "profile": "synthetic", + "flight_capture_note": "after 120 frames, clear transient run.beams and draw one clean final frame", + "screens": [ + "vila", + "mapa", + "hangar", + "piloto", + "preparar", + "opcoes", + "meu-voo-0", + "meu-voo-1", + "perfis", + "perfis-erro", + "vila-recuperacao", + "amazonia", + "amazonia-contraste", + "caatinga", + "caatinga-contraste" + ], + "layout_failures": [] +} diff --git a/docs/validacao-v1.6/cobertura.json b/docs/validacao-v1.6/cobertura.json new file mode 100644 index 0000000..aa841b4 --- /dev/null +++ b/docs/validacao-v1.6/cobertura.json @@ -0,0 +1,15 @@ +{ + "ci": "https://github.com/lapsin-maker/dobramundo/actions/runs/40236396562", + "commit": "d47035cd9d1acb75ac01a81bb25bd87a7c1e71d4", + "python": [ + "3.8", + "3.12" + ], + "lines_covered": 9352, + "lines_valid": 11845, + "branches_covered": 2787, + "branches_valid": 4206, + "line_rate": 0.7895, + "branch_rate": 0.6626, + "scope": "dobramundo, branch coverage; not a quality guarantee" +} diff --git a/docs/validacao-v1.6/desempenho.md b/docs/validacao-v1.6/desempenho.md new file mode 100644 index 0000000..e3eebcd --- /dev/null +++ b/docs/validacao-v1.6/desempenho.md @@ -0,0 +1,57 @@ +# Desempenho e câmera — versão 1.6 + +## Equipamento e condições + +Intel Core i7-10750H (6 núcleos/12 threads), 32 GB RAM, Windows 11 build 26200, Python 3.12.10, pygame 2.6.1; render 1100×650 em CPU. Os relatórios foram coletados sem outros testes ou builds locais concorrentes. Aplicativos de uso normal não foram controlados. São observações deste equipamento e desta sessão, sem garantia de repetição ou de desempenho noutro computador. + +Os cenários sem câmera usam SDL dummy, processo novo e 60 quadros de aquecimento por caso; alguns relatórios estão em estresse sem limite de quadros. As medições com câmera indicam alvo de 60 FPS e excluem o tempo de sleep das durações de quadro. Quantidade de quadros: 600 por cenário, exceto `runtime-camera-paced`, com 480. + +## Inicialização e memória — comparação sem avatar + +O baseline 1.5 foi extraído do commit `f80294b` para uma pasta isolada e executado com o mesmo Python da medição 1.6. O par (`baseline-current` e `runtime-seed7`) usa a semente 7, sem avatar. Inicialização fria, delta de RSS e maior RSS amostrado ao fim dos cenários (não o pico instantâneo do processo): + +| Relatório | Startup frio | Delta RSS após inicialização | Pico RSS observado nos voos | +|---|---:|---:|---:| +| 1.5 baseline, `baseline-current` | 2.772 ms | 160,7 MiB | 532,1 MiB | +| 1.6, `runtime-seed7` | 1.084 ms | 87,2 MiB | 258,9 MiB | + +Neste par, o RSS máximo observado caiu cerca de 51% e o delta inicial cerca de 46%. A inicialização reportada também foi menor. São resultados de duas execuções, não uma distribuição de repetições: não atribuir toda a diferença ao código nem generalizar para outros equipamentos. O primeiro quadro dos quatro casos variou de 10 a 671 ms no baseline e de 20 a 352 ms em `runtime-seed7`; o pico de primeiro quadro não é o startup frio. + +## Duração dos quadros sem câmera + +P95 e máximo em milissegundos. Valores maiores são quadros mais demorados. + +| Caso | 1.5 baseline p95/máx | 1.6 sem avatar p95/máx | +|---|---:|---:| +| Amazônia, normal | 11,580 / 15,116 | 13,974 / 20,393 | +| Amazônia, alto contraste | 13,933 / 19,912 | 15,741 / 28,772 | +| Caatinga, normal | 7,705 / 10,476 | 9,917 / 12,688 | +| Caatinga, alto contraste | 12,515 / 16,512 | 12,570 / 16,275 | + +O conjunto não mostra melhora geral do tempo de CPU por quadro; os dois casos da Amazônia e Caatinga normal tiveram p95 maior em 1.6. Em nova execução da semente 7 com avatar sintético e sem câmera, o p95/máximo foi 11,966/18,544 ms (Amazônia normal), 19,169/40,274 ms (Amazônia contraste), 10,351/14,958 ms (Caatinga normal) e 13,491/18,831 ms (Caatinga contraste). O avatar é uma carga específica, não um agregado de aparências. + +## Câmera local e picos + +No relatório final com avatar sintético e inferência de câmera em paralelo, p95/máximo por caso foi: Amazônia normal 18,050/41,875 ms; Amazônia contraste 17,541/22,050 ms; Caatinga normal 38,394/67,459 ms; Caatinga contraste 16,098/21,147 ms. Outros dois ensaios sem avatar, paced e recheck, registraram máximos de 55,321 ms e 18,071 ms, respectivamente, em Caatinga normal; o recheck chegou a 29,231 ms em Amazônia/contraste. Esses picos são preservados aqui e mostram que não há garantia de 60 FPS. + +Os ensaios de câmera em paralelo reportaram 28,05–29,55 leituras e inferências por segundo, sem erros, falhas de leitura ou amostras descartadas por idade nesses arquivos. Isso descreve a captura/inferência observadas, não a resposta física do jogo. `camera-local.json` contém uma janela medida de 8,032 s após aquecimento de 5,781 s: 26,39 FPS de captura e 26,27 inferências/s; a última inferência durou 94 ms na resolução de relógio informada (15,625 ms). A idade de 1.172 ms do último resultado ocorreu após o encerramento da câmera; não é latência humana nem medida de reação do controle. + +O benchmark consulta a idade do último resultado disponível logo após a chamada de apresentação. O render continua com entrada sintética enquanto o detector processa a webcam em paralelo; essa amostra não é necessariamente a leitura consumida pelo controle do jogo. A origem temporal é o retorno de `VideoCapture.read`, que **não** inclui buffering/exposição do sensor, emissão do projetor nem o instante em que a imagem é vista no chão. Não equivale a latência ponta a ponta. A métrica da calibração do jogo acompanha separadamente a leitura efetivamente consumida até o canvas pronto; os contratos de sequência/relógio são testados. `last_result_age` após `stop` também não é latência de movimento. + +## Soak prolongado + +O [soak de 30 ciclos](soak.json) concluiu sem falhas: 1.215,5 s simulados (20 min 15,5 s), em 758,138 s de parede. Foram 72.000 quadros de voo, além das visitas repetidas à vila, mapa, piloto, hangar e preparação. Alternou os dois biomas, contraste, cabelos, tons de pele, cadeira e andador; sem câmera e com invencibilidade apenas para manter a carga de render. O máximo foi 27 entidades vivas, abaixo do limite de diagnóstico de 300. + +RSS amostrado ao final de cada ciclo: 419,5 MiB no primeiro, máximo 559,6 MiB, e 542,5 MiB no último. Houve aquecimento/acúmulo inicial de variantes; nos dez ciclos finais o intervalo foi 537,3–555,0 MiB, sem crescimento monotônico. O último inventário reteve aproximadamente 309 MiB estimados de superfícies (o cálculo conservador pode contar subsurfaces compartilhadas). Isso não prova ausência de todo vazamento nem limite de RAM no console. A carga prolongada com múltiplas aparências é diferente dos quatro voos curtos usados na comparação anterior. + +## Relatórios JSON preservados + +Os arquivos abaixo são cópias dos relatórios indicados; não incluem dados de perfil. Foi feita inspeção de strings para caminhos absolutos e não havia nenhum a remover. + +- [baseline-current-runtime.json](baseline-current-runtime.json) +- [runtime-seed7-runtime.json](runtime-seed7-runtime.json) +- [runtime-avatar-runtime.json](runtime-avatar-runtime.json) +- [runtime-avatar-camera-runtime.json](runtime-avatar-camera-runtime.json) +- [runtime-camera-paced-runtime.json](runtime-camera-paced-runtime.json) +- [runtime-camera-recheck-runtime.json](runtime-camera-recheck-runtime.json) +- [camera-local.json](camera-local.json) diff --git a/docs/validacao-v1.6/economia/audit-community-routes.json b/docs/validacao-v1.6/economia/audit-community-routes.json new file mode 100644 index 0000000..6c38f05 --- /dev/null +++ b/docs/validacao-v1.6/economia/audit-community-routes.json @@ -0,0 +1,500 @@ +{ + "model": "world-route-planner-v1", + "contract": "planner geometric route safety only; not user reachability", + "cycles_per_world": 500, + "dt_s": 0.05, + "official_seeds": [ + 20261025, + 41721, + 90817, + 203011 + ], + "cases": [ + { + "biome": "amazonia", + "mode": "normal", + "intro": false, + "seed": 20261025, + "theme": "encontro_das_aguas", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 23, + "kept": 23, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "normal", + "intro": false, + "seed": 41721, + "theme": "porto_de_manaus", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 18, + "kept": 18, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "normal", + "intro": false, + "seed": 90817, + "theme": "igarapes", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 9, + "kept": 9, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "normal", + "intro": false, + "seed": 203011, + "theme": "trilha_da_floresta", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 21, + "kept": 21, + "adjusted": 1, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "normal", + "intro": true, + "seed": 20261025, + "theme": "encontro_das_aguas", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 8, + "kept": 8, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "normal", + "intro": true, + "seed": 41721, + "theme": "porto_de_manaus", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 8, + "kept": 8, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "normal", + "intro": true, + "seed": 90817, + "theme": "igarapes", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 11, + "kept": 11, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "normal", + "intro": true, + "seed": 203011, + "theme": "trilha_da_floresta", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 9, + "kept": 9, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "intro": false, + "seed": 20261025, + "theme": "encontro_das_aguas", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 42, + "kept": 42, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "intro": false, + "seed": 41721, + "theme": "porto_de_manaus", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 38, + "kept": 38, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "intro": false, + "seed": 90817, + "theme": "igarapes", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 23, + "kept": 23, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "intro": false, + "seed": 203011, + "theme": "trilha_da_floresta", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 39, + "kept": 39, + "adjusted": 3, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "intro": true, + "seed": 20261025, + "theme": "encontro_das_aguas", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 11, + "kept": 11, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "intro": true, + "seed": 41721, + "theme": "porto_de_manaus", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 6, + "kept": 6, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "intro": true, + "seed": 90817, + "theme": "igarapes", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 9, + "kept": 9, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "intro": true, + "seed": 203011, + "theme": "trilha_da_floresta", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 9, + "kept": 9, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "normal", + "intro": false, + "seed": 20261025, + "theme": "pomares_do_sao_francisco", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 23, + "kept": 23, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "normal", + "intro": false, + "seed": 41721, + "theme": "ribeira_de_petrolina", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 18, + "kept": 18, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "normal", + "intro": false, + "seed": 90817, + "theme": "energia_do_sertao", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 9, + "kept": 9, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "normal", + "intro": false, + "seed": 203011, + "theme": "travessia_da_caatinga", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 21, + "kept": 21, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "normal", + "intro": true, + "seed": 20261025, + "theme": "pomares_do_sao_francisco", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 8, + "kept": 8, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "normal", + "intro": true, + "seed": 41721, + "theme": "ribeira_de_petrolina", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 8, + "kept": 8, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "normal", + "intro": true, + "seed": 90817, + "theme": "energia_do_sertao", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 11, + "kept": 11, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "normal", + "intro": true, + "seed": 203011, + "theme": "travessia_da_caatinga", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 9, + "kept": 9, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "intro": false, + "seed": 20261025, + "theme": "pomares_do_sao_francisco", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 42, + "kept": 42, + "adjusted": 1, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "intro": false, + "seed": 41721, + "theme": "ribeira_de_petrolina", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 38, + "kept": 38, + "adjusted": 1, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "intro": false, + "seed": 90817, + "theme": "energia_do_sertao", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 23, + "kept": 23, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "intro": false, + "seed": 203011, + "theme": "travessia_da_caatinga", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 39, + "kept": 39, + "adjusted": 1, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "intro": true, + "seed": 20261025, + "theme": "pomares_do_sao_francisco", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 11, + "kept": 11, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "intro": true, + "seed": 41721, + "theme": "ribeira_de_petrolina", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 6, + "kept": 6, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "intro": true, + "seed": 90817, + "theme": "energia_do_sertao", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 9, + "kept": 9, + "adjusted": 0, + "skipped": 0, + "passed": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "intro": true, + "seed": 203011, + "theme": "travessia_da_caatinga", + "initial_independent_route": true, + "frontier_after_25s": true, + "tutorial_failures": 0, + "attempted": 9, + "kept": 9, + "adjusted": 0, + "skipped": 0, + "passed": true + } + ], + "failures": [], + "summary": { + "cases": 32, + "passed": 32, + "failures": 0 + } +} diff --git a/docs/validacao-v1.6/economia/baseline-amazonia-8.json b/docs/validacao-v1.6/economia/baseline-amazonia-8.json new file mode 100644 index 0000000..1e9f9f1 --- /dev/null +++ b/docs/validacao-v1.6/economia/baseline-amazonia-8.json @@ -0,0 +1,604 @@ +{ + "model": "dynamic-position-agent-v1", + "limitations": [ + "synthetic controller, not a child or usability study", + "approach decisions use simplified one-obstacle route targets", + "results do not establish comfort, fairness, or physical reachability" + ], + "parameters": { + "biome": "amazonia", + "collect_attempt_probability": 0.4, + "deliberate_decision_error_probability": 0.1, + "pause_seconds_per_active_minute": 0.0, + "interrupt_after_active_seconds": 0.0, + "session_limit_seconds": 0, + "reaction_seconds": 0.35, + "input_latency_seconds": 0.25, + "exploration": false, + "assistance": false, + "flight_count_per_mode": 8, + "seed_start": 1 + }, + "collection_costs": { + "papel": 656, + "plastico": 824, + "metal": 1224, + "vidro": 640 + }, + "mean_resources_by_mode": { + "normal": { + "papel": 5.5, + "plastico": 9.25, + "metal": 9.5, + "vidro": 6.75 + }, + "dificil": { + "papel": 6.5, + "plastico": 7.375, + "metal": 8.0, + "vidro": 8.625 + } + }, + "runs": [ + { + "biome": "amazonia", + "mode": "normal", + "seed": 1, + "seconds_active": 39.917, + "seconds_wall": 39.917, + "max_player_displacement": 234.039, + "stage_times_s": [], + "restoration": 16.12, + "resources": { + "papel": 8, + "plastico": 8, + "metal": 12, + "vidro": 14 + }, + "resource_total": 42, + "collected": 9, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 2, + "nao_tentadas": 12, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 2, + "seconds_active": 41.083, + "seconds_wall": 41.083, + "max_player_displacement": 233.15, + "stage_times_s": [], + "restoration": 10.9, + "resources": { + "papel": 4, + "plastico": 8, + "metal": 8, + "vidro": 0 + }, + "resource_total": 20, + "collected": 5, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 0, + "sem_rota_simplificada": 3, + "nao_tentadas": 8, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 3, + "seconds_active": 40.533, + "seconds_wall": 40.533, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 8, + "vidro": 0 + }, + "resource_total": 12, + "collected": 3, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 1, + "nao_tentadas": 6, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 4, + "seconds_active": 26.25, + "seconds_wall": 26.25, + "max_player_displacement": 221.653, + "stage_times_s": [], + "restoration": 5.0, + "resources": { + "papel": 0, + "plastico": 0, + "metal": 0, + "vidro": 0 + }, + "resource_total": 0, + "collected": 0, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 3, + "nao_tentadas": 9, + "alvos_de_coleta": 1 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 5, + "seconds_active": 58.783, + "seconds_wall": 58.783, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 16.12, + "resources": { + "papel": 4, + "plastico": 16, + "metal": 8, + "vidro": 14 + }, + "resource_total": 42, + "collected": 9, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 3, + "nao_tentadas": 17, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 6, + "seconds_active": 105.717, + "seconds_wall": 105.717, + "max_player_displacement": 230.418, + "stage_times_s": [], + "restoration": 25.02, + "resources": { + "papel": 12, + "plastico": 24, + "metal": 20, + "vidro": 18 + }, + "resource_total": 74, + "collected": 14, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 1, + "sem_rota_simplificada": 6, + "nao_tentadas": 20, + "alvos_de_coleta": 13 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 7, + "seconds_active": 30.783, + "seconds_wall": 30.783, + "max_player_displacement": 221.643, + "stage_times_s": [], + "restoration": 7.36, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 4, + "vidro": 0 + }, + "resource_total": 8, + "collected": 2, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 1, + "nao_tentadas": 5, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 8, + "seconds_active": 61.483, + "seconds_wall": 61.483, + "max_player_displacement": 231.305, + "stage_times_s": [], + "restoration": 20.48, + "resources": { + "papel": 8, + "plastico": 18, + "metal": 16, + "vidro": 8 + }, + "resource_total": 50, + "collected": 11, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 7, + "sem_rota_simplificada": 3, + "nao_tentadas": 21, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 1, + "seconds_active": 9.033, + "seconds_wall": 9.033, + "max_player_displacement": 208.382, + "stage_times_s": [], + "restoration": 5.92, + "resources": { + "papel": 3, + "plastico": 1, + "metal": 1, + "vidro": 3 + }, + "resource_total": 8, + "collected": 8, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 4, + "sem_rota_simplificada": 2, + "nao_tentadas": 17, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 2, + "seconds_active": 41.933, + "seconds_wall": 41.933, + "max_player_displacement": 209.907, + "stage_times_s": [], + "restoration": 14.02, + "resources": { + "papel": 16, + "plastico": 17, + "metal": 20, + "vidro": 26 + }, + "resource_total": 79, + "collected": 67, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 7, + "nao_tentadas": 16, + "alvos_de_coleta": 13 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 3, + "seconds_active": 19.217, + "seconds_wall": 19.217, + "max_player_displacement": 221.763, + "stage_times_s": [], + "restoration": 6.38, + "resources": { + "papel": 3, + "plastico": 3, + "metal": 6, + "vidro": 0 + }, + "resource_total": 12, + "collected": 12, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 6, + "sem_rota_simplificada": 3, + "nao_tentadas": 20, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 4, + "seconds_active": 17.767, + "seconds_wall": 17.767, + "max_player_displacement": 221.774, + "stage_times_s": [], + "restoration": 7.23, + "resources": { + "papel": 1, + "plastico": 3, + "metal": 5, + "vidro": 12 + }, + "resource_total": 21, + "collected": 15, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 2, + "nao_tentadas": 16, + "alvos_de_coleta": 7 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 5, + "seconds_active": 26.75, + "seconds_wall": 26.75, + "max_player_displacement": 216.683, + "stage_times_s": [], + "restoration": 6.96, + "resources": { + "papel": 3, + "plastico": 5, + "metal": 6, + "vidro": 3 + }, + "resource_total": 17, + "collected": 17, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 5, + "nao_tentadas": 14, + "alvos_de_coleta": 13 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 6, + "seconds_active": 28.483, + "seconds_wall": 28.483, + "max_player_displacement": 215.143, + "stage_times_s": [], + "restoration": 7.8, + "resources": { + "papel": 5, + "plastico": 10, + "metal": 6, + "vidro": 5 + }, + "resource_total": 26, + "collected": 20, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 1, + "sem_rota_simplificada": 4, + "nao_tentadas": 18, + "alvos_de_coleta": 5 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 7, + "seconds_active": 33.333, + "seconds_wall": 33.333, + "max_player_displacement": 219.797, + "stage_times_s": [], + "restoration": 11.6, + "resources": { + "papel": 14, + "plastico": 12, + "metal": 16, + "vidro": 15 + }, + "resource_total": 57, + "collected": 51, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 9, + "nao_tentadas": 24, + "alvos_de_coleta": 18 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 8, + "seconds_active": 23.467, + "seconds_wall": 23.467, + "max_player_displacement": 220.609, + "stage_times_s": [], + "restoration": 7.76, + "resources": { + "papel": 7, + "plastico": 8, + "metal": 4, + "vidro": 5 + }, + "resource_total": 24, + "collected": 24, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 5, + "sem_rota_simplificada": 3, + "nao_tentadas": 26, + "alvos_de_coleta": 11 + }, + "exploration": false, + "assistance": false + } + ] +} \ No newline at end of file diff --git a/docs/validacao-v1.6/economia/baseline-caatinga-8.json b/docs/validacao-v1.6/economia/baseline-caatinga-8.json new file mode 100644 index 0000000..46899d1 --- /dev/null +++ b/docs/validacao-v1.6/economia/baseline-caatinga-8.json @@ -0,0 +1,604 @@ +{ + "model": "dynamic-position-agent-v1", + "limitations": [ + "synthetic controller, not a child or usability study", + "approach decisions use simplified one-obstacle route targets", + "results do not establish comfort, fairness, or physical reachability" + ], + "parameters": { + "biome": "caatinga", + "collect_attempt_probability": 0.4, + "deliberate_decision_error_probability": 0.1, + "pause_seconds_per_active_minute": 0.0, + "interrupt_after_active_seconds": 0.0, + "session_limit_seconds": 0, + "reaction_seconds": 0.35, + "input_latency_seconds": 0.25, + "exploration": false, + "assistance": false, + "flight_count_per_mode": 8, + "seed_start": 1 + }, + "collection_costs": { + "papel": 656, + "plastico": 824, + "metal": 1224, + "vidro": 640 + }, + "mean_resources_by_mode": { + "normal": { + "papel": 6.5, + "plastico": 9.25, + "metal": 10.0, + "vidro": 5.5 + }, + "dificil": { + "papel": 6.5, + "plastico": 7.375, + "metal": 8.0, + "vidro": 8.625 + } + }, + "runs": [ + { + "biome": "caatinga", + "mode": "normal", + "seed": 1, + "seconds_active": 39.917, + "seconds_wall": 39.917, + "max_player_displacement": 234.039, + "stage_times_s": [], + "restoration": 16.12, + "resources": { + "papel": 8, + "plastico": 8, + "metal": 12, + "vidro": 14 + }, + "resource_total": 42, + "collected": 9, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 2, + "nao_tentadas": 12, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 2, + "seconds_active": 41.083, + "seconds_wall": 41.083, + "max_player_displacement": 233.15, + "stage_times_s": [], + "restoration": 10.9, + "resources": { + "papel": 4, + "plastico": 8, + "metal": 8, + "vidro": 0 + }, + "resource_total": 20, + "collected": 5, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 0, + "sem_rota_simplificada": 3, + "nao_tentadas": 8, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 3, + "seconds_active": 41.783, + "seconds_wall": 41.783, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 9.72, + "resources": { + "papel": 4, + "plastico": 4, + "metal": 8, + "vidro": 0 + }, + "resource_total": 16, + "collected": 4, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 2, + "nao_tentadas": 7, + "alvos_de_coleta": 5 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 4, + "seconds_active": 26.25, + "seconds_wall": 26.25, + "max_player_displacement": 221.653, + "stage_times_s": [], + "restoration": 5.0, + "resources": { + "papel": 0, + "plastico": 0, + "metal": 0, + "vidro": 0 + }, + "resource_total": 0, + "collected": 0, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 3, + "nao_tentadas": 9, + "alvos_de_coleta": 1 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 5, + "seconds_active": 58.783, + "seconds_wall": 58.783, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 14.44, + "resources": { + "papel": 8, + "plastico": 12, + "metal": 8, + "vidro": 4 + }, + "resource_total": 32, + "collected": 8, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 4, + "nao_tentadas": 16, + "alvos_de_coleta": 11 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 6, + "seconds_active": 100.683, + "seconds_wall": 100.683, + "max_player_displacement": 230.099, + "stage_times_s": [], + "restoration": 27.38, + "resources": { + "papel": 16, + "plastico": 24, + "metal": 24, + "vidro": 18 + }, + "resource_total": 82, + "collected": 16, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 1, + "sem_rota_simplificada": 7, + "nao_tentadas": 20, + "alvos_de_coleta": 13 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 7, + "seconds_active": 30.783, + "seconds_wall": 30.783, + "max_player_displacement": 221.643, + "stage_times_s": [], + "restoration": 7.36, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 4, + "vidro": 0 + }, + "resource_total": 8, + "collected": 2, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 1, + "nao_tentadas": 5, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 8, + "seconds_active": 61.483, + "seconds_wall": 61.483, + "max_player_displacement": 231.305, + "stage_times_s": [], + "restoration": 20.48, + "resources": { + "papel": 8, + "plastico": 18, + "metal": 16, + "vidro": 8 + }, + "resource_total": 50, + "collected": 11, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 7, + "sem_rota_simplificada": 3, + "nao_tentadas": 21, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 1, + "seconds_active": 9.033, + "seconds_wall": 9.033, + "max_player_displacement": 208.382, + "stage_times_s": [], + "restoration": 5.92, + "resources": { + "papel": 3, + "plastico": 1, + "metal": 1, + "vidro": 3 + }, + "resource_total": 8, + "collected": 8, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 4, + "sem_rota_simplificada": 2, + "nao_tentadas": 17, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 2, + "seconds_active": 41.933, + "seconds_wall": 41.933, + "max_player_displacement": 209.907, + "stage_times_s": [], + "restoration": 14.02, + "resources": { + "papel": 16, + "plastico": 17, + "metal": 20, + "vidro": 26 + }, + "resource_total": 79, + "collected": 67, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 7, + "nao_tentadas": 16, + "alvos_de_coleta": 13 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 3, + "seconds_active": 19.217, + "seconds_wall": 19.217, + "max_player_displacement": 221.763, + "stage_times_s": [], + "restoration": 6.38, + "resources": { + "papel": 3, + "plastico": 3, + "metal": 6, + "vidro": 0 + }, + "resource_total": 12, + "collected": 12, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 6, + "sem_rota_simplificada": 3, + "nao_tentadas": 20, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 4, + "seconds_active": 17.767, + "seconds_wall": 17.767, + "max_player_displacement": 221.774, + "stage_times_s": [], + "restoration": 7.23, + "resources": { + "papel": 1, + "plastico": 3, + "metal": 5, + "vidro": 12 + }, + "resource_total": 21, + "collected": 15, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 2, + "nao_tentadas": 16, + "alvos_de_coleta": 7 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 5, + "seconds_active": 26.75, + "seconds_wall": 26.75, + "max_player_displacement": 216.683, + "stage_times_s": [], + "restoration": 6.96, + "resources": { + "papel": 3, + "plastico": 5, + "metal": 6, + "vidro": 3 + }, + "resource_total": 17, + "collected": 17, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 5, + "nao_tentadas": 14, + "alvos_de_coleta": 13 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 6, + "seconds_active": 28.483, + "seconds_wall": 28.483, + "max_player_displacement": 215.143, + "stage_times_s": [], + "restoration": 7.8, + "resources": { + "papel": 5, + "plastico": 10, + "metal": 6, + "vidro": 5 + }, + "resource_total": 26, + "collected": 20, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 1, + "sem_rota_simplificada": 4, + "nao_tentadas": 18, + "alvos_de_coleta": 5 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 7, + "seconds_active": 33.333, + "seconds_wall": 33.333, + "max_player_displacement": 219.797, + "stage_times_s": [], + "restoration": 11.6, + "resources": { + "papel": 14, + "plastico": 12, + "metal": 16, + "vidro": 15 + }, + "resource_total": 57, + "collected": 51, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 9, + "nao_tentadas": 24, + "alvos_de_coleta": 18 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 8, + "seconds_active": 23.483, + "seconds_wall": 23.483, + "max_player_displacement": 220.609, + "stage_times_s": [], + "restoration": 7.76, + "resources": { + "papel": 7, + "plastico": 8, + "metal": 4, + "vidro": 5 + }, + "resource_total": 24, + "collected": 24, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 5, + "sem_rota_simplificada": 3, + "nao_tentadas": 26, + "alvos_de_coleta": 11 + }, + "exploration": false, + "assistance": false + } + ] +} \ No newline at end of file diff --git a/docs/validacao-v1.6/economia/errors-early-stop-amazonia-8.json b/docs/validacao-v1.6/economia/errors-early-stop-amazonia-8.json new file mode 100644 index 0000000..8bd6c40 --- /dev/null +++ b/docs/validacao-v1.6/economia/errors-early-stop-amazonia-8.json @@ -0,0 +1,604 @@ +{ + "model": "dynamic-position-agent-v1", + "limitations": [ + "synthetic controller, not a child or usability study", + "approach decisions use simplified one-obstacle route targets", + "results do not establish comfort, fairness, or physical reachability" + ], + "parameters": { + "biome": "amazonia", + "collect_attempt_probability": 0.4, + "deliberate_decision_error_probability": 0.3, + "pause_seconds_per_active_minute": 0.0, + "interrupt_after_active_seconds": 20.0, + "session_limit_seconds": 0, + "reaction_seconds": 0.35, + "input_latency_seconds": 0.25, + "exploration": false, + "assistance": false, + "flight_count_per_mode": 8, + "seed_start": 1 + }, + "collection_costs": { + "papel": 656, + "plastico": 824, + "metal": 1224, + "vidro": 640 + }, + "mean_resources_by_mode": { + "normal": { + "papel": 2.5, + "plastico": 1.5, + "metal": 3.5, + "vidro": 0.0 + }, + "dificil": { + "papel": 6.0, + "plastico": 7.5, + "metal": 7.25, + "vidro": 6.125 + } + }, + "runs": [ + { + "biome": "amazonia", + "mode": "normal", + "seed": 1, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 7.36, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 4, + "vidro": 0 + }, + "resource_total": 8, + "collected": 2, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 1, + "sem_rota_simplificada": 0, + "nao_tentadas": 8, + "alvos_de_coleta": 3 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 2, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 4, + "plastico": 4, + "metal": 4, + "vidro": 0 + }, + "resource_total": 12, + "collected": 3, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 1, + "sem_rota_simplificada": 0, + "nao_tentadas": 7, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 3, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 8, + "vidro": 0 + }, + "resource_total": 12, + "collected": 3, + "hits": 0, + "max_lives": 3, + "lives_left": 3, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 0, + "sem_rota_simplificada": 0, + "nao_tentadas": 3, + "alvos_de_coleta": 3 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 4, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 100.0, + "stage_times_s": [], + "restoration": 5.0, + "resources": { + "papel": 0, + "plastico": 0, + "metal": 0, + "vidro": 0 + }, + "resource_total": 0, + "collected": 0, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 0, + "nao_tentadas": 8, + "alvos_de_coleta": 0 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 5, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.701, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 8, + "vidro": 0 + }, + "resource_total": 12, + "collected": 3, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 0, + "nao_tentadas": 6, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 6, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.774, + "stage_times_s": [], + "restoration": 6.18, + "resources": { + "papel": 0, + "plastico": 4, + "metal": 0, + "vidro": 0 + }, + "resource_total": 4, + "collected": 1, + "hits": 0, + "max_lives": 3, + "lives_left": 3, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 0, + "nao_tentadas": 6, + "alvos_de_coleta": 2 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 7, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.643, + "stage_times_s": [], + "restoration": 6.18, + "resources": { + "papel": 0, + "plastico": 0, + "metal": 4, + "vidro": 0 + }, + "resource_total": 4, + "collected": 1, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 0, + "nao_tentadas": 4, + "alvos_de_coleta": 3 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 8, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 7.36, + "resources": { + "papel": 4, + "plastico": 4, + "metal": 0, + "vidro": 0 + }, + "resource_total": 8, + "collected": 2, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 6, + "sem_rota_simplificada": 0, + "nao_tentadas": 5, + "alvos_de_coleta": 2 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 1, + "seconds_active": 7.283, + "seconds_wall": 7.283, + "max_player_displacement": 234.09, + "stage_times_s": [], + "restoration": 5.69, + "resources": { + "papel": 2, + "plastico": 2, + "metal": 1, + "vidro": 1 + }, + "resource_total": 6, + "collected": 6, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 5, + "sem_rota_simplificada": 1, + "nao_tentadas": 14, + "alvos_de_coleta": 7 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 2, + "seconds_active": 18.333, + "seconds_wall": 18.333, + "max_player_displacement": 231.991, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 8, + "plastico": 9, + "metal": 8, + "vidro": 5 + }, + "resource_total": 30, + "collected": 30, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 11, + "sem_rota_simplificada": 3, + "nao_tentadas": 40, + "alvos_de_coleta": 17 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 3, + "seconds_active": 13.4, + "seconds_wall": 13.4, + "max_player_displacement": 221.763, + "stage_times_s": [], + "restoration": 5.69, + "resources": { + "papel": 1, + "plastico": 2, + "metal": 3, + "vidro": 0 + }, + "resource_total": 6, + "collected": 6, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 8, + "sem_rota_simplificada": 1, + "nao_tentadas": 19, + "alvos_de_coleta": 5 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 4, + "seconds_active": 16.583, + "seconds_wall": 16.583, + "max_player_displacement": 221.774, + "stage_times_s": [], + "restoration": 10.13, + "resources": { + "papel": 8, + "plastico": 9, + "metal": 13, + "vidro": 14 + }, + "resource_total": 44, + "collected": 38, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 7, + "sem_rota_simplificada": 2, + "nao_tentadas": 19, + "alvos_de_coleta": 12 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 5, + "seconds_active": 17.767, + "seconds_wall": 17.767, + "max_player_displacement": 218.043, + "stage_times_s": [], + "restoration": 6.38, + "resources": { + "papel": 3, + "plastico": 3, + "metal": 5, + "vidro": 1 + }, + "resource_total": 12, + "collected": 12, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 10, + "sem_rota_simplificada": 1, + "nao_tentadas": 28, + "alvos_de_coleta": 9 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 6, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.652, + "stage_times_s": [], + "restoration": 10.99, + "resources": { + "papel": 11, + "plastico": 15, + "metal": 11, + "vidro": 16 + }, + "resource_total": 53, + "collected": 41, + "hits": 2, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 10, + "sem_rota_simplificada": 2, + "nao_tentadas": 23, + "alvos_de_coleta": 10 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 7, + "seconds_active": 13.683, + "seconds_wall": 13.683, + "max_player_displacement": 233.937, + "stage_times_s": [], + "restoration": 9.38, + "resources": { + "papel": 9, + "plastico": 10, + "metal": 12, + "vidro": 7 + }, + "resource_total": 38, + "collected": 32, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 7, + "sem_rota_simplificada": 2, + "nao_tentadas": 21, + "alvos_de_coleta": 11 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 8, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 234.091, + "stage_times_s": [], + "restoration": 9.8, + "resources": { + "papel": 6, + "plastico": 10, + "metal": 5, + "vidro": 5 + }, + "resource_total": 26, + "collected": 20, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 19, + "sem_rota_simplificada": 3, + "nao_tentadas": 40, + "alvos_de_coleta": 12 + }, + "exploration": false, + "assistance": false + } + ] +} \ No newline at end of file diff --git a/docs/validacao-v1.6/economia/errors-early-stop-caatinga-8.json b/docs/validacao-v1.6/economia/errors-early-stop-caatinga-8.json new file mode 100644 index 0000000..7b34acf --- /dev/null +++ b/docs/validacao-v1.6/economia/errors-early-stop-caatinga-8.json @@ -0,0 +1,604 @@ +{ + "model": "dynamic-position-agent-v1", + "limitations": [ + "synthetic controller, not a child or usability study", + "approach decisions use simplified one-obstacle route targets", + "results do not establish comfort, fairness, or physical reachability" + ], + "parameters": { + "biome": "caatinga", + "collect_attempt_probability": 0.4, + "deliberate_decision_error_probability": 0.3, + "pause_seconds_per_active_minute": 0.0, + "interrupt_after_active_seconds": 20.0, + "session_limit_seconds": 0, + "reaction_seconds": 0.35, + "input_latency_seconds": 0.25, + "exploration": false, + "assistance": false, + "flight_count_per_mode": 8, + "seed_start": 1 + }, + "collection_costs": { + "papel": 656, + "plastico": 824, + "metal": 1224, + "vidro": 640 + }, + "mean_resources_by_mode": { + "normal": { + "papel": 2.5, + "plastico": 1.5, + "metal": 3.5, + "vidro": 0.0 + }, + "dificil": { + "papel": 5.625, + "plastico": 7.25, + "metal": 7.0, + "vidro": 6.125 + } + }, + "runs": [ + { + "biome": "caatinga", + "mode": "normal", + "seed": 1, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 7.36, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 4, + "vidro": 0 + }, + "resource_total": 8, + "collected": 2, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 1, + "sem_rota_simplificada": 0, + "nao_tentadas": 8, + "alvos_de_coleta": 3 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 2, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 4, + "plastico": 4, + "metal": 4, + "vidro": 0 + }, + "resource_total": 12, + "collected": 3, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 1, + "sem_rota_simplificada": 0, + "nao_tentadas": 7, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 3, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 8, + "vidro": 0 + }, + "resource_total": 12, + "collected": 3, + "hits": 0, + "max_lives": 3, + "lives_left": 3, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 0, + "sem_rota_simplificada": 0, + "nao_tentadas": 3, + "alvos_de_coleta": 3 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 4, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 100.0, + "stage_times_s": [], + "restoration": 5.0, + "resources": { + "papel": 0, + "plastico": 0, + "metal": 0, + "vidro": 0 + }, + "resource_total": 0, + "collected": 0, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 0, + "nao_tentadas": 8, + "alvos_de_coleta": 0 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 5, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.701, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 8, + "vidro": 0 + }, + "resource_total": 12, + "collected": 3, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 0, + "nao_tentadas": 6, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 6, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.774, + "stage_times_s": [], + "restoration": 6.18, + "resources": { + "papel": 0, + "plastico": 4, + "metal": 0, + "vidro": 0 + }, + "resource_total": 4, + "collected": 1, + "hits": 0, + "max_lives": 3, + "lives_left": 3, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 0, + "nao_tentadas": 6, + "alvos_de_coleta": 2 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 7, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.643, + "stage_times_s": [], + "restoration": 6.18, + "resources": { + "papel": 0, + "plastico": 0, + "metal": 4, + "vidro": 0 + }, + "resource_total": 4, + "collected": 1, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 0, + "nao_tentadas": 4, + "alvos_de_coleta": 3 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 8, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 7.36, + "resources": { + "papel": 4, + "plastico": 4, + "metal": 0, + "vidro": 0 + }, + "resource_total": 8, + "collected": 2, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 6, + "sem_rota_simplificada": 0, + "nao_tentadas": 5, + "alvos_de_coleta": 2 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 1, + "seconds_active": 7.283, + "seconds_wall": 7.283, + "max_player_displacement": 234.09, + "stage_times_s": [], + "restoration": 5.69, + "resources": { + "papel": 2, + "plastico": 2, + "metal": 1, + "vidro": 1 + }, + "resource_total": 6, + "collected": 6, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 5, + "sem_rota_simplificada": 1, + "nao_tentadas": 14, + "alvos_de_coleta": 7 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 2, + "seconds_active": 13.867, + "seconds_wall": 13.867, + "max_player_displacement": 231.991, + "stage_times_s": [], + "restoration": 7.65, + "resources": { + "papel": 5, + "plastico": 7, + "metal": 6, + "vidro": 5 + }, + "resource_total": 23, + "collected": 23, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 8, + "sem_rota_simplificada": 3, + "nao_tentadas": 29, + "alvos_de_coleta": 11 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 3, + "seconds_active": 13.4, + "seconds_wall": 13.4, + "max_player_displacement": 221.763, + "stage_times_s": [], + "restoration": 5.69, + "resources": { + "papel": 1, + "plastico": 2, + "metal": 3, + "vidro": 0 + }, + "resource_total": 6, + "collected": 6, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 8, + "sem_rota_simplificada": 1, + "nao_tentadas": 19, + "alvos_de_coleta": 5 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 4, + "seconds_active": 16.583, + "seconds_wall": 16.583, + "max_player_displacement": 221.774, + "stage_times_s": [], + "restoration": 10.13, + "resources": { + "papel": 8, + "plastico": 9, + "metal": 13, + "vidro": 14 + }, + "resource_total": 44, + "collected": 38, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 7, + "sem_rota_simplificada": 2, + "nao_tentadas": 19, + "alvos_de_coleta": 12 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 5, + "seconds_active": 17.767, + "seconds_wall": 17.767, + "max_player_displacement": 218.043, + "stage_times_s": [], + "restoration": 6.38, + "resources": { + "papel": 3, + "plastico": 3, + "metal": 5, + "vidro": 1 + }, + "resource_total": 12, + "collected": 12, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 10, + "sem_rota_simplificada": 1, + "nao_tentadas": 28, + "alvos_de_coleta": 9 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 6, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 221.652, + "stage_times_s": [], + "restoration": 10.99, + "resources": { + "papel": 11, + "plastico": 15, + "metal": 11, + "vidro": 16 + }, + "resource_total": 53, + "collected": 41, + "hits": 2, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 10, + "sem_rota_simplificada": 2, + "nao_tentadas": 23, + "alvos_de_coleta": 10 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 7, + "seconds_active": 13.683, + "seconds_wall": 13.683, + "max_player_displacement": 233.937, + "stage_times_s": [], + "restoration": 9.38, + "resources": { + "papel": 9, + "plastico": 10, + "metal": 12, + "vidro": 7 + }, + "resource_total": 38, + "collected": 32, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 7, + "sem_rota_simplificada": 2, + "nao_tentadas": 21, + "alvos_de_coleta": 11 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 8, + "seconds_active": 20.0, + "seconds_wall": 20.0, + "max_player_displacement": 234.091, + "stage_times_s": [], + "restoration": 9.8, + "resources": { + "papel": 6, + "plastico": 10, + "metal": 5, + "vidro": 5 + }, + "resource_total": 26, + "collected": 20, + "hits": 1, + "max_lives": 3, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 19, + "sem_rota_simplificada": 3, + "nao_tentadas": 40, + "alvos_de_coleta": 12 + }, + "exploration": false, + "assistance": false + } + ] +} \ No newline at end of file diff --git a/docs/validacao-v1.6/economia/errors-interruption-amazonia-8.json b/docs/validacao-v1.6/economia/errors-interruption-amazonia-8.json new file mode 100644 index 0000000..11582ed --- /dev/null +++ b/docs/validacao-v1.6/economia/errors-interruption-amazonia-8.json @@ -0,0 +1,604 @@ +{ + "model": "dynamic-position-agent-v1", + "limitations": [ + "synthetic controller, not a child or usability study", + "approach decisions use simplified one-obstacle route targets", + "results do not establish comfort, fairness, or physical reachability" + ], + "parameters": { + "biome": "amazonia", + "collect_attempt_probability": 0.4, + "deliberate_decision_error_probability": 0.3, + "pause_seconds_per_active_minute": 10.0, + "interrupt_after_active_seconds": 120.0, + "session_limit_seconds": 0, + "reaction_seconds": 0.35, + "input_latency_seconds": 0.25, + "exploration": false, + "assistance": false, + "flight_count_per_mode": 8, + "seed_start": 1 + }, + "collection_costs": { + "papel": 656, + "plastico": 824, + "metal": 1224, + "vidro": 640 + }, + "mean_resources_by_mode": { + "normal": { + "papel": 5.0, + "plastico": 6.75, + "metal": 6.0, + "vidro": 3.75 + }, + "dificil": { + "papel": 6.375, + "plastico": 8.125, + "metal": 7.75, + "vidro": 6.25 + } + }, + "runs": [ + { + "biome": "amazonia", + "mode": "normal", + "seed": 1, + "seconds_active": 28.45, + "seconds_wall": 28.45, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 7.36, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 4, + "vidro": 0 + }, + "resource_total": 8, + "collected": 2, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 1, + "nao_tentadas": 10, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 2, + "seconds_active": 31.883, + "seconds_wall": 31.883, + "max_player_displacement": 233.36, + "stage_times_s": [], + "restoration": 9.72, + "resources": { + "papel": 4, + "plastico": 4, + "metal": 4, + "vidro": 4 + }, + "resource_total": 16, + "collected": 4, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 2, + "nao_tentadas": 8, + "alvos_de_coleta": 7 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 3, + "seconds_active": 39.467, + "seconds_wall": 39.467, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 8, + "vidro": 0 + }, + "resource_total": 12, + "collected": 3, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 3, + "sem_rota_simplificada": 1, + "nao_tentadas": 6, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 4, + "seconds_active": 26.25, + "seconds_wall": 26.25, + "max_player_displacement": 100.0, + "stage_times_s": [], + "restoration": 5.0, + "resources": { + "papel": 0, + "plastico": 0, + "metal": 0, + "vidro": 0 + }, + "resource_total": 0, + "collected": 0, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 6, + "sem_rota_simplificada": 2, + "nao_tentadas": 10, + "alvos_de_coleta": 0 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 5, + "seconds_active": 58.75, + "seconds_wall": 58.75, + "max_player_displacement": 226.519, + "stage_times_s": [], + "restoration": 15.62, + "resources": { + "papel": 8, + "plastico": 16, + "metal": 8, + "vidro": 4 + }, + "resource_total": 36, + "collected": 9, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 10, + "sem_rota_simplificada": 2, + "nao_tentadas": 18, + "alvos_de_coleta": 9 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 6, + "seconds_active": 73.483, + "seconds_wall": 83.483, + "max_player_displacement": 221.774, + "stage_times_s": [], + "restoration": 20.3, + "resources": { + "papel": 8, + "plastico": 20, + "metal": 16, + "vidro": 14 + }, + "resource_total": 58, + "collected": 10, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 12, + "sem_rota_simplificada": 2, + "nao_tentadas": 17, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 7, + "seconds_active": 30.783, + "seconds_wall": 30.783, + "max_player_displacement": 221.643, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 8, + "vidro": 0 + }, + "resource_total": 12, + "collected": 3, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 5, + "sem_rota_simplificada": 1, + "nao_tentadas": 9, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 8, + "seconds_active": 52.117, + "seconds_wall": 52.117, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 12.58, + "resources": { + "papel": 8, + "plastico": 14, + "metal": 0, + "vidro": 8 + }, + "resource_total": 30, + "collected": 6, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 11, + "sem_rota_simplificada": 3, + "nao_tentadas": 18, + "alvos_de_coleta": 5 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 1, + "seconds_active": 7.283, + "seconds_wall": 7.283, + "max_player_displacement": 234.09, + "stage_times_s": [], + "restoration": 5.69, + "resources": { + "papel": 2, + "plastico": 2, + "metal": 1, + "vidro": 1 + }, + "resource_total": 6, + "collected": 6, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 5, + "sem_rota_simplificada": 1, + "nao_tentadas": 14, + "alvos_de_coleta": 7 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 2, + "seconds_active": 18.333, + "seconds_wall": 18.333, + "max_player_displacement": 231.991, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 8, + "plastico": 9, + "metal": 8, + "vidro": 5 + }, + "resource_total": 30, + "collected": 30, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 11, + "sem_rota_simplificada": 3, + "nao_tentadas": 40, + "alvos_de_coleta": 17 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 3, + "seconds_active": 13.4, + "seconds_wall": 13.4, + "max_player_displacement": 221.763, + "stage_times_s": [], + "restoration": 5.69, + "resources": { + "papel": 1, + "plastico": 2, + "metal": 3, + "vidro": 0 + }, + "resource_total": 6, + "collected": 6, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 8, + "sem_rota_simplificada": 1, + "nao_tentadas": 19, + "alvos_de_coleta": 5 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 4, + "seconds_active": 16.583, + "seconds_wall": 16.583, + "max_player_displacement": 221.774, + "stage_times_s": [], + "restoration": 10.13, + "resources": { + "papel": 8, + "plastico": 9, + "metal": 13, + "vidro": 14 + }, + "resource_total": 44, + "collected": 38, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 7, + "sem_rota_simplificada": 2, + "nao_tentadas": 19, + "alvos_de_coleta": 12 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 5, + "seconds_active": 17.767, + "seconds_wall": 17.767, + "max_player_displacement": 218.043, + "stage_times_s": [], + "restoration": 6.38, + "resources": { + "papel": 3, + "plastico": 3, + "metal": 5, + "vidro": 1 + }, + "resource_total": 12, + "collected": 12, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 10, + "sem_rota_simplificada": 1, + "nao_tentadas": 28, + "alvos_de_coleta": 9 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 6, + "seconds_active": 23.817, + "seconds_wall": 23.817, + "max_player_displacement": 221.652, + "stage_times_s": [], + "restoration": 11.79, + "resources": { + "papel": 12, + "plastico": 17, + "metal": 14, + "vidro": 17 + }, + "resource_total": 60, + "collected": 48, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 12, + "sem_rota_simplificada": 3, + "nao_tentadas": 30, + "alvos_de_coleta": 16 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 7, + "seconds_active": 13.683, + "seconds_wall": 13.683, + "max_player_displacement": 233.937, + "stage_times_s": [], + "restoration": 9.38, + "resources": { + "papel": 9, + "plastico": 10, + "metal": 12, + "vidro": 7 + }, + "resource_total": 38, + "collected": 32, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 7, + "sem_rota_simplificada": 2, + "nao_tentadas": 21, + "alvos_de_coleta": 11 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 8, + "seconds_active": 28.167, + "seconds_wall": 28.167, + "max_player_displacement": 234.091, + "stage_times_s": [], + "restoration": 10.49, + "resources": { + "papel": 8, + "plastico": 13, + "metal": 6, + "vidro": 5 + }, + "resource_total": 32, + "collected": 26, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 25, + "sem_rota_simplificada": 5, + "nao_tentadas": 51, + "alvos_de_coleta": 16 + }, + "exploration": false, + "assistance": false + } + ] +} \ No newline at end of file diff --git a/docs/validacao-v1.6/economia/errors-interruption-caatinga-8.json b/docs/validacao-v1.6/economia/errors-interruption-caatinga-8.json new file mode 100644 index 0000000..d60792b --- /dev/null +++ b/docs/validacao-v1.6/economia/errors-interruption-caatinga-8.json @@ -0,0 +1,604 @@ +{ + "model": "dynamic-position-agent-v1", + "limitations": [ + "synthetic controller, not a child or usability study", + "approach decisions use simplified one-obstacle route targets", + "results do not establish comfort, fairness, or physical reachability" + ], + "parameters": { + "biome": "caatinga", + "collect_attempt_probability": 0.4, + "deliberate_decision_error_probability": 0.3, + "pause_seconds_per_active_minute": 10.0, + "interrupt_after_active_seconds": 120.0, + "session_limit_seconds": 0, + "reaction_seconds": 0.35, + "input_latency_seconds": 0.25, + "exploration": false, + "assistance": false, + "flight_count_per_mode": 8, + "seed_start": 1 + }, + "collection_costs": { + "papel": 656, + "plastico": 824, + "metal": 1224, + "vidro": 640 + }, + "mean_resources_by_mode": { + "normal": { + "papel": 5.5, + "plastico": 8.25, + "metal": 6.0, + "vidro": 3.75 + }, + "dificil": { + "papel": 6.0, + "plastico": 7.875, + "metal": 7.5, + "vidro": 6.25 + } + }, + "runs": [ + { + "biome": "caatinga", + "mode": "normal", + "seed": 1, + "seconds_active": 28.45, + "seconds_wall": 28.45, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 7.36, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 4, + "vidro": 0 + }, + "resource_total": 8, + "collected": 2, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 1, + "nao_tentadas": 10, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 2, + "seconds_active": 31.883, + "seconds_wall": 31.883, + "max_player_displacement": 233.36, + "stage_times_s": [], + "restoration": 9.72, + "resources": { + "papel": 4, + "plastico": 4, + "metal": 4, + "vidro": 4 + }, + "resource_total": 16, + "collected": 4, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 2, + "sem_rota_simplificada": 2, + "nao_tentadas": 8, + "alvos_de_coleta": 7 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 3, + "seconds_active": 41.683, + "seconds_wall": 41.683, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 10.9, + "resources": { + "papel": 8, + "plastico": 4, + "metal": 8, + "vidro": 0 + }, + "resource_total": 20, + "collected": 5, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 4, + "sem_rota_simplificada": 2, + "nao_tentadas": 8, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 4, + "seconds_active": 26.25, + "seconds_wall": 26.25, + "max_player_displacement": 100.0, + "stage_times_s": [], + "restoration": 5.0, + "resources": { + "papel": 0, + "plastico": 0, + "metal": 0, + "vidro": 0 + }, + "resource_total": 0, + "collected": 0, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 6, + "sem_rota_simplificada": 2, + "nao_tentadas": 10, + "alvos_de_coleta": 0 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 5, + "seconds_active": 58.75, + "seconds_wall": 58.75, + "max_player_displacement": 226.519, + "stage_times_s": [], + "restoration": 15.62, + "resources": { + "papel": 8, + "plastico": 16, + "metal": 8, + "vidro": 4 + }, + "resource_total": 36, + "collected": 9, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 10, + "sem_rota_simplificada": 2, + "nao_tentadas": 18, + "alvos_de_coleta": 9 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 6, + "seconds_active": 73.483, + "seconds_wall": 83.483, + "max_player_displacement": 221.774, + "stage_times_s": [], + "restoration": 20.3, + "resources": { + "papel": 8, + "plastico": 20, + "metal": 16, + "vidro": 14 + }, + "resource_total": 58, + "collected": 10, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 12, + "sem_rota_simplificada": 2, + "nao_tentadas": 17, + "alvos_de_coleta": 8 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 7, + "seconds_active": 30.783, + "seconds_wall": 30.783, + "max_player_displacement": 221.643, + "stage_times_s": [], + "restoration": 8.54, + "resources": { + "papel": 4, + "plastico": 0, + "metal": 8, + "vidro": 0 + }, + "resource_total": 12, + "collected": 3, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 5, + "sem_rota_simplificada": 1, + "nao_tentadas": 9, + "alvos_de_coleta": 4 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 8, + "seconds_active": 66.283, + "seconds_wall": 76.283, + "max_player_displacement": 221.775, + "stage_times_s": [], + "restoration": 14.94, + "resources": { + "papel": 8, + "plastico": 22, + "metal": 0, + "vidro": 8 + }, + "resource_total": 38, + "collected": 8, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 14, + "sem_rota_simplificada": 4, + "nao_tentadas": 21, + "alvos_de_coleta": 6 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 1, + "seconds_active": 7.283, + "seconds_wall": 7.283, + "max_player_displacement": 234.09, + "stage_times_s": [], + "restoration": 5.69, + "resources": { + "papel": 2, + "plastico": 2, + "metal": 1, + "vidro": 1 + }, + "resource_total": 6, + "collected": 6, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 5, + "sem_rota_simplificada": 1, + "nao_tentadas": 14, + "alvos_de_coleta": 7 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 2, + "seconds_active": 13.867, + "seconds_wall": 13.867, + "max_player_displacement": 231.991, + "stage_times_s": [], + "restoration": 7.65, + "resources": { + "papel": 5, + "plastico": 7, + "metal": 6, + "vidro": 5 + }, + "resource_total": 23, + "collected": 23, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 8, + "sem_rota_simplificada": 3, + "nao_tentadas": 29, + "alvos_de_coleta": 11 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 3, + "seconds_active": 13.4, + "seconds_wall": 13.4, + "max_player_displacement": 221.763, + "stage_times_s": [], + "restoration": 5.69, + "resources": { + "papel": 1, + "plastico": 2, + "metal": 3, + "vidro": 0 + }, + "resource_total": 6, + "collected": 6, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 8, + "sem_rota_simplificada": 1, + "nao_tentadas": 19, + "alvos_de_coleta": 5 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 4, + "seconds_active": 16.583, + "seconds_wall": 16.583, + "max_player_displacement": 221.774, + "stage_times_s": [], + "restoration": 10.13, + "resources": { + "papel": 8, + "plastico": 9, + "metal": 13, + "vidro": 14 + }, + "resource_total": 44, + "collected": 38, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 7, + "sem_rota_simplificada": 2, + "nao_tentadas": 19, + "alvos_de_coleta": 12 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 5, + "seconds_active": 17.767, + "seconds_wall": 17.767, + "max_player_displacement": 218.043, + "stage_times_s": [], + "restoration": 6.38, + "resources": { + "papel": 3, + "plastico": 3, + "metal": 5, + "vidro": 1 + }, + "resource_total": 12, + "collected": 12, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 10, + "sem_rota_simplificada": 1, + "nao_tentadas": 28, + "alvos_de_coleta": 9 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 6, + "seconds_active": 23.817, + "seconds_wall": 23.817, + "max_player_displacement": 221.652, + "stage_times_s": [], + "restoration": 11.79, + "resources": { + "papel": 12, + "plastico": 17, + "metal": 14, + "vidro": 17 + }, + "resource_total": 60, + "collected": 48, + "hits": 4, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 12, + "sem_rota_simplificada": 3, + "nao_tentadas": 30, + "alvos_de_coleta": 16 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 7, + "seconds_active": 13.683, + "seconds_wall": 13.683, + "max_player_displacement": 233.937, + "stage_times_s": [], + "restoration": 9.38, + "resources": { + "papel": 9, + "plastico": 10, + "metal": 12, + "vidro": 7 + }, + "resource_total": 38, + "collected": 32, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 7, + "sem_rota_simplificada": 2, + "nao_tentadas": 21, + "alvos_de_coleta": 11 + }, + "exploration": false, + "assistance": false + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 8, + "seconds_active": 28.167, + "seconds_wall": 28.167, + "max_player_displacement": 234.091, + "stage_times_s": [], + "restoration": 10.49, + "resources": { + "papel": 8, + "plastico": 13, + "metal": 6, + "vidro": 5 + }, + "resource_total": 32, + "collected": 26, + "hits": 3, + "max_lives": 3, + "lives_left": 0, + "completed": false, + "game_over": true, + "interrupted": false, + "session_timeout": false, + "pause_count": 0, + "pause_seconds": 0.0, + "controller_counts": { + "decisoes_perdidas": 25, + "sem_rota_simplificada": 5, + "nao_tentadas": 51, + "alvos_de_coleta": 16 + }, + "exploration": false, + "assistance": false + } + ] +} \ No newline at end of file diff --git a/docs/validacao-v1.6/economia/exploration-assistance-amazonia-8.json b/docs/validacao-v1.6/economia/exploration-assistance-amazonia-8.json new file mode 100644 index 0000000..96e9fde --- /dev/null +++ b/docs/validacao-v1.6/economia/exploration-assistance-amazonia-8.json @@ -0,0 +1,618 @@ +{ + "model": "dynamic-position-agent-v1", + "limitations": [ + "synthetic controller, not a child or usability study", + "approach decisions use simplified one-obstacle route targets", + "results do not establish comfort, fairness, or physical reachability" + ], + "parameters": { + "biome": "amazonia", + "collect_attempt_probability": 0.4, + "deliberate_decision_error_probability": 0.3, + "pause_seconds_per_active_minute": 10.0, + "interrupt_after_active_seconds": 0.0, + "session_limit_seconds": 120, + "reaction_seconds": 0.35, + "input_latency_seconds": 0.25, + "exploration": true, + "assistance": true, + "flight_count_per_mode": 8, + "seed_start": 1 + }, + "collection_costs": { + "papel": 656, + "plastico": 824, + "metal": 1224, + "vidro": 640 + }, + "mean_resources_by_mode": { + "normal": { + "papel": 25.25, + "plastico": 28.75, + "metal": 27.75, + "vidro": 21.25 + }, + "dificil": { + "papel": 54.375, + "plastico": 63.125, + "metal": 55.375, + "vidro": 64.125 + } + }, + "runs": [ + { + "biome": "amazonia", + "mode": "normal", + "seed": 1, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.094, + "stage_times_s": [ + 125.033 + ], + "restoration": 36.14, + "resources": { + "papel": 34, + "plastico": 24, + "metal": 36, + "vidro": 22 + }, + "resource_total": 116, + "collected": 23, + "hits": 9, + "max_lives": 5, + "lives_left": 1, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 31, + "sem_rota_simplificada": 5, + "nao_tentadas": 39, + "alvos_de_coleta": 18 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 2, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.094, + "stage_times_s": [], + "restoration": 31.28, + "resources": { + "papel": 22, + "plastico": 24, + "metal": 40, + "vidro": 16 + }, + "resource_total": 102, + "collected": 21, + "hits": 11, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 23, + "sem_rota_simplificada": 7, + "nao_tentadas": 37, + "alvos_de_coleta": 20 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 3, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.02, + "stage_times_s": [ + 105.617 + ], + "restoration": 39.54, + "resources": { + "papel": 38, + "plastico": 28, + "metal": 40, + "vidro": 24 + }, + "resource_total": 130, + "collected": 28, + "hits": 16, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 32, + "sem_rota_simplificada": 5, + "nao_tentadas": 27, + "alvos_de_coleta": 18 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 4, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 233.22, + "stage_times_s": [], + "restoration": 27.38, + "resources": { + "papel": 24, + "plastico": 26, + "metal": 14, + "vidro": 18 + }, + "resource_total": 82, + "collected": 16, + "hits": 13, + "max_lives": 5, + "lives_left": 3, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 37, + "sem_rota_simplificada": 10, + "nao_tentadas": 36, + "alvos_de_coleta": 15 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 5, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.093, + "stage_times_s": [ + 129.817 + ], + "restoration": 34.32, + "resources": { + "papel": 20, + "plastico": 32, + "metal": 34, + "vidro": 22 + }, + "resource_total": 108, + "collected": 24, + "hits": 13, + "max_lives": 5, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 36, + "sem_rota_simplificada": 7, + "nao_tentadas": 40, + "alvos_de_coleta": 18 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 6, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.092, + "stage_times_s": [ + 125.133 + ], + "restoration": 35.46, + "resources": { + "papel": 32, + "plastico": 34, + "metal": 24, + "vidro": 28 + }, + "resource_total": 118, + "collected": 22, + "hits": 11, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 31, + "sem_rota_simplificada": 5, + "nao_tentadas": 28, + "alvos_de_coleta": 20 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 7, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.094, + "stage_times_s": [], + "restoration": 24.88, + "resources": { + "papel": 20, + "plastico": 22, + "metal": 26, + "vidro": 8 + }, + "resource_total": 76, + "collected": 16, + "hits": 16, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 40, + "sem_rota_simplificada": 10, + "nao_tentadas": 42, + "alvos_de_coleta": 17 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "normal", + "seed": 8, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.092, + "stage_times_s": [], + "restoration": 27.06, + "resources": { + "papel": 12, + "plastico": 40, + "metal": 8, + "vidro": 32 + }, + "resource_total": 92, + "collected": 17, + "hits": 9, + "max_lives": 5, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 33, + "sem_rota_simplificada": 6, + "nao_tentadas": 36, + "alvos_de_coleta": 16 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 1, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.09, + "stage_times_s": [ + 111.633 + ], + "restoration": 38.84, + "resources": { + "papel": 77, + "plastico": 75, + "metal": 70, + "vidro": 78 + }, + "resource_total": 300, + "collected": 252, + "hits": 25, + "max_lives": 5, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 99, + "sem_rota_simplificada": 18, + "nao_tentadas": 199, + "alvos_de_coleta": 99 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 2, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.089, + "stage_times_s": [], + "restoration": 31.9, + "resources": { + "papel": 64, + "plastico": 58, + "metal": 60, + "vidro": 54 + }, + "resource_total": 236, + "collected": 200, + "hits": 16, + "max_lives": 5, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 68, + "sem_rota_simplificada": 17, + "nao_tentadas": 166, + "alvos_de_coleta": 80 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 3, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.083, + "stage_times_s": [ + 112.967 + ], + "restoration": 36.75, + "resources": { + "papel": 59, + "plastico": 76, + "metal": 56, + "vidro": 75 + }, + "resource_total": 266, + "collected": 218, + "hits": 21, + "max_lives": 5, + "lives_left": 1, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 102, + "sem_rota_simplificada": 16, + "nao_tentadas": 179, + "alvos_de_coleta": 93 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 4, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 233.976, + "stage_times_s": [], + "restoration": 32.26, + "resources": { + "papel": 59, + "plastico": 63, + "metal": 62, + "vidro": 59 + }, + "resource_total": 243, + "collected": 207, + "hits": 22, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 91, + "sem_rota_simplificada": 26, + "nao_tentadas": 214, + "alvos_de_coleta": 83 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 5, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 225.839, + "stage_times_s": [], + "restoration": 30.02, + "resources": { + "papel": 38, + "plastico": 55, + "metal": 44, + "vidro": 65 + }, + "resource_total": 202, + "collected": 178, + "hits": 15, + "max_lives": 5, + "lives_left": 4, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 93, + "sem_rota_simplificada": 16, + "nao_tentadas": 201, + "alvos_de_coleta": 92 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 6, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 233.659, + "stage_times_s": [ + 128.617 + ], + "restoration": 34.38, + "resources": { + "papel": 44, + "plastico": 57, + "metal": 59, + "vidro": 65 + }, + "resource_total": 225, + "collected": 189, + "hits": 15, + "max_lives": 5, + "lives_left": 3, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 102, + "sem_rota_simplificada": 27, + "nao_tentadas": 241, + "alvos_de_coleta": 91 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 7, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 233.937, + "stage_times_s": [], + "restoration": 31.44, + "resources": { + "papel": 48, + "plastico": 52, + "metal": 58, + "vidro": 63 + }, + "resource_total": 221, + "collected": 179, + "hits": 18, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 106, + "sem_rota_simplificada": 23, + "nao_tentadas": 210, + "alvos_de_coleta": 105 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "amazonia", + "mode": "dificil", + "seed": 8, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.091, + "stage_times_s": [], + "restoration": 29.57, + "resources": { + "papel": 46, + "plastico": 69, + "metal": 34, + "vidro": 54 + }, + "resource_total": 203, + "collected": 167, + "hits": 20, + "max_lives": 5, + "lives_left": 1, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 121, + "sem_rota_simplificada": 21, + "nao_tentadas": 179, + "alvos_de_coleta": 81 + }, + "exploration": true, + "assistance": true + } + ] +} \ No newline at end of file diff --git a/docs/validacao-v1.6/economia/exploration-assistance-caatinga-8.json b/docs/validacao-v1.6/economia/exploration-assistance-caatinga-8.json new file mode 100644 index 0000000..db5a4e6 --- /dev/null +++ b/docs/validacao-v1.6/economia/exploration-assistance-caatinga-8.json @@ -0,0 +1,618 @@ +{ + "model": "dynamic-position-agent-v1", + "limitations": [ + "synthetic controller, not a child or usability study", + "approach decisions use simplified one-obstacle route targets", + "results do not establish comfort, fairness, or physical reachability" + ], + "parameters": { + "biome": "caatinga", + "collect_attempt_probability": 0.4, + "deliberate_decision_error_probability": 0.3, + "pause_seconds_per_active_minute": 10.0, + "interrupt_after_active_seconds": 0.0, + "session_limit_seconds": 120, + "reaction_seconds": 0.35, + "input_latency_seconds": 0.25, + "exploration": true, + "assistance": true, + "flight_count_per_mode": 8, + "seed_start": 1 + }, + "collection_costs": { + "papel": 656, + "plastico": 824, + "metal": 1224, + "vidro": 640 + }, + "mean_resources_by_mode": { + "normal": { + "papel": 24.0, + "plastico": 26.0, + "metal": 28.75, + "vidro": 21.25 + }, + "dificil": { + "papel": 53.25, + "plastico": 60.5, + "metal": 54.0, + "vidro": 60.625 + } + }, + "runs": [ + { + "biome": "caatinga", + "mode": "normal", + "seed": 1, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.094, + "stage_times_s": [ + 125.033 + ], + "restoration": 34.96, + "resources": { + "papel": 34, + "plastico": 20, + "metal": 36, + "vidro": 22 + }, + "resource_total": 112, + "collected": 22, + "hits": 9, + "max_lives": 5, + "lives_left": 1, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 31, + "sem_rota_simplificada": 6, + "nao_tentadas": 39, + "alvos_de_coleta": 16 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 2, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.094, + "stage_times_s": [], + "restoration": 31.28, + "resources": { + "papel": 22, + "plastico": 24, + "metal": 40, + "vidro": 16 + }, + "resource_total": 102, + "collected": 21, + "hits": 11, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 23, + "sem_rota_simplificada": 7, + "nao_tentadas": 37, + "alvos_de_coleta": 20 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 3, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.02, + "stage_times_s": [ + 105.617 + ], + "restoration": 39.04, + "resources": { + "papel": 32, + "plastico": 28, + "metal": 40, + "vidro": 24 + }, + "resource_total": 124, + "collected": 28, + "hits": 15, + "max_lives": 5, + "lives_left": 1, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 32, + "sem_rota_simplificada": 5, + "nao_tentadas": 27, + "alvos_de_coleta": 18 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 4, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.089, + "stage_times_s": [], + "restoration": 22.52, + "resources": { + "papel": 20, + "plastico": 18, + "metal": 18, + "vidro": 12 + }, + "resource_total": 68, + "collected": 14, + "hits": 9, + "max_lives": 5, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 34, + "sem_rota_simplificada": 7, + "nao_tentadas": 38, + "alvos_de_coleta": 12 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 5, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.093, + "stage_times_s": [ + 129.817 + ], + "restoration": 34.32, + "resources": { + "papel": 20, + "plastico": 32, + "metal": 34, + "vidro": 22 + }, + "resource_total": 108, + "collected": 24, + "hits": 13, + "max_lives": 5, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 36, + "sem_rota_simplificada": 7, + "nao_tentadas": 40, + "alvos_de_coleta": 18 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 6, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.092, + "stage_times_s": [ + 125.133 + ], + "restoration": 35.46, + "resources": { + "papel": 32, + "plastico": 34, + "metal": 24, + "vidro": 28 + }, + "resource_total": 118, + "collected": 22, + "hits": 11, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 31, + "sem_rota_simplificada": 5, + "nao_tentadas": 28, + "alvos_de_coleta": 20 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 7, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.061, + "stage_times_s": [], + "restoration": 26.06, + "resources": { + "papel": 20, + "plastico": 12, + "metal": 30, + "vidro": 18 + }, + "resource_total": 80, + "collected": 17, + "hits": 16, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 37, + "sem_rota_simplificada": 10, + "nao_tentadas": 37, + "alvos_de_coleta": 20 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "normal", + "seed": 8, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.092, + "stage_times_s": [], + "restoration": 25.88, + "resources": { + "papel": 12, + "plastico": 40, + "metal": 8, + "vidro": 28 + }, + "resource_total": 88, + "collected": 16, + "hits": 9, + "max_lives": 5, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 33, + "sem_rota_simplificada": 6, + "nao_tentadas": 36, + "alvos_de_coleta": 16 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 1, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.09, + "stage_times_s": [], + "restoration": 32.03, + "resources": { + "papel": 56, + "plastico": 64, + "metal": 62, + "vidro": 58 + }, + "resource_total": 240, + "collected": 210, + "hits": 25, + "max_lives": 5, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 96, + "sem_rota_simplificada": 19, + "nao_tentadas": 199, + "alvos_de_coleta": 90 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 2, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 231.991, + "stage_times_s": [ + 119.667 + ], + "restoration": 35.75, + "resources": { + "papel": 73, + "plastico": 59, + "metal": 64, + "vidro": 60 + }, + "resource_total": 256, + "collected": 214, + "hits": 17, + "max_lives": 5, + "lives_left": 4, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 81, + "sem_rota_simplificada": 15, + "nao_tentadas": 193, + "alvos_de_coleta": 96 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 3, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 233.908, + "stage_times_s": [ + 129.967 + ], + "restoration": 33.34, + "resources": { + "papel": 61, + "plastico": 71, + "metal": 55, + "vidro": 61 + }, + "resource_total": 248, + "collected": 218, + "hits": 20, + "max_lives": 5, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 105, + "sem_rota_simplificada": 16, + "nao_tentadas": 180, + "alvos_de_coleta": 94 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 4, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 233.411, + "stage_times_s": [], + "restoration": 32.42, + "resources": { + "papel": 56, + "plastico": 57, + "metal": 55, + "vidro": 56 + }, + "resource_total": 224, + "collected": 194, + "hits": 21, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 90, + "sem_rota_simplificada": 19, + "nao_tentadas": 208, + "alvos_de_coleta": 81 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 5, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 225.839, + "stage_times_s": [], + "restoration": 30.02, + "resources": { + "papel": 39, + "plastico": 53, + "metal": 45, + "vidro": 65 + }, + "resource_total": 202, + "collected": 178, + "hits": 15, + "max_lives": 5, + "lives_left": 4, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 93, + "sem_rota_simplificada": 16, + "nao_tentadas": 201, + "alvos_de_coleta": 92 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 6, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.061, + "stage_times_s": [ + 128.333 + ], + "restoration": 34.5, + "resources": { + "papel": 44, + "plastico": 57, + "metal": 60, + "vidro": 65 + }, + "resource_total": 226, + "collected": 190, + "hits": 15, + "max_lives": 5, + "lives_left": 3, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 102, + "sem_rota_simplificada": 27, + "nao_tentadas": 241, + "alvos_de_coleta": 91 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 7, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.09, + "stage_times_s": [], + "restoration": 30.13, + "resources": { + "papel": 50, + "plastico": 54, + "metal": 57, + "vidro": 66 + }, + "resource_total": 227, + "collected": 185, + "hits": 19, + "max_lives": 5, + "lives_left": 5, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 106, + "sem_rota_simplificada": 23, + "nao_tentadas": 210, + "alvos_de_coleta": 105 + }, + "exploration": true, + "assistance": true + }, + { + "biome": "caatinga", + "mode": "dificil", + "seed": 8, + "seconds_active": 120.0, + "seconds_wall": 130.0, + "max_player_displacement": 234.091, + "stage_times_s": [], + "restoration": 29.68, + "resources": { + "papel": 47, + "plastico": 69, + "metal": 34, + "vidro": 54 + }, + "resource_total": 204, + "collected": 168, + "hits": 19, + "max_lives": 5, + "lives_left": 2, + "completed": false, + "game_over": false, + "interrupted": true, + "session_timeout": true, + "pause_count": 1, + "pause_seconds": 10.0, + "controller_counts": { + "decisoes_perdidas": 121, + "sem_rota_simplificada": 21, + "nao_tentadas": 179, + "alvos_de_coleta": 81 + }, + "exploration": true, + "assistance": true + } + ] +} \ No newline at end of file diff --git a/docs/validacao-v1.6/economia/sintese.md b/docs/validacao-v1.6/economia/sintese.md new file mode 100644 index 0000000..66ff35f --- /dev/null +++ b/docs/validacao-v1.6/economia/sintese.md @@ -0,0 +1,68 @@ +# Economia P1/P2 — reavaliação após expiração de metas e custos iniciais + +**Modelo:** `dynamic-position-agent-v1`; cada execução usa 8 sementes por bioma e modo. Os JSONs foram regenerados após a expiração de missão não cumprida aos 60 s ativos e usam a implementação atual. O agente controla posição com a física real de `Player`, uma decisão simplificada de rota, erros deliberados e colisões reais. Não representa crianças nem constitui teste de usabilidade. + +**Limites:** os resultados descrevem só esse modelo. As metas expiram sem recompensa/punição e aguardam 2,5 s para nova oferta; isso evita objetivo preso, mas não mede se 60 s é o ritmo ideal para crianças. Não alterei preços posteriores. + +## Cenários e resultados + +| Cenário / bioma | Modo | Ativo / parede médios | Conclusões | Game over | Limite/interrupção | Batidas médias | Recursos/voo (papel, plástico, metal, vidro) | +|---|---|---:|---:|---:|---:|---:|---| +| Padrão · Manaus | Normal | 51 / 51 s | 0/8 | 8/8 | 0/8 | 3.1 | 5.5 · 9.2 · 9.5 · 6.8 | +| Padrão · Manaus | Dificil | 25 / 25 s | 0/8 | 8/8 | 0/8 | 3.4 | 6.5 · 7.4 · 8.0 · 8.6 | +| Padrão · Petrolina | Normal | 50 / 50 s | 0/8 | 8/8 | 0/8 | 3.1 | 6.5 · 9.2 · 10.0 · 5.5 | +| Padrão · Petrolina | Dificil | 25 / 25 s | 0/8 | 8/8 | 0/8 | 3.4 | 6.5 · 7.4 · 8.0 · 8.6 | +| Erro + encerramento aos 20 s · Manaus | Normal | 20 / 20 s | 0/8 | 0/8 | 8/8 | 0.8 | 2.5 · 1.5 · 3.5 · 0.0 | +| Erro + encerramento aos 20 s · Manaus | Dificil | 16 / 16 s | 0/8 | 6/8 | 2/8 | 2.6 | 6.0 · 7.5 · 7.2 · 6.1 | +| Erro + encerramento aos 20 s · Petrolina | Normal | 20 / 20 s | 0/8 | 0/8 | 8/8 | 0.8 | 2.5 · 1.5 · 3.5 · 0.0 | +| Erro + encerramento aos 20 s · Petrolina | Dificil | 15 / 15 s | 0/8 | 6/8 | 2/8 | 2.6 | 5.6 · 7.2 · 7.0 · 6.1 | +| Explorar + assistência + limite 120 s · Manaus | Normal | 120 / 130 s | 0/8 | 0/8 | 8/8 | 12.2 | 25.2 · 28.8 · 27.8 · 21.2 | +| Explorar + assistência + limite 120 s · Manaus | Dificil | 120 / 130 s | 0/8 | 0/8 | 8/8 | 19.0 | 54.4 · 63.1 · 55.4 · 64.1 | +| Explorar + assistência + limite 120 s · Petrolina | Normal | 120 / 130 s | 0/8 | 0/8 | 8/8 | 11.6 | 24.0 · 26.0 · 28.8 · 21.2 | +| Explorar + assistência + limite 120 s · Petrolina | Dificil | 120 / 130 s | 0/8 | 0/8 | 8/8 | 18.9 | 53.2 · 60.5 · 54.0 · 60.6 | +| Erro + pausa + limite de 120 s · Manaus | Normal | 43 / 44 s | 0/8 | 8/8 | 0/8 | 3.1 | 5.0 · 6.8 · 6.0 · 3.8 | +| Erro + pausa + limite de 120 s · Manaus | Dificil | 17 / 17 s | 0/8 | 8/8 | 0/8 | 3.1 | 6.4 · 8.1 · 7.8 · 6.2 | +| Erro + pausa + limite de 120 s · Petrolina | Normal | 45 / 47 s | 0/8 | 8/8 | 0/8 | 3.1 | 5.5 · 8.2 · 6.0 · 3.8 | +| Erro + pausa + limite de 120 s · Petrolina | Dificil | 17 / 17 s | 0/8 | 8/8 | 0/8 | 3.1 | 6.0 · 7.9 · 7.5 · 6.2 | + +## Primeiras compras + +Custos: **Ponto de troca = 8 papel + 8 plástico**; **Horta = 24 papel + 16 vidro**. Para cada cenário, bioma e modo, usei os oito registros guardados em ordem de semente (1 a 8) como **uma única trajetória sintética de oito voos**. Somei os recursos mantidos pelo perfil, comprei o Ponto assim que possível e depois a Horta assim que possível. Prêmios de missão entram no saldo, como no jogo; `collected` permanece uma contagem separada de coletas físicas. + +| Cenário / bioma | Modo | Voo do Ponto | Voo da Horta após o Ponto | +|---|---|---:|---:| +| Padrão · Manaus | Normal | 1 | 6 | +| Padrão · Manaus | Difícil | 2 | 7 | +| Padrão · Petrolina | Normal | 1 | 6 | +| Padrão · Petrolina | Difícil | 2 | 7 | +| Erro + encerramento aos 20 s · Manaus | Normal | 6 | >8 | +| Erro + encerramento aos 20 s · Manaus | Difícil | 2 | 6 | +| Erro + encerramento aos 20 s · Petrolina | Normal | 6 | >8 | +| Erro + encerramento aos 20 s · Petrolina | Difícil | 3 | 7 | +| Explorar + assistência + limite 120 s · Manaus | Normal | 1 | 1 | +| Explorar + assistência + limite 120 s · Manaus | Difícil | 1 | 1 | +| Explorar + assistência + limite 120 s · Petrolina | Normal | 1 | 1 | +| Explorar + assistência + limite 120 s · Petrolina | Difícil | 1 | 1 | +| Erro + pausa + limite de 120 s · Manaus | Normal | 5 | 7 | +| Erro + pausa + limite de 120 s · Manaus | Difícil | 2 | 6 | +| Erro + pausa + limite de 120 s · Petrolina | Normal | 3 | 6 | +| Erro + pausa + limite de 120 s · Petrolina | Difícil | 3 | 7 | + +Cada linha é somente uma trajetória construída com oito sementes; não é oito trajetórias independentes, frequência de sucesso ou chance para jogadores. O voo indicado é o primeiro em que o saldo acumulado permite a compra nessa trajetória. Os resultados descrevem o agente sintético, não preveem a progressão de uma criança. Os preços de entrada seguem a decisão de produto: 2 coletas de cada material no Normal para o Ponto; os custos posteriores foram preservados. + +## Rotas comunitárias + +A auditoria delimitada das quatro sementes oficiais em Manaus e Petrolina, normal e difícil, com introdução ligada/desligada, obteve **32/32 casos aprovados** após 25 s simulados por mundo: rota inicial validada independentemente, frontier não vazia e zero falhas de tutorial. Isso valida o contrato do planner nesses casos, não alcance físico individual. Detalhes em `audit-community-routes.json`. + +## Artefatos + +- `baseline-amazonia-8.json` +- `baseline-caatinga-8.json` +- `errors-early-stop-amazonia-8.json` +- `errors-early-stop-caatinga-8.json` +- `exploration-assistance-amazonia-8.json` +- `exploration-assistance-caatinga-8.json` +- `errors-interruption-amazonia-8.json` +- `errors-interruption-caatinga-8.json` +- `audit-community-routes.json` +- `sintese.md` (este relatório) diff --git a/docs/validacao-v1.6/proveniencia.json b/docs/validacao-v1.6/proveniencia.json new file mode 100644 index 0000000..166ed4d --- /dev/null +++ b/docs/validacao-v1.6/proveniencia.json @@ -0,0 +1,14 @@ +{ + "date": "2026-10-25", + "baseline_commit": "f80294b45508f4ba87cf22eeb3cc6e6e23ee56fc", + "runtime_game_tree": "447b012de46ec0b5110946d3bd64d9106a32e1f0", + "runtime_assets_tree": "d61e7e9ef7a9ab7cc58a9334cbec54bd4a6c2156", + "tree_reference_commit": "d47035cd9d1acb75ac01a81bb25bd87a7c1e71d4", + "benchmark_script_sha256": "57cfc9732bfe32d3e7d12746889bc35e2e7728848f262f9a9506d4dc4cc23bc7", + "notes": [ + "baseline extracted from Git into a separate folder; same local Python executable", + "empty-pilot comparison uses seed 7; avatar runs add customized synthetic appearance", + "camera reports contain metrics, no images or landmarks", + "soak uses synthetic invincible flight solely for render lifecycle stress" + ] +} diff --git a/docs/validacao-v1.6/runtime-avatar-camera-runtime.json b/docs/validacao-v1.6/runtime-avatar-camera-runtime.json new file mode 100644 index 0000000..bc081b9 --- /dev/null +++ b/docs/validacao-v1.6/runtime-avatar-camera-runtime.json @@ -0,0 +1,485 @@ +{ + "conditions": "CPU; SDL dummy; local camera inference running concurrently; 1100x650; fresh process; 60 warmup frames per case", + "pacing": "60 fps target, sleep excluded from frame timings", + "python": "3.12.10", + "platform": "Windows-11-10.0.26200-SP0", + "camera_clock_resolution_ms": 15.625, + "startup_ms": 929.65, + "rss_before_bytes": 40804352, + "rss_after_bytes": 132333568, + "rss_delta_bytes": 91529216, + "startup_watercolor_count": 0, + "startup_watercolor_bytes": 0, + "seed": 7, + "pilot": "customized synthetic avatar", + "flights": { + "amazonia_normal": { + "frame": { + "median_ms": 10.27, + "p95_ms": 18.05, + "p99_ms": 24.168, + "max_ms": 41.875 + }, + "scene_setup_ms": 15.373, + "warmup": { + "median_ms": 8.553, + "p95_ms": 13.939, + "p99_ms": 451.216, + "max_ms": 451.216 + }, + "first_frame_ms": 451.216, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.9267, + "components": { + "horizon": { + "median_ms": 0.007, + "p95_ms": 2.377, + "p99_ms": 3.317, + "max_ms": 4.747 + }, + "ground": { + "median_ms": 5.165, + "p95_ms": 8.805, + "p99_ms": 13.253, + "max_ms": 23.879 + }, + "background": { + "median_ms": 7.754, + "p95_ms": 14.188, + "p99_ms": 17.855, + "max_ms": 27.706 + }, + "world": { + "median_ms": 8.818, + "p95_ms": 15.826, + "p99_ms": 19.97, + "max_ms": 29.576 + }, + "present": { + "median_ms": 0.358, + "p95_ms": 0.711, + "p99_ms": 0.934, + "max_ms": 2.738 + } + }, + "rss_bytes": 456552448, + "renderer_caches": { + "unique_retained_surface_bytes": 174074604, + "surface_bytes_by_owner": { + "assets": 23554348, + "scene_sprites": 0, + "world_sprite_cache": 587260, + "world_transient": 1085032, + "sky": 4818952, + "ground": 917504, + "watercolor": 106342268, + "plane_skin": 27015716, + "paper_items": 9753524 + }, + "cache_items": { + "scaled": 2, + "mips": 1, + "outlines": 0, + "rotations": 7, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 47.0, + "p95_ms": 78.0, + "p99_ms": 94.0, + "max_ms": 125.0 + }, + "camera": { + "frames_read": 355, + "inferences": 354, + "published": 354, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6343.999999997322, + "capture_fps": 29.659954883455544, + "inference_fps": 29.576405714769756, + "capture_interval_ms": 16.00000000325963, + "inference_interval_ms": 16.00000000325963, + "inference_ms": 16.00000000325963, + "result_age_ms": 16.00000000325963, + "last_result_age_ms": 16.00000000325963, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + }, + "amazonia_contrast": { + "frame": { + "median_ms": 12.611, + "p95_ms": 17.541, + "p99_ms": 20.857, + "max_ms": 22.05 + }, + "scene_setup_ms": 6.878, + "warmup": { + "median_ms": 11.105, + "p95_ms": 15.472, + "p99_ms": 22.728, + "max_ms": 22.728 + }, + "first_frame_ms": 22.728, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.9283, + "components": { + "horizon": { + "median_ms": 0.006, + "p95_ms": 1.517, + "p99_ms": 2.326, + "max_ms": 3.257 + }, + "ground": { + "median_ms": 4.628, + "p95_ms": 6.777, + "p99_ms": 8.312, + "max_ms": 10.644 + }, + "desaturate": { + "median_ms": 2.009, + "p95_ms": 3.22, + "p99_ms": 3.872, + "max_ms": 4.356 + }, + "background": { + "median_ms": 9.073, + "p95_ms": 12.851, + "p99_ms": 14.883, + "max_ms": 16.889 + }, + "world": { + "median_ms": 11.293, + "p95_ms": 16.11, + "p99_ms": 19.343, + "max_ms": 21.13 + }, + "present": { + "median_ms": 0.319, + "p95_ms": 0.693, + "p99_ms": 0.876, + "max_ms": 1.168 + } + }, + "rss_bytes": 470155264, + "renderer_caches": { + "unique_retained_surface_bytes": 179692936, + "surface_bytes_by_owner": { + "assets": 23554348, + "scene_sprites": 0, + "world_sprite_cache": 1245368, + "world_transient": 5368672, + "sky": 4818952, + "ground": 917504, + "watercolor": 106342268, + "plane_skin": 27015716, + "paper_items": 10430108 + }, + "cache_items": { + "scaled": 3, + "mips": 2, + "outlines": 1, + "rotations": 14, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 32.0, + "p95_ms": 63.0, + "p99_ms": 78.0, + "max_ms": 93.0 + }, + "camera": { + "frames_read": 695, + "inferences": 694, + "published": 694, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6343.999999997322, + "capture_fps": 29.811693046804773, + "inference_fps": 29.76879852443527, + "capture_interval_ms": 47.00000000593718, + "inference_interval_ms": 47.00000000593718, + "inference_ms": 16.00000000325963, + "result_age_ms": 62.999999994644895, + "last_result_age_ms": 16.00000000325963, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + }, + "caatinga_normal": { + "frame": { + "median_ms": 7.209, + "p95_ms": 38.394, + "p99_ms": 53.51, + "max_ms": 67.459 + }, + "scene_setup_ms": 7.804, + "warmup": { + "median_ms": 5.809, + "p95_ms": 11.298, + "p99_ms": 243.288, + "max_ms": 243.288 + }, + "first_frame_ms": 243.288, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.8517, + "components": { + "horizon": { + "median_ms": 0.008, + "p95_ms": 1.868, + "p99_ms": 2.56, + "max_ms": 3.439 + }, + "ground": { + "median_ms": 2.251, + "p95_ms": 12.064, + "p99_ms": 17.803, + "max_ms": 24.43 + }, + "background": { + "median_ms": 4.811, + "p95_ms": 23.855, + "p99_ms": 35.102, + "max_ms": 55.214 + }, + "world": { + "median_ms": 5.814, + "p95_ms": 31.131, + "p99_ms": 45.495, + "max_ms": 61.468 + }, + "present": { + "median_ms": 0.379, + "p95_ms": 1.301, + "p99_ms": 2.063, + "max_ms": 2.969 + } + }, + "rss_bytes": 466087936, + "renderer_caches": { + "unique_retained_surface_bytes": 181043368, + "surface_bytes_by_owner": { + "assets": 23483180, + "scene_sprites": 0, + "world_sprite_cache": 587260, + "world_transient": 4301432, + "sky": 4818952, + "ground": 917504, + "watercolor": 109932252, + "plane_skin": 27015716, + "paper_items": 9987072 + }, + "cache_items": { + "scaled": 2, + "mips": 1, + "outlines": 0, + "rotations": 7, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 47.0, + "p95_ms": 204.0, + "p99_ms": 265.0, + "max_ms": 375.0 + }, + "camera": { + "frames_read": 1021, + "inferences": 1020, + "published": 1020, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6343.999999997322, + "capture_fps": 27.90074875662881, + "inference_fps": 27.873421872440144, + "capture_interval_ms": 46.999999991385266, + "inference_interval_ms": 46.999999991385266, + "inference_ms": 30.999999988125637, + "result_age_ms": 46.999999991385266, + "last_result_age_ms": 30.999999988125637, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + }, + "caatinga_contrast": { + "frame": { + "median_ms": 10.95, + "p95_ms": 16.098, + "p99_ms": 19.972, + "max_ms": 21.147 + }, + "scene_setup_ms": 7.597, + "warmup": { + "median_ms": 8.955, + "p95_ms": 12.857, + "p99_ms": 21.211, + "max_ms": 21.211 + }, + "first_frame_ms": 21.211, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.965, + "components": { + "horizon": { + "median_ms": 0.007, + "p95_ms": 1.692, + "p99_ms": 2.39, + "max_ms": 3.38 + }, + "ground": { + "median_ms": 2.164, + "p95_ms": 3.673, + "p99_ms": 4.556, + "max_ms": 5.846 + }, + "desaturate": { + "median_ms": 2.178, + "p95_ms": 3.643, + "p99_ms": 4.468, + "max_ms": 5.999 + }, + "background": { + "median_ms": 6.958, + "p95_ms": 10.934, + "p99_ms": 12.84, + "max_ms": 15.593 + }, + "world": { + "median_ms": 9.497, + "p95_ms": 14.404, + "p99_ms": 16.987, + "max_ms": 19.281 + }, + "present": { + "median_ms": 0.34, + "p95_ms": 0.721, + "p99_ms": 0.96, + "max_ms": 1.776 + } + }, + "rss_bytes": 469987328, + "renderer_caches": { + "unique_retained_surface_bytes": 183366244, + "surface_bytes_by_owner": { + "assets": 23483180, + "scene_sprites": 0, + "world_sprite_cache": 1245368, + "world_transient": 5368672, + "sky": 4818952, + "ground": 917504, + "watercolor": 109932252, + "plane_skin": 27015716, + "paper_items": 10584600 + }, + "cache_items": { + "scaled": 3, + "mips": 2, + "outlines": 1, + "rotations": 14, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 46.0, + "p95_ms": 78.0, + "p99_ms": 94.0, + "max_ms": 94.0 + }, + "camera": { + "frames_read": 1360, + "inferences": 1359, + "published": 1359, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6343.999999997322, + "capture_fps": 28.397820049694253, + "inference_fps": 28.376939299657714, + "capture_interval_ms": 47.00000000593718, + "inference_interval_ms": 16.00000000325963, + "inference_ms": 16.00000000325963, + "result_age_ms": 47.00000000593718, + "last_result_age_ms": 16.00000000325963, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + } + }, + "camera_start": { + "frames_read": 3, + "inferences": 2, + "published": 2, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6343.999999997322, + "capture_fps": 38.46153846446607, + "inference_fps": 25.64102564297738, + "capture_interval_ms": 30.999999988125637, + "inference_interval_ms": 30.999999988125637, + "inference_ms": 15.999999988707714, + "result_age_ms": 30.999999988125637, + "last_result_age_ms": 30.999999988125637, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + }, + "camera_ready": true, + "latency_basis": "read-return to present-call completion; excludes sensor buffering and physical display latency", + "camera_thread_stopped": true, + "camera_end": { + "frames_read": 1360, + "inferences": 1360, + "published": 1360, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6343.999999997322, + "capture_fps": 28.04991234402359, + "inference_fps": 28.04991234402359, + "capture_interval_ms": 47.00000000593718, + "inference_interval_ms": 47.00000000593718, + "inference_ms": 14.999999999417923, + "result_age_ms": 593.9999999973224, + "last_result_age_ms": 14.999999999417923, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": true + }, + "status": "ok" +} \ No newline at end of file diff --git a/docs/validacao-v1.6/runtime-avatar-runtime.json b/docs/validacao-v1.6/runtime-avatar-runtime.json new file mode 100644 index 0000000..503870c --- /dev/null +++ b/docs/validacao-v1.6/runtime-avatar-runtime.json @@ -0,0 +1,326 @@ +{ + "conditions": "CPU; SDL dummy; no camera; 1100x650; fresh process; 60 warmup frames per case", + "pacing": "uncapped stress", + "python": "3.12.10", + "platform": "Windows-11-10.0.26200-SP0", + "camera_clock_resolution_ms": 15.625, + "startup_ms": 1035.83, + "rss_before_bytes": 40759296, + "rss_after_bytes": 133038080, + "rss_delta_bytes": 92278784, + "startup_watercolor_count": 0, + "startup_watercolor_bytes": 0, + "seed": 7, + "pilot": "customized synthetic avatar", + "flights": { + "amazonia_normal": { + "frame": { + "median_ms": 7.936, + "p95_ms": 11.966, + "p99_ms": 14.17, + "max_ms": 18.544 + }, + "scene_setup_ms": 7.378, + "warmup": { + "median_ms": 8.05, + "p95_ms": 13.819, + "p99_ms": 399.529, + "max_ms": 399.529 + }, + "first_frame_ms": 399.529, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.9983, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 1.64, + "p99_ms": 2.244, + "max_ms": 2.373 + }, + "ground": { + "median_ms": 4.062, + "p95_ms": 5.767, + "p99_ms": 6.904, + "max_ms": 8.092 + }, + "background": { + "median_ms": 5.912, + "p95_ms": 9.394, + "p99_ms": 11.334, + "max_ms": 14.531 + }, + "world": { + "median_ms": 6.79, + "p95_ms": 10.531, + "p99_ms": 12.712, + "max_ms": 16.486 + }, + "present": { + "median_ms": 0.286, + "p95_ms": 0.622, + "p99_ms": 0.763, + "max_ms": 0.917 + } + }, + "rss_bytes": 256925696, + "renderer_caches": { + "unique_retained_surface_bytes": 174074604, + "surface_bytes_by_owner": { + "assets": 23554348, + "scene_sprites": 0, + "world_sprite_cache": 587260, + "world_transient": 1085032, + "sky": 4818952, + "ground": 917504, + "watercolor": 106342268, + "plane_skin": 27015716, + "paper_items": 9753524 + }, + "cache_items": { + "scaled": 2, + "mips": 1, + "outlines": 0, + "rotations": 7, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + } + }, + "amazonia_contrast": { + "frame": { + "median_ms": 11.944, + "p95_ms": 19.169, + "p99_ms": 25.004, + "max_ms": 40.274 + }, + "scene_setup_ms": 7.42, + "warmup": { + "median_ms": 11.044, + "p95_ms": 20.074, + "p99_ms": 21.656, + "max_ms": 21.656 + }, + "first_frame_ms": 21.656, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.9083, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 1.224, + "p99_ms": 1.924, + "max_ms": 2.195 + }, + "ground": { + "median_ms": 4.309, + "p95_ms": 7.551, + "p99_ms": 10.378, + "max_ms": 16.294 + }, + "desaturate": { + "median_ms": 1.919, + "p95_ms": 3.515, + "p99_ms": 4.303, + "max_ms": 6.506 + }, + "background": { + "median_ms": 8.509, + "p95_ms": 14.135, + "p99_ms": 18.214, + "max_ms": 25.147 + }, + "world": { + "median_ms": 10.782, + "p95_ms": 17.549, + "p99_ms": 22.951, + "max_ms": 38.21 + }, + "present": { + "median_ms": 0.31, + "p95_ms": 0.64, + "p99_ms": 0.967, + "max_ms": 2.155 + } + }, + "rss_bytes": 270548992, + "renderer_caches": { + "unique_retained_surface_bytes": 179692936, + "surface_bytes_by_owner": { + "assets": 23554348, + "scene_sprites": 0, + "world_sprite_cache": 1245368, + "world_transient": 5368672, + "sky": 4818952, + "ground": 917504, + "watercolor": 106342268, + "plane_skin": 27015716, + "paper_items": 10430108 + }, + "cache_items": { + "scaled": 3, + "mips": 2, + "outlines": 1, + "rotations": 14, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + } + }, + "caatinga_normal": { + "frame": { + "median_ms": 6.65, + "p95_ms": 10.351, + "p99_ms": 13.283, + "max_ms": 14.958 + }, + "scene_setup_ms": 10.029, + "warmup": { + "median_ms": 4.755, + "p95_ms": 10.915, + "p99_ms": 202.946, + "max_ms": 202.946 + }, + "first_frame_ms": 202.946, + "frames_measured": 600, + "within_60fps_budget_fraction": 1.0, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 1.631, + "p99_ms": 2.305, + "max_ms": 3.345 + }, + "ground": { + "median_ms": 1.99, + "p95_ms": 3.393, + "p99_ms": 4.451, + "max_ms": 5.471 + }, + "background": { + "median_ms": 4.33, + "p95_ms": 7.321, + "p99_ms": 9.542, + "max_ms": 11.852 + }, + "world": { + "median_ms": 5.28, + "p95_ms": 8.583, + "p99_ms": 11.573, + "max_ms": 13.516 + }, + "present": { + "median_ms": 0.314, + "p95_ms": 0.64, + "p99_ms": 0.873, + "max_ms": 1.26 + } + }, + "rss_bytes": 264790016, + "renderer_caches": { + "unique_retained_surface_bytes": 181043368, + "surface_bytes_by_owner": { + "assets": 23483180, + "scene_sprites": 0, + "world_sprite_cache": 587260, + "world_transient": 4301432, + "sky": 4818952, + "ground": 917504, + "watercolor": 109932252, + "plane_skin": 27015716, + "paper_items": 9987072 + }, + "cache_items": { + "scaled": 2, + "mips": 1, + "outlines": 0, + "rotations": 7, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + } + }, + "caatinga_contrast": { + "frame": { + "median_ms": 9.371, + "p95_ms": 13.491, + "p99_ms": 15.672, + "max_ms": 18.831 + }, + "scene_setup_ms": 18.764, + "warmup": { + "median_ms": 8.623, + "p95_ms": 11.439, + "p99_ms": 35.198, + "max_ms": 35.198 + }, + "first_frame_ms": 35.198, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.995, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 1.376, + "p99_ms": 2.042, + "max_ms": 2.911 + }, + "ground": { + "median_ms": 1.881, + "p95_ms": 2.963, + "p99_ms": 3.503, + "max_ms": 5.225 + }, + "desaturate": { + "median_ms": 1.899, + "p95_ms": 3.04, + "p99_ms": 3.54, + "max_ms": 4.052 + }, + "background": { + "median_ms": 6.081, + "p95_ms": 8.797, + "p99_ms": 10.69, + "max_ms": 13.066 + }, + "world": { + "median_ms": 8.219, + "p95_ms": 11.925, + "p99_ms": 13.804, + "max_ms": 16.853 + }, + "present": { + "median_ms": 0.294, + "p95_ms": 0.632, + "p99_ms": 0.813, + "max_ms": 0.969 + } + }, + "rss_bytes": 269250560, + "renderer_caches": { + "unique_retained_surface_bytes": 183366244, + "surface_bytes_by_owner": { + "assets": 23483180, + "scene_sprites": 0, + "world_sprite_cache": 1245368, + "world_transient": 5368672, + "sky": 4818952, + "ground": 917504, + "watercolor": 109932252, + "plane_skin": 27015716, + "paper_items": 10584600 + }, + "cache_items": { + "scaled": 3, + "mips": 2, + "outlines": 1, + "rotations": 14, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + } + } + }, + "status": "ok" +} \ No newline at end of file diff --git a/docs/validacao-v1.6/runtime-camera-paced-runtime.json b/docs/validacao-v1.6/runtime-camera-paced-runtime.json new file mode 100644 index 0000000..77ac835 --- /dev/null +++ b/docs/validacao-v1.6/runtime-camera-paced-runtime.json @@ -0,0 +1,484 @@ +{ + "conditions": "CPU; SDL dummy; local camera inference running concurrently; 1100x650; fresh process; 60 warmup frames per case", + "pacing": "60 fps target, sleep excluded from frame timings", + "python": "3.12.10", + "platform": "Windows-11-10.0.26200-SP0", + "camera_clock_resolution_ms": 15.625, + "startup_ms": 1086.58, + "rss_before_bytes": 40767488, + "rss_after_bytes": 132984832, + "rss_delta_bytes": 92217344, + "startup_watercolor_count": 0, + "startup_watercolor_bytes": 0, + "seed": 7, + "flights": { + "amazonia_normal": { + "frame": { + "median_ms": 10.186, + "p95_ms": 15.225, + "p99_ms": 18.481, + "max_ms": 19.803 + }, + "scene_setup_ms": 20.464, + "warmup": { + "median_ms": 9.35, + "p95_ms": 13.692, + "p99_ms": 498.188, + "max_ms": 498.188 + }, + "first_frame_ms": 498.188, + "frames_measured": 480, + "within_60fps_budget_fraction": 0.9771, + "components": { + "horizon": { + "median_ms": 0.007, + "p95_ms": 1.586, + "p99_ms": 2.403, + "max_ms": 3.466 + }, + "ground": { + "median_ms": 5.043, + "p95_ms": 7.865, + "p99_ms": 9.267, + "max_ms": 11.223 + }, + "background": { + "median_ms": 7.69, + "p95_ms": 11.493, + "p99_ms": 13.926, + "max_ms": 16.654 + }, + "world": { + "median_ms": 8.767, + "p95_ms": 12.856, + "p99_ms": 15.201, + "max_ms": 18.179 + }, + "present": { + "median_ms": 0.348, + "p95_ms": 0.665, + "p99_ms": 0.954, + "max_ms": 1.185 + } + }, + "rss_bytes": 452001792, + "renderer_caches": { + "unique_retained_surface_bytes": 166917172, + "surface_bytes_by_owner": { + "assets": 23554348, + "scene_sprites": 0, + "world_sprite_cache": 587260, + "world_transient": 1085032, + "sky": 4818952, + "ground": 917504, + "watercolor": 106001780, + "plane_skin": 23417156, + "paper_items": 6535140 + }, + "cache_items": { + "scaled": 2, + "mips": 1, + "outlines": 0, + "rotations": 7, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 47.0, + "p95_ms": 63.0, + "p99_ms": 78.0, + "max_ms": 94.0 + }, + "camera": { + "frames_read": 291, + "inferences": 291, + "published": 291, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 7485.000000000582, + "capture_fps": 29.751559145273525, + "inference_fps": 29.797255785367895, + "capture_interval_ms": 31.999999991967343, + "inference_interval_ms": 31.999999991967343, + "inference_ms": 14.999999999417923, + "result_age_ms": 31.000000002677552, + "last_result_age_ms": 14.999999999417923, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + }, + "amazonia_contrast": { + "frame": { + "median_ms": 12.662, + "p95_ms": 17.486, + "p99_ms": 21.285, + "max_ms": 23.393 + }, + "scene_setup_ms": 7.359, + "warmup": { + "median_ms": 11.917, + "p95_ms": 15.172, + "p99_ms": 25.886, + "max_ms": 25.886 + }, + "first_frame_ms": 25.886, + "frames_measured": 480, + "within_60fps_budget_fraction": 0.9104, + "components": { + "horizon": { + "median_ms": 0.006, + "p95_ms": 1.76, + "p99_ms": 2.818, + "max_ms": 3.078 + }, + "ground": { + "median_ms": 4.659, + "p95_ms": 6.682, + "p99_ms": 8.521, + "max_ms": 9.797 + }, + "desaturate": { + "median_ms": 2.032, + "p95_ms": 3.196, + "p99_ms": 3.926, + "max_ms": 4.657 + }, + "background": { + "median_ms": 9.077, + "p95_ms": 13.243, + "p99_ms": 15.532, + "max_ms": 17.549 + }, + "world": { + "median_ms": 11.32, + "p95_ms": 15.787, + "p99_ms": 19.399, + "max_ms": 20.969 + }, + "present": { + "median_ms": 0.336, + "p95_ms": 0.686, + "p99_ms": 0.844, + "max_ms": 1.048 + } + }, + "rss_bytes": 466911232, + "renderer_caches": { + "unique_retained_surface_bytes": 171808152, + "surface_bytes_by_owner": { + "assets": 23554348, + "scene_sprites": 0, + "world_sprite_cache": 1245368, + "world_transient": 5368672, + "sky": 4818952, + "ground": 917504, + "watercolor": 106001780, + "plane_skin": 23417156, + "paper_items": 6484372 + }, + "cache_items": { + "scaled": 3, + "mips": 2, + "outlines": 1, + "rotations": 14, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 46.0, + "p95_ms": 63.0, + "p99_ms": 79.0, + "max_ms": 94.0 + }, + "camera": { + "frames_read": 570, + "inferences": 569, + "published": 569, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 7485.000000000582, + "capture_fps": 29.90242367012065, + "inference_fps": 29.873470887794543, + "capture_interval_ms": 32.00000000651926, + "inference_interval_ms": 32.00000000651926, + "inference_ms": 32.00000000651926, + "result_age_ms": 47.00000000593718, + "last_result_age_ms": 32.00000000651926, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + }, + "caatinga_normal": { + "frame": { + "median_ms": 6.831, + "p95_ms": 35.256, + "p99_ms": 45.734, + "max_ms": 55.321 + }, + "scene_setup_ms": 11.742, + "warmup": { + "median_ms": 5.757, + "p95_ms": 15.717, + "p99_ms": 324.486, + "max_ms": 324.486 + }, + "first_frame_ms": 324.486, + "frames_measured": 480, + "within_60fps_budget_fraction": 0.85, + "components": { + "horizon": { + "median_ms": 0.008, + "p95_ms": 1.588, + "p99_ms": 2.649, + "max_ms": 3.993 + }, + "ground": { + "median_ms": 2.174, + "p95_ms": 12.11, + "p99_ms": 16.207, + "max_ms": 19.157 + }, + "background": { + "median_ms": 4.629, + "p95_ms": 22.417, + "p99_ms": 30.816, + "max_ms": 33.983 + }, + "world": { + "median_ms": 5.581, + "p95_ms": 28.002, + "p99_ms": 36.689, + "max_ms": 43.0 + }, + "present": { + "median_ms": 0.342, + "p95_ms": 1.273, + "p99_ms": 1.82, + "max_ms": 2.893 + } + }, + "rss_bytes": 462098432, + "renderer_caches": { + "unique_retained_surface_bytes": 174134752, + "surface_bytes_by_owner": { + "assets": 23483180, + "scene_sprites": 0, + "world_sprite_cache": 587260, + "world_transient": 4141272, + "sky": 4818952, + "ground": 917504, + "watercolor": 110144276, + "plane_skin": 23417156, + "paper_items": 6625152 + }, + "cache_items": { + "scaled": 2, + "mips": 1, + "outlines": 0, + "rotations": 6, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 47.0, + "p95_ms": 203.0, + "p99_ms": 250.0, + "max_ms": 266.0 + }, + "camera": { + "frames_read": 838, + "inferences": 837, + "published": 837, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 7485.000000000582, + "capture_fps": 28.123636607706583, + "inference_fps": 28.104224027930186, + "capture_interval_ms": 31.000000002677552, + "inference_interval_ms": 31.000000002677552, + "inference_ms": 14.999999999417923, + "result_age_ms": 47.00000000593718, + "last_result_age_ms": 31.000000002677552, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + }, + "caatinga_contrast": { + "frame": { + "median_ms": 9.752, + "p95_ms": 13.865, + "p99_ms": 16.024, + "max_ms": 17.953 + }, + "scene_setup_ms": 8.656, + "warmup": { + "median_ms": 8.43, + "p95_ms": 11.155, + "p99_ms": 25.039, + "max_ms": 25.039 + }, + "first_frame_ms": 25.039, + "frames_measured": 480, + "within_60fps_budget_fraction": 0.9958, + "components": { + "horizon": { + "median_ms": 0.007, + "p95_ms": 1.494, + "p99_ms": 2.296, + "max_ms": 3.114 + }, + "ground": { + "median_ms": 2.005, + "p95_ms": 3.021, + "p99_ms": 3.524, + "max_ms": 4.13 + }, + "desaturate": { + "median_ms": 1.977, + "p95_ms": 3.125, + "p99_ms": 3.658, + "max_ms": 3.801 + }, + "background": { + "median_ms": 6.197, + "p95_ms": 9.214, + "p99_ms": 10.503, + "max_ms": 13.233 + }, + "world": { + "median_ms": 8.482, + "p95_ms": 12.053, + "p99_ms": 14.044, + "max_ms": 16.548 + }, + "present": { + "median_ms": 0.309, + "p95_ms": 0.658, + "p99_ms": 0.837, + "max_ms": 0.926 + } + }, + "rss_bytes": 468078592, + "renderer_caches": { + "unique_retained_surface_bytes": 175701112, + "surface_bytes_by_owner": { + "assets": 23483180, + "scene_sprites": 0, + "world_sprite_cache": 1245368, + "world_transient": 5042112, + "sky": 4818952, + "ground": 917504, + "watercolor": 110144276, + "plane_skin": 23417156, + "paper_items": 6632564 + }, + "cache_items": { + "scaled": 3, + "mips": 2, + "outlines": 1, + "rotations": 12, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 32.0, + "p95_ms": 63.0, + "p99_ms": 78.0, + "max_ms": 94.0 + }, + "camera": { + "frames_read": 1115, + "inferences": 1114, + "published": 1114, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 7485.000000000582, + "capture_fps": 28.57875176214319, + "inference_fps": 28.564102564102566, + "capture_interval_ms": 15.999999988707714, + "inference_interval_ms": 15.999999988707714, + "inference_ms": 15.999999988707714, + "result_age_ms": 30.999999988125637, + "last_result_age_ms": 15.999999988707714, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + } + }, + "camera_start": { + "frames_read": 2, + "inferences": 1, + "published": 1, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 7485.000000000582, + "capture_fps": 32.258064513342816, + "inference_fps": 21.276595741993127, + "capture_interval_ms": 62.000000005355105, + "inference_interval_ms": 47.00000000593718, + "inference_ms": 47.00000000593718, + "result_age_ms": 62.000000005355105, + "last_result_age_ms": 62.000000005355105, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + }, + "camera_ready": true, + "latency_basis": "read-return to present-call completion; excludes sensor buffering and physical display latency", + "camera_thread_stopped": true, + "camera_end": { + "frames_read": 1115, + "inferences": 1115, + "published": 1115, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 7485.000000000582, + "capture_fps": 28.172216888164062, + "inference_fps": 28.182898162417935, + "capture_interval_ms": 15.999999988707714, + "inference_interval_ms": 15.999999988707714, + "inference_ms": 14.999999999417923, + "result_age_ms": 578.0000000086147, + "last_result_age_ms": 31.000000002677552, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": true + }, + "status": "ok" +} \ No newline at end of file diff --git a/docs/validacao-v1.6/runtime-camera-recheck-runtime.json b/docs/validacao-v1.6/runtime-camera-recheck-runtime.json new file mode 100644 index 0000000..44fbc4a --- /dev/null +++ b/docs/validacao-v1.6/runtime-camera-recheck-runtime.json @@ -0,0 +1,484 @@ +{ + "conditions": "CPU; SDL dummy; local camera inference running concurrently; 1100x650; fresh process; 60 warmup frames per case", + "pacing": "60 fps target, sleep excluded from frame timings", + "python": "3.12.10", + "platform": "Windows-11-10.0.26200-SP0", + "camera_clock_resolution_ms": 15.625, + "startup_ms": 1022.14, + "rss_before_bytes": 40841216, + "rss_after_bytes": 132374528, + "rss_delta_bytes": 91533312, + "startup_watercolor_count": 0, + "startup_watercolor_bytes": 0, + "seed": 7, + "flights": { + "amazonia_normal": { + "frame": { + "median_ms": 9.493, + "p95_ms": 13.874, + "p99_ms": 16.668, + "max_ms": 18.322 + }, + "scene_setup_ms": 11.61, + "warmup": { + "median_ms": 11.515, + "p95_ms": 14.964, + "p99_ms": 441.51, + "max_ms": 441.51 + }, + "first_frame_ms": 441.51, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.99, + "components": { + "horizon": { + "median_ms": 0.007, + "p95_ms": 1.981, + "p99_ms": 3.027, + "max_ms": 4.694 + }, + "ground": { + "median_ms": 4.79, + "p95_ms": 7.061, + "p99_ms": 8.176, + "max_ms": 9.711 + }, + "background": { + "median_ms": 7.027, + "p95_ms": 10.979, + "p99_ms": 13.701, + "max_ms": 15.302 + }, + "world": { + "median_ms": 8.087, + "p95_ms": 12.202, + "p99_ms": 15.367, + "max_ms": 16.7 + }, + "present": { + "median_ms": 0.327, + "p95_ms": 0.704, + "p99_ms": 0.859, + "max_ms": 1.383 + } + }, + "rss_bytes": 453017600, + "renderer_caches": { + "unique_retained_surface_bytes": 170476044, + "surface_bytes_by_owner": { + "assets": 23554348, + "scene_sprites": 0, + "world_sprite_cache": 587260, + "world_transient": 1085032, + "sky": 4818952, + "ground": 917504, + "watercolor": 106342268, + "plane_skin": 23417156, + "paper_items": 9753524 + }, + "cache_items": { + "scaled": 2, + "mips": 1, + "outlines": 0, + "rotations": 7, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 46.0, + "p95_ms": 63.0, + "p99_ms": 78.0, + "max_ms": 94.0 + }, + "camera": { + "frames_read": 353, + "inferences": 353, + "published": 353, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6671.999999991385, + "capture_fps": 30.04255319148936, + "inference_fps": 30.04255319148936, + "capture_interval_ms": 14.999999999417923, + "inference_interval_ms": 14.999999999417923, + "inference_ms": 16.00000000325963, + "result_age_ms": 31.999999991967343, + "last_result_age_ms": 16.00000000325963, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + }, + "amazonia_contrast": { + "frame": { + "median_ms": 12.753, + "p95_ms": 17.17, + "p99_ms": 19.289, + "max_ms": 29.231 + }, + "scene_setup_ms": 6.179, + "warmup": { + "median_ms": 11.17, + "p95_ms": 14.64, + "p99_ms": 26.646, + "max_ms": 26.646 + }, + "first_frame_ms": 26.646, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.9317, + "components": { + "horizon": { + "median_ms": 0.006, + "p95_ms": 1.407, + "p99_ms": 2.204, + "max_ms": 3.514 + }, + "ground": { + "median_ms": 4.62, + "p95_ms": 6.551, + "p99_ms": 7.649, + "max_ms": 12.45 + }, + "desaturate": { + "median_ms": 2.045, + "p95_ms": 3.333, + "p99_ms": 3.621, + "max_ms": 5.006 + }, + "background": { + "median_ms": 9.093, + "p95_ms": 12.482, + "p99_ms": 14.312, + "max_ms": 23.551 + }, + "world": { + "median_ms": 11.487, + "p95_ms": 15.435, + "p99_ms": 17.588, + "max_ms": 27.531 + }, + "present": { + "median_ms": 0.317, + "p95_ms": 0.71, + "p99_ms": 0.856, + "max_ms": 1.265 + } + }, + "rss_bytes": 467390464, + "renderer_caches": { + "unique_retained_surface_bytes": 176094376, + "surface_bytes_by_owner": { + "assets": 23554348, + "scene_sprites": 0, + "world_sprite_cache": 1245368, + "world_transient": 5368672, + "sky": 4818952, + "ground": 917504, + "watercolor": 106342268, + "plane_skin": 23417156, + "paper_items": 10430108 + }, + "cache_items": { + "scaled": 3, + "mips": 2, + "outlines": 1, + "rotations": 14, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 32.0, + "p95_ms": 63.0, + "p99_ms": 78.0, + "max_ms": 94.0 + }, + "camera": { + "frames_read": 691, + "inferences": 691, + "published": 691, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6671.999999991385, + "capture_fps": 29.96270921862109, + "inference_fps": 29.96270921862109, + "capture_interval_ms": 30.999999988125637, + "inference_interval_ms": 30.999999988125637, + "inference_ms": 16.00000000325963, + "result_age_ms": 47.00000000593718, + "last_result_age_ms": 16.00000000325963, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + }, + "caatinga_normal": { + "frame": { + "median_ms": 6.513, + "p95_ms": 9.885, + "p99_ms": 12.406, + "max_ms": 18.071 + }, + "scene_setup_ms": 7.402, + "warmup": { + "median_ms": 6.397, + "p95_ms": 9.898, + "p99_ms": 217.609, + "max_ms": 217.609 + }, + "first_frame_ms": 217.609, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.9983, + "components": { + "horizon": { + "median_ms": 0.007, + "p95_ms": 1.851, + "p99_ms": 2.701, + "max_ms": 3.389 + }, + "ground": { + "median_ms": 2.018, + "p95_ms": 3.16, + "p99_ms": 4.003, + "max_ms": 5.079 + }, + "background": { + "median_ms": 4.286, + "p95_ms": 7.226, + "p99_ms": 8.706, + "max_ms": 11.543 + }, + "world": { + "median_ms": 5.242, + "p95_ms": 8.418, + "p99_ms": 10.548, + "max_ms": 14.68 + }, + "present": { + "median_ms": 0.308, + "p95_ms": 0.647, + "p99_ms": 0.796, + "max_ms": 1.405 + } + }, + "rss_bytes": 461033472, + "renderer_caches": { + "unique_retained_surface_bytes": 177444808, + "surface_bytes_by_owner": { + "assets": 23483180, + "scene_sprites": 0, + "world_sprite_cache": 587260, + "world_transient": 4301432, + "sky": 4818952, + "ground": 917504, + "watercolor": 109932252, + "plane_skin": 23417156, + "paper_items": 9987072 + }, + "cache_items": { + "scaled": 2, + "mips": 1, + "outlines": 0, + "rotations": 7, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 32.0, + "p95_ms": 78.0, + "p99_ms": 94.0, + "max_ms": 109.0 + }, + "camera": { + "frames_read": 1036, + "inferences": 1035, + "published": 1035, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6671.999999991385, + "capture_fps": 30.00202716399524, + "inference_fps": 29.973067678315708, + "capture_interval_ms": 30.999999988125637, + "inference_interval_ms": 30.999999988125637, + "inference_ms": 15.999999988707714, + "result_age_ms": 46.999999991385266, + "last_result_age_ms": 30.999999988125637, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + }, + "caatinga_contrast": { + "frame": { + "median_ms": 10.348, + "p95_ms": 14.915, + "p99_ms": 21.749, + "max_ms": 26.329 + }, + "scene_setup_ms": 7.953, + "warmup": { + "median_ms": 8.653, + "p95_ms": 13.134, + "p99_ms": 22.71, + "max_ms": 22.71 + }, + "first_frame_ms": 22.71, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.9683, + "components": { + "horizon": { + "median_ms": 0.007, + "p95_ms": 1.652, + "p99_ms": 2.422, + "max_ms": 2.856 + }, + "ground": { + "median_ms": 2.069, + "p95_ms": 3.316, + "p99_ms": 5.877, + "max_ms": 7.647 + }, + "desaturate": { + "median_ms": 2.045, + "p95_ms": 3.551, + "p99_ms": 4.884, + "max_ms": 6.222 + }, + "background": { + "median_ms": 6.527, + "p95_ms": 10.534, + "p99_ms": 14.786, + "max_ms": 17.42 + }, + "world": { + "median_ms": 8.961, + "p95_ms": 13.313, + "p99_ms": 19.491, + "max_ms": 23.999 + }, + "present": { + "median_ms": 0.326, + "p95_ms": 0.668, + "p99_ms": 0.827, + "max_ms": 3.712 + } + }, + "rss_bytes": 469929984, + "renderer_caches": { + "unique_retained_surface_bytes": 179767684, + "surface_bytes_by_owner": { + "assets": 23483180, + "scene_sprites": 0, + "world_sprite_cache": 1245368, + "world_transient": 5368672, + "sky": 4818952, + "ground": 917504, + "watercolor": 109932252, + "plane_skin": 23417156, + "paper_items": 10584600 + }, + "cache_items": { + "scaled": 3, + "mips": 2, + "outlines": 1, + "rotations": 14, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "latest_camera_result_age_at_present": { + "median_ms": 46.0, + "p95_ms": 78.0, + "p99_ms": 94.0, + "max_ms": 109.0 + }, + "camera": { + "frames_read": 1373, + "inferences": 1372, + "published": 1372, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6671.999999991385, + "capture_fps": 29.939597461777666, + "inference_fps": 29.917791491302953, + "capture_interval_ms": 46.000000002095476, + "inference_interval_ms": 46.000000002095476, + "inference_ms": 46.000000002095476, + "result_age_ms": 62.000000005355105, + "last_result_age_ms": 46.000000002095476, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + } + } + }, + "camera_start": { + "frames_read": 2, + "inferences": 1, + "published": 1, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6671.999999991385, + "capture_fps": 32.258064513342816, + "inference_fps": 16.129032256671408, + "capture_interval_ms": 31.000000002677552, + "inference_interval_ms": 31.000000002677552, + "inference_ms": 31.000000002677552, + "result_age_ms": 62.000000005355105, + "last_result_age_ms": 31.000000002677552, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": false + }, + "camera_ready": true, + "latency_basis": "read-return to present-call completion; excludes sensor buffering and physical display latency", + "camera_thread_stopped": true, + "camera_end": { + "frames_read": 1373, + "inferences": 1373, + "published": 1373, + "stale_dropped": 0, + "read_failures": 0, + "errors": 0, + "startup_ms": 6671.999999991385, + "capture_fps": 29.54721528793498, + "inference_fps": 29.54721528793498, + "capture_interval_ms": 46.000000002095476, + "inference_interval_ms": 46.000000002095476, + "inference_ms": 31.999999991967343, + "result_age_ms": 625.0, + "last_result_age_ms": 31.999999991967343, + "resolution": [ + 640, + 480 + ], + "error": null, + "stopping": true + }, + "status": "ok" +} \ No newline at end of file diff --git a/docs/validacao-v1.6/runtime-seed7-runtime.json b/docs/validacao-v1.6/runtime-seed7-runtime.json new file mode 100644 index 0000000..e5e3c5a --- /dev/null +++ b/docs/validacao-v1.6/runtime-seed7-runtime.json @@ -0,0 +1,325 @@ +{ + "conditions": "CPU; SDL dummy; no camera; 1100x650; fresh process; 60 warmup frames per case", + "pacing": "uncapped stress", + "python": "3.12.10", + "platform": "Windows-11-10.0.26200-SP0", + "camera_clock_resolution_ms": 15.625, + "startup_ms": 1084.03, + "rss_before_bytes": 40808448, + "rss_after_bytes": 132235264, + "rss_delta_bytes": 91426816, + "startup_watercolor_count": 0, + "startup_watercolor_bytes": 0, + "seed": 7, + "flights": { + "amazonia_normal": { + "frame": { + "median_ms": 8.975, + "p95_ms": 13.974, + "p99_ms": 18.21, + "max_ms": 20.393 + }, + "scene_setup_ms": 8.392, + "warmup": { + "median_ms": 7.733, + "p95_ms": 12.296, + "p99_ms": 351.686, + "max_ms": 351.686 + }, + "first_frame_ms": 351.686, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.9767, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 2.069, + "p99_ms": 2.89, + "max_ms": 3.255 + }, + "ground": { + "median_ms": 4.544, + "p95_ms": 6.849, + "p99_ms": 8.61, + "max_ms": 10.48 + }, + "background": { + "median_ms": 6.686, + "p95_ms": 11.052, + "p99_ms": 13.725, + "max_ms": 15.176 + }, + "world": { + "median_ms": 7.618, + "p95_ms": 12.282, + "p99_ms": 15.917, + "max_ms": 18.117 + }, + "present": { + "median_ms": 0.314, + "p95_ms": 0.661, + "p99_ms": 0.887, + "max_ms": 1.573 + } + }, + "rss_bytes": 253837312, + "renderer_caches": { + "unique_retained_surface_bytes": 170476044, + "surface_bytes_by_owner": { + "assets": 23554348, + "scene_sprites": 0, + "world_sprite_cache": 587260, + "world_transient": 1085032, + "sky": 4818952, + "ground": 917504, + "watercolor": 106342268, + "plane_skin": 23417156, + "paper_items": 9753524 + }, + "cache_items": { + "scaled": 2, + "mips": 1, + "outlines": 0, + "rotations": 7, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + } + }, + "amazonia_contrast": { + "frame": { + "median_ms": 12.172, + "p95_ms": 15.741, + "p99_ms": 19.625, + "max_ms": 28.772 + }, + "scene_setup_ms": 9.288, + "warmup": { + "median_ms": 10.676, + "p95_ms": 19.171, + "p99_ms": 26.396, + "max_ms": 26.396 + }, + "first_frame_ms": 26.396, + "frames_measured": 600, + "within_60fps_budget_fraction": 0.9683, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 1.821, + "p99_ms": 2.37, + "max_ms": 2.734 + }, + "ground": { + "median_ms": 4.428, + "p95_ms": 6.077, + "p99_ms": 7.885, + "max_ms": 13.28 + }, + "desaturate": { + "median_ms": 1.989, + "p95_ms": 3.011, + "p99_ms": 3.701, + "max_ms": 4.814 + }, + "background": { + "median_ms": 8.715, + "p95_ms": 11.683, + "p99_ms": 14.315, + "max_ms": 20.646 + }, + "world": { + "median_ms": 10.937, + "p95_ms": 14.234, + "p99_ms": 17.896, + "max_ms": 24.797 + }, + "present": { + "median_ms": 0.329, + "p95_ms": 0.614, + "p99_ms": 0.744, + "max_ms": 0.968 + } + }, + "rss_bytes": 265420800, + "renderer_caches": { + "unique_retained_surface_bytes": 176094376, + "surface_bytes_by_owner": { + "assets": 23554348, + "scene_sprites": 0, + "world_sprite_cache": 1245368, + "world_transient": 5368672, + "sky": 4818952, + "ground": 917504, + "watercolor": 106342268, + "plane_skin": 23417156, + "paper_items": 10430108 + }, + "cache_items": { + "scaled": 3, + "mips": 2, + "outlines": 1, + "rotations": 14, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + } + }, + "caatinga_normal": { + "frame": { + "median_ms": 6.482, + "p95_ms": 9.917, + "p99_ms": 11.599, + "max_ms": 12.688 + }, + "scene_setup_ms": 9.972, + "warmup": { + "median_ms": 6.445, + "p95_ms": 10.012, + "p99_ms": 245.881, + "max_ms": 245.881 + }, + "first_frame_ms": 245.881, + "frames_measured": 600, + "within_60fps_budget_fraction": 1.0, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 2.237, + "p99_ms": 2.849, + "max_ms": 3.529 + }, + "ground": { + "median_ms": 2.024, + "p95_ms": 2.947, + "p99_ms": 3.388, + "max_ms": 3.971 + }, + "background": { + "median_ms": 4.29, + "p95_ms": 7.084, + "p99_ms": 8.576, + "max_ms": 9.775 + }, + "world": { + "median_ms": 5.234, + "p95_ms": 8.267, + "p99_ms": 9.898, + "max_ms": 11.382 + }, + "present": { + "median_ms": 0.342, + "p95_ms": 0.623, + "p99_ms": 0.754, + "max_ms": 1.118 + } + }, + "rss_bytes": 261099520, + "renderer_caches": { + "unique_retained_surface_bytes": 177444808, + "surface_bytes_by_owner": { + "assets": 23483180, + "scene_sprites": 0, + "world_sprite_cache": 587260, + "world_transient": 4301432, + "sky": 4818952, + "ground": 917504, + "watercolor": 109932252, + "plane_skin": 23417156, + "paper_items": 9987072 + }, + "cache_items": { + "scaled": 2, + "mips": 1, + "outlines": 0, + "rotations": 7, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + } + }, + "caatinga_contrast": { + "frame": { + "median_ms": 9.308, + "p95_ms": 12.57, + "p99_ms": 15.246, + "max_ms": 16.275 + }, + "scene_setup_ms": 8.148, + "warmup": { + "median_ms": 8.664, + "p95_ms": 14.509, + "p99_ms": 24.14, + "max_ms": 24.14 + }, + "first_frame_ms": 19.571, + "frames_measured": 600, + "within_60fps_budget_fraction": 1.0, + "components": { + "horizon": { + "median_ms": 0.005, + "p95_ms": 1.657, + "p99_ms": 2.367, + "max_ms": 3.267 + }, + "ground": { + "median_ms": 1.865, + "p95_ms": 2.636, + "p99_ms": 3.117, + "max_ms": 5.142 + }, + "desaturate": { + "median_ms": 1.896, + "p95_ms": 2.716, + "p99_ms": 3.454, + "max_ms": 3.701 + }, + "background": { + "median_ms": 5.94, + "p95_ms": 8.397, + "p99_ms": 10.25, + "max_ms": 11.2 + }, + "world": { + "median_ms": 8.163, + "p95_ms": 11.444, + "p99_ms": 12.924, + "max_ms": 14.941 + }, + "present": { + "median_ms": 0.296, + "p95_ms": 0.605, + "p99_ms": 0.693, + "max_ms": 0.802 + } + }, + "rss_bytes": 271466496, + "renderer_caches": { + "unique_retained_surface_bytes": 179767684, + "surface_bytes_by_owner": { + "assets": 23483180, + "scene_sprites": 0, + "world_sprite_cache": 1245368, + "world_transient": 5368672, + "sky": 4818952, + "ground": 917504, + "watercolor": 109932252, + "plane_skin": 23417156, + "paper_items": 10584600 + }, + "cache_items": { + "scaled": 3, + "mips": 2, + "outlines": 1, + "rotations": 14, + "ground_groups": 0, + "asset_images": 55 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + } + } + }, + "status": "ok" +} \ No newline at end of file diff --git a/docs/validacao-v1.6/selftest-fonte.json b/docs/validacao-v1.6/selftest-fonte.json new file mode 100644 index 0000000..7afe050 --- /dev/null +++ b/docs/validacao-v1.6/selftest-fonte.json @@ -0,0 +1,114 @@ +{ + "versao": "1.6.0", + "frozen": false, + "pygame": "2.6.1", + "sprites": { + "biome_sprites": 48, + "era_final_sprites": 26, + "dieselpunk_sprites": 8, + "scenario_sprites": 27, + "waste_sprites": 4, + "powerup_sprites": 3, + "plane_sprites": 22, + "plane_menu": 22, + "pilot_layers": 106, + "ui": 2, + "ground": 6 + }, + "telas": { + "abertura": { + "media_ms": 1.36, + "p95_ms": 1.42 + }, + "vila": { + "media_ms": 32.91, + "p95_ms": 19.21 + }, + "mapa": { + "media_ms": 14.1, + "p95_ms": 15.37 + }, + "hangar": { + "media_ms": 2.81, + "p95_ms": 3.16 + }, + "hangar_padrao": { + "media_ms": 3.29, + "p95_ms": 3.47 + }, + "piloto": { + "media_ms": 11.13, + "p95_ms": 11.86 + }, + "selecao": { + "media_ms": 8.19, + "p95_ms": 8.52 + }, + "preparar": { + "media_ms": 8.69, + "p95_ms": 9.42 + }, + "melhorias": { + "media_ms": 15.91, + "p95_ms": 16.01 + }, + "melhorias_aviao": { + "media_ms": 15.04, + "p95_ms": 15.33 + }, + "opcoes": { + "media_ms": 10.62, + "p95_ms": 9.73 + }, + "projecao": { + "media_ms": 8.0, + "p95_ms": 8.09 + }, + "sobre": { + "media_ms": 7.98, + "p95_ms": 7.19 + }, + "ods": { + "media_ms": 6.55, + "p95_ms": 6.68 + } + }, + "voos": { + "amazonia": { + "quadros": 1200, + "transformacao": 74.0, + "estrelas": 2, + "estagio": 2, + "recursos": { + "papel": 0, + "plastico": 8, + "metal": 0, + "vidro": 0 + }, + "pontos": 130, + "media_ms": 8.49, + "p95_ms": 12.43 + }, + "caatinga": { + "quadros": 1200, + "transformacao": 74.0, + "estrelas": 2, + "estagio": 2, + "recursos": { + "papel": 4, + "plastico": 0, + "metal": 4, + "vidro": 0 + }, + "pontos": 130, + "media_ms": 5.91, + "p95_ms": 8.59 + } + }, + "camera": { + "modelo": true, + "detector": "ok" + }, + "falhas": [], + "status": "ok" +} diff --git a/docs/validacao-v1.6/soak.json b/docs/validacao-v1.6/soak.json new file mode 100644 index 0000000..bde43cb --- /dev/null +++ b/docs/validacao-v1.6/soak.json @@ -0,0 +1,1092 @@ +{ + "version": "1.6.0", + "cycles": [ + { + "cycle": 0, + "biome": "amazonia", + "contrast": false, + "rss_bytes": 439873536, + "loaded_surface_bytes": 44752248, + "loaded_images": 11, + "renderer_caches": { + "unique_retained_surface_bytes": 306346720, + "surface_bytes_by_owner": { + "assets": 83809864, + "scene_sprites": 2095552, + "world_sprite_cache": 29801864, + "world_transient": 22843368, + "sky": 4818952, + "ground": 917504, + "watercolor": 108715360, + "plane_skin": 41015524, + "paper_items": 12328732 + }, + "cache_items": { + "scaled": 94, + "mips": 1, + "outlines": 0, + "rotations": 121, + "ground_groups": 0, + "asset_images": 11 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 15, + "median_ms": 7.989, + "p95_ms": 13.091, + "p99_ms": 34.476, + "max_ms": 44.469 + }, + { + "cycle": 1, + "biome": "caatinga", + "contrast": false, + "rss_bytes": 461238272, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 284298440, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 27700896, + "world_transient": 26991736, + "sky": 5770612, + "ground": 917504, + "watercolor": 113818384, + "plane_skin": 43018516, + "paper_items": 17930632 + }, + "cache_items": { + "scaled": 61, + "mips": 1, + "outlines": 0, + "rotations": 129, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 21, + "median_ms": 5.861, + "p95_ms": 9.064, + "p99_ms": 12.437, + "max_ms": 206.604 + }, + { + "cycle": 2, + "biome": "amazonia", + "contrast": true, + "rss_bytes": 501501952, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 293388300, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29639840, + "world_transient": 34678504, + "sky": 5841780, + "ground": 917504, + "watercolor": 114594088, + "plane_skin": 47985584, + "paper_items": 11580840 + }, + "cache_items": { + "scaled": 88, + "mips": 1, + "outlines": 1, + "rotations": 172, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 20, + "median_ms": 11.68, + "p95_ms": 17.283, + "p99_ms": 22.815, + "max_ms": 38.456 + }, + { + "cycle": 3, + "biome": "caatinga", + "contrast": true, + "rss_bytes": 516481024, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 291591168, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29645472, + "world_transient": 27344264, + "sky": 5770612, + "ground": 917504, + "watercolor": 114501604, + "plane_skin": 55776384, + "paper_items": 9485168 + }, + "cache_items": { + "scaled": 89, + "mips": 1, + "outlines": 1, + "rotations": 124, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 21, + "median_ms": 9.652, + "p95_ms": 14.9, + "p99_ms": 18.081, + "max_ms": 225.028 + }, + { + "cycle": 4, + "biome": "amazonia", + "contrast": false, + "rss_bytes": 539521024, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 295374688, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29784464, + "world_transient": 26513592, + "sky": 5841780, + "ground": 917504, + "watercolor": 114987560, + "plane_skin": 51767676, + "paper_items": 17411952 + }, + "cache_items": { + "scaled": 91, + "mips": 1, + "outlines": 0, + "rotations": 148, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 23, + "median_ms": 8.489, + "p95_ms": 13.183, + "p99_ms": 18.684, + "max_ms": 43.37 + }, + { + "cycle": 5, + "biome": "caatinga", + "contrast": false, + "rss_bytes": 551194624, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 306611112, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29798000, + "world_transient": 33252344, + "sky": 5770612, + "ground": 917504, + "watercolor": 114491060, + "plane_skin": 56480740, + "paper_items": 17750692 + }, + "cache_items": { + "scaled": 114, + "mips": 1, + "outlines": 0, + "rotations": 198, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 21, + "median_ms": 5.689, + "p95_ms": 8.43, + "p99_ms": 11.715, + "max_ms": 203.648 + }, + { + "cycle": 6, + "biome": "amazonia", + "contrast": true, + "rss_bytes": 562851840, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 316312060, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29751280, + "world_transient": 34909240, + "sky": 5841780, + "ground": 917504, + "watercolor": 115076704, + "plane_skin": 64525544, + "paper_items": 17139848 + }, + "cache_items": { + "scaled": 110, + "mips": 1, + "outlines": 1, + "rotations": 197, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 19, + "median_ms": 11.763, + "p95_ms": 17.031, + "p99_ms": 21.642, + "max_ms": 35.901 + }, + { + "cycle": 7, + "biome": "caatinga", + "contrast": true, + "rss_bytes": 543842304, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 301217844, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29751456, + "world_transient": 32796424, + "sky": 5770612, + "ground": 917504, + "watercolor": 114612464, + "plane_skin": 60770840, + "paper_items": 8448384 + }, + "cache_items": { + "scaled": 110, + "mips": 1, + "outlines": 1, + "rotations": 195, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 19, + "median_ms": 8.811, + "p95_ms": 13.078, + "p99_ms": 16.57, + "max_ms": 223.88 + }, + { + "cycle": 8, + "biome": "amazonia", + "contrast": false, + "rss_bytes": 545083392, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 299468528, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 27749340, + "world_transient": 19019224, + "sky": 5841780, + "ground": 917504, + "watercolor": 115169616, + "plane_skin": 65229900, + "paper_items": 17391004 + }, + "cache_items": { + "scaled": 61, + "mips": 1, + "outlines": 0, + "rotations": 73, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 18, + "median_ms": 7.93, + "p95_ms": 11.686, + "p99_ms": 15.008, + "max_ms": 42.394 + }, + { + "cycle": 9, + "biome": "caatinga", + "contrast": false, + "rss_bytes": 547336192, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 296775360, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 26918176, + "world_transient": 19286104, + "sky": 5770612, + "ground": 917504, + "watercolor": 114620012, + "plane_skin": 73020700, + "paper_items": 8092092 + }, + "cache_items": { + "scaled": 55, + "mips": 1, + "outlines": 0, + "rotations": 74, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 18, + "median_ms": 6.135, + "p95_ms": 9.691, + "p99_ms": 13.022, + "max_ms": 189.22 + }, + { + "cycle": 10, + "biome": "amazonia", + "contrast": true, + "rss_bytes": 570183680, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 323541704, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29760544, + "world_transient": 37334584, + "sky": 5841780, + "ground": 917504, + "watercolor": 115253388, + "plane_skin": 68896336, + "paper_items": 17387408 + }, + "cache_items": { + "scaled": 90, + "mips": 1, + "outlines": 1, + "rotations": 179, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 27, + "median_ms": 12.157, + "p95_ms": 26.301, + "p99_ms": 33.236, + "max_ms": 57.766 + }, + { + "cycle": 11, + "biome": "caatinga", + "contrast": true, + "rss_bytes": 556720128, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 314031064, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 28137360, + "world_transient": 31862872, + "sky": 5770612, + "ground": 917504, + "watercolor": 114643856, + "plane_skin": 72800744, + "paper_items": 11747956 + }, + "cache_items": { + "scaled": 62, + "mips": 1, + "outlines": 1, + "rotations": 131, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 22, + "median_ms": 10.646, + "p95_ms": 17.415, + "p99_ms": 44.885, + "max_ms": 254.415 + }, + { + "cycle": 12, + "biome": "amazonia", + "contrast": false, + "rss_bytes": 579002368, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 336600628, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29677152, + "world_transient": 45178008, + "sky": 5841780, + "ground": 917504, + "watercolor": 115141584, + "plane_skin": 78145252, + "paper_items": 13549188 + }, + "cache_items": { + "scaled": 112, + "mips": 1, + "outlines": 0, + "rotations": 273, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 26, + "median_ms": 8.609, + "p95_ms": 12.337, + "p99_ms": 14.962, + "max_ms": 38.134 + }, + { + "cycle": 13, + "biome": "caatinga", + "contrast": false, + "rss_bytes": 548413440, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 306641932, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29704400, + "world_transient": 24422312, + "sky": 5770612, + "ground": 917504, + "watercolor": 115893632, + "plane_skin": 72473836, + "paper_items": 9309476 + }, + "cache_items": { + "scaled": 92, + "mips": 1, + "outlines": 0, + "rotations": 123, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 22, + "median_ms": 6.329, + "p95_ms": 8.926, + "p99_ms": 10.442, + "max_ms": 213.015 + }, + { + "cycle": 14, + "biome": "amazonia", + "contrast": true, + "rss_bytes": 571858944, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 323197640, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29808224, + "world_transient": 27283448, + "sky": 5841780, + "ground": 917504, + "watercolor": 116575992, + "plane_skin": 76632248, + "paper_items": 17988284 + }, + "cache_items": { + "scaled": 89, + "mips": 1, + "outlines": 1, + "rotations": 147, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 17, + "median_ms": 12.1, + "p95_ms": 16.784, + "p99_ms": 19.913, + "max_ms": 48.19 + }, + { + "cycle": 15, + "biome": "caatinga", + "contrast": true, + "rss_bytes": 586772480, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 340066496, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29803296, + "world_transient": 40395624, + "sky": 5770612, + "ground": 917504, + "watercolor": 116027624, + "plane_skin": 82230760, + "paper_items": 16770916 + }, + "cache_items": { + "scaled": 88, + "mips": 1, + "outlines": 1, + "rotations": 234, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 25, + "median_ms": 9.339, + "p95_ms": 14.118, + "p99_ms": 17.259, + "max_ms": 203.85 + }, + { + "cycle": 16, + "biome": "amazonia", + "contrast": false, + "rss_bytes": 566026240, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 324501600, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29792544, + "world_transient": 33255912, + "sky": 5841780, + "ground": 917504, + "watercolor": 116669268, + "plane_skin": 75681676, + "paper_items": 14192756 + }, + "cache_items": { + "scaled": 113, + "mips": 1, + "outlines": 0, + "rotations": 201, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 14, + "median_ms": 8.526, + "p95_ms": 13.634, + "p99_ms": 18.476, + "max_ms": 31.096 + }, + { + "cycle": 17, + "biome": "caatinga", + "contrast": false, + "rss_bytes": 578560000, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 334477576, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29811248, + "world_transient": 37462392, + "sky": 5770612, + "ground": 917504, + "watercolor": 115978828, + "plane_skin": 78980876, + "paper_items": 17405956 + }, + "cache_items": { + "scaled": 93, + "mips": 1, + "outlines": 0, + "rotations": 180, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 18, + "median_ms": 6.307, + "p95_ms": 9.447, + "p99_ms": 11.4, + "max_ms": 209.945 + }, + { + "cycle": 18, + "biome": "amazonia", + "contrast": true, + "rss_bytes": 566550528, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 320724948, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 28168044, + "world_transient": 20065384, + "sky": 5841780, + "ground": 917504, + "watercolor": 116568896, + "plane_skin": 83836552, + "paper_items": 17176628 + }, + "cache_items": { + "scaled": 61, + "mips": 1, + "outlines": 1, + "rotations": 75, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 21, + "median_ms": 12.085, + "p95_ms": 17.256, + "p99_ms": 21.449, + "max_ms": 32.245 + }, + { + "cycle": 19, + "biome": "caatinga", + "contrast": true, + "rss_bytes": 575082496, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 330938244, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29672288, + "world_transient": 41869272, + "sky": 5770612, + "ground": 917504, + "watercolor": 116048668, + "plane_skin": 77541472, + "paper_items": 10968268 + }, + "cache_items": { + "scaled": 90, + "mips": 1, + "outlines": 1, + "rotations": 203, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 22, + "median_ms": 9.243, + "p95_ms": 13.425, + "p99_ms": 17.352, + "max_ms": 223.375 + }, + { + "cycle": 20, + "biome": "amazonia", + "contrast": false, + "rss_bytes": 574377984, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 327712316, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29785696, + "world_transient": 29097704, + "sky": 5841780, + "ground": 917504, + "watercolor": 116331384, + "plane_skin": 80586668, + "paper_items": 17001420 + }, + "cache_items": { + "scaled": 91, + "mips": 1, + "outlines": 0, + "rotations": 147, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 20, + "median_ms": 8.424, + "p95_ms": 11.823, + "p99_ms": 13.601, + "max_ms": 16.725 + }, + { + "cycle": 21, + "biome": "caatinga", + "contrast": false, + "rss_bytes": 581918720, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 335278940, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29797472, + "world_transient": 40089672, + "sky": 5770612, + "ground": 917504, + "watercolor": 115922084, + "plane_skin": 85188340, + "paper_items": 9443096 + }, + "cache_items": { + "scaled": 114, + "mips": 1, + "outlines": 0, + "rotations": 243, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 16, + "median_ms": 6.022, + "p95_ms": 9.574, + "p99_ms": 11.848, + "max_ms": 243.886 + }, + { + "cycle": 22, + "biome": "amazonia", + "contrast": true, + "rss_bytes": 564092928, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 316161140, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 28261396, + "world_transient": 20065384, + "sky": 5841780, + "ground": 917504, + "watercolor": 116546784, + "plane_skin": 78866004, + "paper_items": 17512128 + }, + "cache_items": { + "scaled": 62, + "mips": 1, + "outlines": 1, + "rotations": 75, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 20, + "median_ms": 12.215, + "p95_ms": 17.724, + "p99_ms": 21.322, + "max_ms": 30.869 + }, + { + "cycle": 23, + "biome": "caatinga", + "contrast": true, + "rss_bytes": 578899968, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 329486140, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 28132960, + "world_transient": 31824360, + "sky": 5770612, + "ground": 917504, + "watercolor": 116276528, + "plane_skin": 81629940, + "paper_items": 16784076 + }, + "cache_items": { + "scaled": 61, + "mips": 1, + "outlines": 1, + "rotations": 132, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 24, + "median_ms": 10.427, + "p95_ms": 15.307, + "p99_ms": 18.168, + "max_ms": 279.424 + }, + { + "cycle": 24, + "biome": "amazonia", + "contrast": false, + "rss_bytes": 576028672, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 328949628, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29801864, + "world_transient": 25518872, + "sky": 5841780, + "ground": 917504, + "watercolor": 116440836, + "plane_skin": 85442344, + "paper_items": 16836268 + }, + "cache_items": { + "scaled": 94, + "mips": 1, + "outlines": 0, + "rotations": 126, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 18, + "median_ms": 9.393, + "p95_ms": 15.593, + "p99_ms": 20.566, + "max_ms": 33.701 + }, + { + "cycle": 25, + "biome": "caatinga", + "contrast": false, + "rss_bytes": 570695680, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 317360144, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 28241616, + "world_transient": 22712264, + "sky": 5770612, + "ground": 917504, + "watercolor": 116006796, + "plane_skin": 78612000, + "paper_items": 16949192 + }, + "cache_items": { + "scaled": 73, + "mips": 1, + "outlines": 0, + "rotations": 95, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 19, + "median_ms": 6.152, + "p95_ms": 9.359, + "p99_ms": 12.427, + "max_ms": 214.845 + }, + { + "cycle": 26, + "biome": "amazonia", + "contrast": true, + "rss_bytes": 563351552, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 317617588, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29639840, + "world_transient": 26640488, + "sky": 5841780, + "ground": 917504, + "watercolor": 116713444, + "plane_skin": 81629940, + "paper_items": 8084432 + }, + "cache_items": { + "scaled": 88, + "mips": 1, + "outlines": 1, + "rotations": 121, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 22, + "median_ms": 12.933, + "p95_ms": 17.439, + "p99_ms": 20.735, + "max_ms": 26.095 + }, + { + "cycle": 27, + "biome": "caatinga", + "contrast": true, + "rss_bytes": 579690496, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 334090848, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 28137888, + "world_transient": 31488728, + "sky": 5770612, + "ground": 917504, + "watercolor": 116408424, + "plane_skin": 85696348, + "paper_items": 17521184 + }, + "cache_items": { + "scaled": 62, + "mips": 1, + "outlines": 1, + "rotations": 130, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 21, + "median_ms": 9.603, + "p95_ms": 13.893, + "p99_ms": 18.38, + "max_ms": 222.357 + }, + { + "cycle": 28, + "biome": "amazonia", + "contrast": false, + "rss_bytes": 578326528, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 333261756, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29798000, + "world_transient": 36038792, + "sky": 5841780, + "ground": 917504, + "watercolor": 116524808, + "plane_skin": 78612000, + "paper_items": 17378712 + }, + "cache_items": { + "scaled": 114, + "mips": 1, + "outlines": 0, + "rotations": 198, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 16, + "median_ms": 8.772, + "p95_ms": 12.487, + "p99_ms": 14.843, + "max_ms": 17.89 + }, + { + "cycle": 29, + "biome": "caatinga", + "contrast": false, + "rss_bytes": 568856576, + "loaded_surface_bytes": 46054608, + "loaded_images": 114, + "renderer_caches": { + "unique_retained_surface_bytes": 324027596, + "surface_bytes_by_owner": { + "assets": 46054608, + "scene_sprites": 2095552, + "world_sprite_cache": 29704400, + "world_transient": 24886616, + "sky": 5770612, + "ground": 917504, + "watercolor": 116119444, + "plane_skin": 81375936, + "paper_items": 17102924 + }, + "cache_items": { + "scaled": 92, + "mips": 1, + "outlines": 0, + "rotations": 125, + "ground_groups": 0, + "asset_images": 114 + }, + "estimate": "pitch*height unique by Surface object; shared pygame subsurfaces can be conservatively overcounted" + }, + "entities": 20, + "median_ms": 6.239, + "p95_ms": 8.729, + "p99_ms": 10.753, + "max_ms": 204.26 + } + ], + "camera": false, + "dt_s": 0.016666666666666666, + "scope": "synthetic rendering and scene lifecycle; not physical acceptance", + "wall_seconds": 758.138, + "simulated_seconds": 1215.5, + "failures": [], + "status": "ok" +} diff --git a/requirements-ci-py312.txt b/requirements-ci-py312.txt new file mode 100644 index 0000000..9e8dbc6 --- /dev/null +++ b/requirements-ci-py312.txt @@ -0,0 +1,13 @@ +# Conjunto de teste Python 3.12; separado do detector/build desktop. +pygame==2.6.1 +pillow==13.0.0 +numpy==2.5.4 +pytest==9.1.1 +pytest-cov==5.0.0 +coverage==7.6.1 +ruff==0.17.2 +iniconfig==2.3.1 +packaging==26.3 +pluggy==1.7.0 +Pygments==2.21.0 +colorama==0.4.6; sys_platform == "win32" diff --git a/requirements-ci-py38.txt b/requirements-ci-py38.txt new file mode 100644 index 0000000..81b0767 --- /dev/null +++ b/requirements-ci-py38.txt @@ -0,0 +1,15 @@ +# Conjunto de teste compatível com o piso Python 3.8; sem webcam. +pygame==2.6.1 +pillow==10.4.0 +numpy==1.24.4 +pytest==8.3.5 +pytest-cov==5.0.0 +coverage==7.6.1 +ruff==0.17.2 +iniconfig==2.1.0 +packaging==25.0 +pluggy==1.5.0 +exceptiongroup==1.3.0 +typing_extensions==4.13.2 +tomli==2.2.1 +colorama==0.4.6; sys_platform == "win32" diff --git a/requirements-dev.txt b/requirements-dev.txt index 299bb7d..14708b8 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,6 +1,7 @@ # Desenvolvimento: testes, lint, build do executável e geração de assets. -r requirements-webcam.txt pytest>=7 +pytest-cov>=5,<6 ruff>=0.5 pyinstaller>=6,<7 numpy>=1.24 diff --git a/tests/helpers.py b/tests/helpers.py new file mode 100644 index 0000000..6af3180 --- /dev/null +++ b/tests/helpers.py @@ -0,0 +1,45 @@ +"""Fontes sintéticas e calibração compartilhadas pelos testes de entrada. + +Nenhuma imagem ou câmera real é usada. Fora destes helpers, prefira comandos e +resultados públicos; detalhes internos só para injeção de falhas/invariantes. +""" + +from dobramundo.input.pose import SEGMENTS, AxisMapper + +CAL_READINGS = 70 + + +def landmarks(points: dict, visibility: float = 0.9): + data = [(0.5, 0.5, 0.0)] * 33 + for index, (x, y) in points.items(): + data[index] = (x, y, visibility) + return data + + +class FakeSource: + """Fonte de câmera falsa: devolve os pontos que o teste definir.""" + + def __init__(self) -> None: + self.error = None + self.seq = 0 + self.points = None + + def start(self): + pass + + def stop(self): + pass + + def show(self, points) -> None: + self.seq += 1 + self.points = points + + def snapshot(self): + return self.seq, self.points, None + + +def calibrated(segment: str = "tronco_pe") -> AxisMapper: + mapper = AxisMapper(SEGMENTS[segment]) + for _ in range(CAL_READINGS): + mapper.feed((0.5, 0.5)) + return mapper diff --git a/tests/test_accessible_baseline.py b/tests/test_accessible_baseline.py index c2dde42..8777710 100644 --- a/tests/test_accessible_baseline.py +++ b/tests/test_accessible_baseline.py @@ -34,7 +34,5 @@ def test_parts_remain_a_collection_and_expedition_star_requirement(): assert stars_for(100.0, requirements, {"leme": 1, "quilha": 1}) == 3 assert all(part.level_costs for part in PLANE_PARTS) assert all( - "mais rápido" not in part.description and "mais agilidade" not in part.description - for part in PLANE_PARTS + "mais rápido" not in part.description and "mais agilidade" not in part.description for part in PLANE_PARTS ) - diff --git a/tests/test_build_contracts.py b/tests/test_build_contracts.py new file mode 100644 index 0000000..7cb8840 --- /dev/null +++ b/tests/test_build_contracts.py @@ -0,0 +1,63 @@ +"""Um build que falha não pode reutilizar evidência de sucesso anterior.""" + +import json +import subprocess +import sys + +import pytest + +from dobramundo.selftest import _safe_error_detail +from tools import build_desktop + + +def test_failed_build_invalidates_the_previous_success(tmp_path, monkeypatch): + monkeypatch.setattr(build_desktop, "ROOT", tmp_path) + report = tmp_path / "build" / "desktop-selftest" / "self_test.json" + report.parent.mkdir(parents=True) + report.write_text('{"status":"ok","run_id":"old"}', encoding="utf-8") + + def fail(command, **kwargs): + raise subprocess.CalledProcessError(7, command) + + monkeypatch.setattr(build_desktop.subprocess, "run", fail) + monkeypatch.setattr(build_desktop, "require_linux_egl_runtime", lambda required: None) + monkeypatch.setattr(sys, "argv", ["build_desktop.py"]) + with pytest.raises(subprocess.CalledProcessError): + build_desktop.main() + current = json.loads(report.read_text(encoding="utf-8")) + assert current["status"] == "failed" + assert current["exit_code"] == 7 + assert current["run_id"] != "old" + + +def test_missing_linux_runtime_invalidates_old_success_before_build(tmp_path, monkeypatch): + monkeypatch.setattr(build_desktop, "ROOT", tmp_path) + monkeypatch.setattr(build_desktop.sys, "platform", "linux") + monkeypatch.setattr(sys, "argv", ["build_desktop.py"]) + report = tmp_path / "build" / "desktop-selftest" / "self_test.json" + report.parent.mkdir(parents=True) + report.write_text('{"status":"ok","run_id":"old"}', encoding="utf-8") + + def missing(name): + raise OSError(name) + + monkeypatch.setattr(build_desktop.ctypes, "CDLL", missing) + with pytest.raises(RuntimeError, match="libegl1"): + build_desktop.main() + current = json.loads(report.read_text(encoding="utf-8")) + assert current["status"] == "failed" and current["run_id"] != "old" + + +@pytest.mark.parametrize( + "library", + [ + r"C:\Users\João Vítor\project\libmediapipe.dll", + "/home/runner/project/libmediapipe.so", + ], +) +def test_native_error_preserves_library_without_local_directories(library): + error = RuntimeError(f"Failed to load '{library}'") + error.__cause__ = OSError("libEGL.so.1: cannot open shared object file") + detail = _safe_error_detail(error) + assert "libmediapipe" in detail and "libEGL.so.1" in detail + assert not any(value in detail for value in ("Users", "João", "runner", "/home", "project")) diff --git a/tests/test_camera_benchmark.py b/tests/test_camera_benchmark.py index a2419f2..c6389bb 100644 --- a/tests/test_camera_benchmark.py +++ b/tests/test_camera_benchmark.py @@ -57,9 +57,11 @@ def test_benchmark_warms_up_then_measures_a_separate_sample_window(monkeypatch): def test_benchmark_reports_insufficient_when_no_results_are_published(monkeypatch): - monkeypatch.setattr(benchmark_camera, "PoseCameraSource", lambda model, camera_index=0: SyntheticSource( - model, camera_index, publish=False - )) + monkeypatch.setattr( + benchmark_camera, + "PoseCameraSource", + lambda model, camera_index=0: SyntheticSource(model, camera_index, publish=False), + ) monkeypatch.setattr(benchmark_camera, "WARMUP_TIMEOUT_S", 0.01) monkeypatch.setattr(benchmark_camera, "POLL_INTERVAL_S", 0.001) report = benchmark_camera.benchmark(0.02, 0, None) diff --git a/tests/test_camera_lifecycle.py b/tests/test_camera_lifecycle.py index 4490cf7..86d721e 100644 --- a/tests/test_camera_lifecycle.py +++ b/tests/test_camera_lifecycle.py @@ -132,4 +132,3 @@ def join(self, timeout=None): thread.alive = False source.stop() assert source._thread is None - diff --git a/tests/test_camera_metrics.py b/tests/test_camera_metrics.py index da348ab..3d95d2f 100644 --- a/tests/test_camera_metrics.py +++ b/tests/test_camera_metrics.py @@ -109,4 +109,3 @@ def test_camera_descarta_resultado_que_envelheceu_durante_inferencia(): assert report["stale_dropped"] == 1 assert report["published"] == 0 assert report["last_result_age_ms"] == 500.0 - diff --git a/tests/test_cenas.py b/tests/test_cenas.py index 804543e..f45a210 100644 --- a/tests/test_cenas.py +++ b/tests/test_cenas.py @@ -4,7 +4,7 @@ import pygame import pytest -from test_controle import CAL_READINGS, FakeSource, landmarks +from helpers import CAL_READINGS, FakeSource, landmarks from dobramundo import config as C from dobramundo.content.progress import VILLAGE_BY_KEY @@ -166,7 +166,7 @@ def test_pausa_automatica_e_retomada(app): app.input.source_factory = lambda: source app.profile.controle = "mao_direita" app.apply_options() - from test_controle import landmarks + from helpers import landmarks for _ in range(CAL_READINGS): source.show(landmarks({16: (0.5, 0.5)})) diff --git a/tests/test_cobertura.py b/tests/test_cobertura.py index 62e4d0b..7d1cfc3 100644 --- a/tests/test_cobertura.py +++ b/tests/test_cobertura.py @@ -4,7 +4,7 @@ import pygame import pytest -from test_controle import CAL_READINGS, FakeSource, landmarks +from helpers import CAL_READINGS, FakeSource, landmarks from dobramundo import config as C from dobramundo.audio import Audio diff --git a/tests/test_console_e_chao.py b/tests/test_console_e_chao.py index dcd7daa..764bf4e 100644 --- a/tests/test_console_e_chao.py +++ b/tests/test_console_e_chao.py @@ -12,7 +12,7 @@ import pygame import pytest -from test_controle import FakeSource, landmarks +from helpers import FakeSource, landmarks from dobramundo import __version__ from dobramundo import config as C @@ -312,6 +312,7 @@ def cartucho(monkeypatch, tmp_path): spec = importlib.util.spec_from_file_location("build_cartridge", ROOT / "tools" / "build_cartridge.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) + monkeypatch.setattr(module, "STAGE_ROOT", tmp_path) monkeypatch.setattr(module, "STAGE", tmp_path / "cartucho") return module diff --git a/tests/test_controle.py b/tests/test_controle.py index a1a56ae..ba8bb8f 100644 --- a/tests/test_controle.py +++ b/tests/test_controle.py @@ -4,6 +4,7 @@ import pygame import pytest +from helpers import CAL_READINGS, FakeSource, calibrated, landmarks from dobramundo import config as C from dobramundo.input.hub import AUTO_PAUSE_S, InputHub @@ -11,36 +12,6 @@ from dobramundo.ui.widgets import Button, Menu # leituras suficientes para calibrar (2 s a 30 leituras por segundo, com folga) -CAL_READINGS = 70 - - -def landmarks(points: dict, visibility: float = 0.9): - data = [(0.5, 0.5, 0.0)] * 33 - for index, (x, y) in points.items(): - data[index] = (x, y, visibility) - return data - - -class FakeSource: - """Fonte de câmera falsa: devolve os pontos que o teste definir.""" - - def __init__(self) -> None: - self.error = None - self.seq = 0 - self.points = None - - def start(self): - pass - - def stop(self): - pass - - def show(self, points) -> None: - self.seq += 1 - self.points = points - - def snapshot(self): - return self.seq, self.points, None @pytest.mark.parametrize("key", sorted(SEGMENTS)) @@ -56,13 +27,6 @@ def test_tronco_precisa_de_dois_pontos(): assert segment_point(landmarks({11: (0.5, 0.5)}), segment) is None -def calibrated(segment: str = "tronco_pe") -> AxisMapper: - mapper = AxisMapper(SEGMENTS[segment]) - for _ in range(CAL_READINGS): - mapper.feed((0.5, 0.5)) - return mapper - - def test_calibracao_usa_a_mediana(): mapper = AxisMapper(SEGMENTS["cabeca"]) for i in range(CAL_READINGS): diff --git a/tests/test_sprint3_controle.py b/tests/test_dwell_editors.py similarity index 100% rename from tests/test_sprint3_controle.py rename to tests/test_dwell_editors.py diff --git a/tests/test_foco_e_controle.py b/tests/test_foco_e_controle.py index df37c65..0a1a42e 100644 --- a/tests/test_foco_e_controle.py +++ b/tests/test_foco_e_controle.py @@ -14,6 +14,7 @@ import pygame import pytest from conftest import DT, make_run +from helpers import CAL_READINGS, FakeSource, calibrated, landmarks from dobramundo import config as C from dobramundo.content.biomes import BIOMES @@ -22,49 +23,11 @@ from dobramundo.game.player import Player from dobramundo.game.run import FlightRun from dobramundo.input.hub import InputHub -from dobramundo.input.pose import SEGMENTS, AxisMapper from dobramundo.persistence import Profile from dobramundo.scenes.result import apply_run SEED = 7 # leituras suficientes para calibrar (2 s a 30 leituras por segundo, com folga) -CAL_READINGS = 70 - - -def landmarks(points: dict, visibility: float = 0.9): - data = [(0.5, 0.5, 0.0)] * 33 - for index, (x, y) in points.items(): - data[index] = (x, y, visibility) - return data - - -class FakeSource: - """Fonte de câmera falsa: devolve os pontos que o teste definir.""" - - def __init__(self) -> None: - self.error = None - self.seq = 0 - self.points = None - - def start(self): - pass - - def stop(self): - pass - - def show(self, points) -> None: - self.seq += 1 - self.points = points - - def snapshot(self): - return self.seq, self.points, None - - -def calibrated(segment: str = "tronco_pe") -> AxisMapper: - mapper = AxisMapper(SEGMENTS[segment]) - for _ in range(CAL_READINGS): - mapper.feed((0.5, 0.5)) - return mapper def threat_run(top: float | None = None, focus: bool = True) -> tuple: diff --git a/tests/test_controle_sprint3.py b/tests/test_head_tracking.py similarity index 91% rename from tests/test_controle_sprint3.py rename to tests/test_head_tracking.py index c2ad72e..478653e 100644 --- a/tests/test_controle_sprint3.py +++ b/tests/test_head_tracking.py @@ -98,8 +98,12 @@ def test_cursor_corporal_alcanca_os_limites_uteis(): for _ in range(70): source.show(frame({0: (0.5, 0.5), 7: (0.46, 0.5), 8: (0.54, 0.5)})) hub.update(1 / 30) - for x, y, expected in ((0.75, 0.5, (C.WIDTH - 1, C.HEIGHT // 2)), (0.25, 0.5, (0, C.HEIGHT // 2)), - (0.5, 0.75, (C.WIDTH // 2, C.HEIGHT - 1)), (0.5, 0.25, (C.WIDTH // 2, 0))): + for x, y, expected in ( + (0.75, 0.5, (C.WIDTH - 1, C.HEIGHT // 2)), + (0.25, 0.5, (0, C.HEIGHT // 2)), + (0.5, 0.75, (C.WIDTH // 2, C.HEIGHT - 1)), + (0.5, 0.25, (C.WIDTH // 2, 0)), + ): for _ in range(70): source.show(frame({0: (x, y), 7: (x - 0.04, y), 8: (x + 0.04, y)})) hub.update(1 / 30) @@ -127,10 +131,12 @@ def test_leitura_antiga_invalida_cursor_e_nao_reusa_quadro(): def test_perfil_migra_pedidos_e_normaliza_novas_opcoes(): - profile = Profile.from_dict({ - "opcoes": {"permanencia_editor": 9.0, "escala_contraste": 9.0}, - "pedidos_vila": {"horta": "solicitada", "desconhecida": "concluida", "escola": "errada"}, - }) + profile = Profile.from_dict( + { + "opcoes": {"permanencia_editor": 9.0, "escala_contraste": 9.0}, + "pedidos_vila": {"horta": "solicitada", "desconhecida": "concluida", "escola": "errada"}, + } + ) assert profile.opcoes.permanencia_editor == 5.0 assert profile.opcoes.escala_contraste == 1.6 assert profile.pedidos_vila == {"horta": "solicitada"} @@ -141,4 +147,3 @@ def test_perfil_migra_pedidos_e_normaliza_novas_opcoes(): assert old.opcoes.permanencia_editor == 3.0 assert old.opcoes.escala_contraste == 1.3 assert old.pedidos_vila == {} - diff --git a/tests/test_itens_refinados.py b/tests/test_itens_refinados.py index 5823767..4feb2eb 100644 --- a/tests/test_itens_refinados.py +++ b/tests/test_itens_refinados.py @@ -16,8 +16,16 @@ def _atlas(path, columns: int, rows: int, *, blank_last: bool = False) -> pygame """Grade propositalmente não divisível por número inteiro de pixels.""" width, height = columns * 25 + 1, rows * 25 + 1 atlas = pygame.Surface((width, height), pygame.SRCALPHA) - colors = ((209, 72, 64), (55, 147, 191), (230, 176, 56), (74, 154, 94), - (161, 95, 176), (69, 168, 161), (203, 116, 57), (238, 238, 238)) + colors = ( + (209, 72, 64), + (55, 147, 191), + (230, 176, 56), + (74, 154, 94), + (161, 95, 176), + (69, 168, 161), + (203, 116, 57), + (238, 238, 238), + ) for index in range(columns * rows): if blank_last and index == columns * rows - 1: continue @@ -32,8 +40,14 @@ def _atlas(path, columns: int, rows: int, *, blank_last: bool = False) -> pygame def _obstacle_atlas(path) -> pygame.Surface: atlas = pygame.Surface((1536, 1024), pygame.SRCALPHA) - crops = ((56, 297, 512, 472), (548, 174, 1078, 270), (1258, 23, 1412, 480), - (31, 655, 512, 953), (548, 646, 1145, 742), (1223, 513, 1455, 977)) + crops = ( + (56, 297, 512, 472), + (548, 174, 1078, 270), + (1258, 23, 1412, 480), + (31, 655, 512, 953), + (548, 646, 1145, 742), + (1223, 513, 1455, 977), + ) for index, (x0, y0, x1, y1) in enumerate(crops): color = (30 + index * 20, 100 + index * 10, 180, 255) pygame.draw.ellipse(atlas, color, (x0 + 3, y0 + 3, x1 - x0 - 6, y1 - y0 - 6)) diff --git a/tests/test_sprint3_feedback.py b/tests/test_multimodal_feedback.py similarity index 86% rename from tests/test_sprint3_feedback.py rename to tests/test_multimodal_feedback.py index 87892de..e11fc7e 100644 --- a/tests/test_sprint3_feedback.py +++ b/tests/test_multimodal_feedback.py @@ -32,14 +32,15 @@ def test_dois_beneficios_tem_relogios_visuais_independentes(app): scene.run.magnet_timer = 7.0 screen = app.canvas scene.draw_hud(screen) - first = screen.subsurface((940, 90, 140, 62)).copy() + # O painel acomoda cinco vidas; ambos os relógios ficam sob sua borda esquerda. + first = screen.subsurface((860, 90, 160, 62)).copy() scene.run.shield_timer = 2.0 scene.draw_hud(screen) - second = screen.subsurface((940, 90, 140, 62)).copy() + second = screen.subsurface((860, 90, 160, 62)).copy() assert pygame.image.tobytes(first, "RGB") != pygame.image.tobytes(second, "RGB") # Só o relógio do escudo mudou; o ímã à direita conserva a informação. - assert pygame.image.tobytes(first.subsurface((80, 0, 60, 62)), "RGB") == pygame.image.tobytes( - second.subsurface((80, 0, 60, 62)), "RGB" + assert pygame.image.tobytes(first.subsurface((66, 0, 94, 62)), "RGB") == pygame.image.tobytes( + second.subsurface((66, 0, 94, 62)), "RGB" ) diff --git a/tests/test_paper_items.py b/tests/test_paper_items.py index 9c3f375..3c8326b 100644 --- a/tests/test_paper_items.py +++ b/tests/test_paper_items.py @@ -13,8 +13,9 @@ def _waste(z: float = 360.0, y: float = 100.0) -> Entity: return Entity(z=z, lane=0, kind="waste", y=y, sprite="papel") -def _obstacle(kind: str, *, width: float = 100.0, y_min: float = 0.0, y_max: float = 70.0, - solar: bool = False) -> Entity: +def _obstacle( + kind: str, *, width: float = 100.0, y_min: float = 0.0, y_max: float = 70.0, solar: bool = False +) -> Entity: spec = ObstacleSpec(kind, "unused", 90.0, width, y_min, y_max) return Entity(z=360.0, lane=0, kind=kind, spec=spec, solar=solar) @@ -22,8 +23,12 @@ def _obstacle(kind: str, *, width: float = 100.0, y_min: float = 0.0, y_max: flo def test_tokens_nativos_distintos_estaticos_e_sem_assets(): items = PaperItems() kinds = ["papel", "plastico", "metal", "vidro", "shield", "magnet", "repair"] - canonical = [items.canonical[("waste", key)] if key in ("papel", "plastico", "metal", "vidro") - else items.canonical[("powerup", key)] for key in kinds] + canonical = [ + items.canonical[("waste", key)] + if key in ("papel", "plastico", "metal", "vidro") + else items.canonical[("powerup", key)] + for key in kinds + ] assert len({pygame.image.tobytes(surface, "RGBA") for surface in canonical}) == len(kinds) screen = pygame.Surface((1100, 650), pygame.SRCALPHA) diff --git a/tests/test_percurso_aquarela.py b/tests/test_percurso_aquarela.py index d91eb2f..d358c5f 100644 --- a/tests/test_percurso_aquarela.py +++ b/tests/test_percurso_aquarela.py @@ -70,8 +70,9 @@ def test_empty_or_tiny_bank_atlas_falls_back_instead_of_dividing_by_zero(display assets = Assets() original = assets.sprite empty = pygame.Surface(size, pygame.SRCALPHA) - monkeypatch.setattr(assets, "sprite", lambda folder, name: empty if name.startswith("banks_") - else original(folder, name)) + monkeypatch.setattr( + assets, "sprite", lambda folder, name: empty if name.startswith("banks_") else original(folder, name) + ) painter = WatercolorWorld(assets) assert painter.draw(display, World(BIOMES["amazonia"]), 0) is False diff --git a/tests/test_perfis_recuperacao.py b/tests/test_perfis_recuperacao.py new file mode 100644 index 0000000..93bd52e --- /dev/null +++ b/tests/test_perfis_recuperacao.py @@ -0,0 +1,279 @@ +"""Recuperação e slots locais sem tocar em dados reais do usuário.""" + +from __future__ import annotations + +import json + +import pygame +import pytest +from helpers import FakeSource + +from dobramundo import persistence as P +from dobramundo.input.pose import SEGMENTS, BodyControl + + +def _profile(points: int, consent: bool = False) -> P.Profile: + profile = P.Profile() + profile.pontos = points + profile.consentimento = consent + profile.piloto["chapeu"] = "coroa" if points else "nenhum" + profile.opcoes.volume_geral = points / 100 + return profile + + +def test_backup_valido_recupera_perfil_corrompido_e_preserva_copia(data_dir): + assert P.save_profile(_profile(10)) + assert P.save_profile(_profile(25, True)) + path = P.profile_path() + path.write_bytes(b"{arquivo interrompido") + + profile, notice = P.load_profile_with_notice() + + assert profile.pontos == 10 + assert profile.consentimento is False + assert notice and "salvamento íntegro" in notice + assert P._profile_from_bytes(path.read_bytes()).pontos == 10 + assert list(data_dir.glob("dobramundo_perfil.corrompido*.json")) + + +@pytest.mark.parametrize("invalid_raw", [b"", b"{perfil interrompido"]) +def test_perfil_corrompido_sem_backup_valido_avisa_e_preserva_original(data_dir, invalid_raw): + path = P.profile_path() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(invalid_raw) + path.with_name(path.name + ".bak").write_bytes(b"not-json") + path.with_name(path.name + ".bak.1").write_bytes(b"") + + profile, notice = P.load_profile_with_notice() + + assert profile.pontos == 0 + assert notice and "estava danificado" in notice + archived = list(data_dir.glob("dobramundo_perfil.corrompido*.json")) + assert len(archived) == 1 + assert archived[0].read_bytes() == invalid_raw + assert not path.exists() + + +def test_arquivo_vazio_tambem_tenta_backup(data_dir): + assert P.save_profile(_profile(7)) + assert P.save_profile(_profile(12)) + P.profile_path().write_bytes(b"") + + profile, notice = P.load_profile_with_notice() + + assert profile.pontos == 7 + assert notice + assert list(data_dir.glob("dobramundo_perfil.corrompido*.json")) + + +def test_backup_recupera_quando_arquivo_principal_sumiu(data_dir): + assert P.save_profile(_profile(8)) + assert P.save_profile(_profile(13)) + P.profile_path().unlink() + + profile, notice = P.load_profile_with_notice() + + assert profile.pontos == 8 + assert notice + assert P.profile_path().is_file() + + +def test_leitura_bloqueada_impede_salvar_perfil_vazio(data_dir, monkeypatch): + path = P.profile_path() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("conteúdo preservado", encoding="utf-8") + original_read_bytes = type(path).read_bytes + + def blocked_read(candidate): + if candidate == path: + raise PermissionError("bloqueado no teste") + return original_read_bytes(candidate) + + monkeypatch.setattr(type(path), "read_bytes", blocked_read) + profile, notice = P.load_profile_with_notice() + + assert notice and "Não foi possível ler" in notice + assert not P.save_profile(profile) + monkeypatch.setattr(type(path), "read_bytes", original_read_bytes) + assert path.read_text(encoding="utf-8") == "conteúdo preservado" + P._READ_BLOCKED_SLOT_IDS.discard(P.DEFAULT_PROFILE_SLOT) + + +def test_slots_independentes_e_indice_nao_guarda_nomes(data_dir): + assert P.save_profile(_profile(31, True)) + slot = P.create_profile_slot() + assert slot is not None + assert P.set_active_profile_slot(slot.id) + assert P.save_profile(_profile(4), slot.id) + + principal = P.load_profile_with_notice(P.DEFAULT_PROFILE_SLOT)[0] + extra = P.load_profile_with_notice(slot.id)[0] + index = json.loads(P.profiles_index_path().read_text(encoding="utf-8")) + + assert principal.pontos == 31 and principal.consentimento is True + assert extra.pontos == 4 and extra.consentimento is False + assert index["active"] == slot.id + assert all("nome" not in key.lower() for key in index) + assert [entry.label for entry in P.list_profile_slots()] == ["Piloto 1", "Piloto 2"] + + +def test_indice_ausente_recupera_backup_valido(data_dir): + slot = P.create_profile_slot() + assert slot is not None + path = P.profiles_index_path() + registry = {"version": P.PROFILE_INDEX_VERSION, "active": slot.id, "slots": ["principal", slot.id]} + path.with_name(path.name + ".bak").write_text(json.dumps(registry), encoding="utf-8") + path.unlink() + + recovered, notice = P._registry_with_notice() + + assert recovered["active"] == slot.id + assert slot.id in recovered["slots"] + assert notice and path.is_file() + + +def test_indice_corrompido_com_falha_de_restauro_mantem_slots_em_memoria(data_dir, monkeypatch): + slot = P.create_profile_slot() + assert slot is not None + path = P.profiles_index_path() + registry = {"version": P.PROFILE_INDEX_VERSION, "active": slot.id, "slots": ["principal", slot.id]} + path.with_name(path.name + ".bak").write_text(json.dumps(registry), encoding="utf-8") + path.write_text("{corrompido", encoding="utf-8") + monkeypatch.setattr(P, "_atomic_write", lambda _path, _raw: False) + + recovered, notice = P._registry_with_notice() + + assert slot.id in recovered["slots"] + assert recovered["active"] == slot.id + assert notice and "na memória" in notice + + +def test_indice_e_backups_perdidos_preservam_slots_orfaos_sem_ativar(data_dir): + slot = P.create_profile_slot() + assert slot is not None + path = P.profiles_index_path() + path.unlink() + + recovered, notice = P._registry_with_notice() + + assert recovered["active"] == P.DEFAULT_PROFILE_SLOT + assert slot.id in recovered["slots"] + assert notice and "sem a lista principal" in notice + assert not path.exists() + + +def test_json_parcial_dos_novos_campos_nao_converte_valores_invalidos(): + profile = P.Profile.from_dict( + { + "opcoes": { + "modo_exploracao": "false", + "limite_voo_s": True, + "assistencia_previsivel": 1, + "semente_desafio": -1, + } + } + ) + + assert profile.opcoes.modo_exploracao is False + assert profile.opcoes.limite_voo_s == 0 + assert profile.opcoes.assistencia_previsivel is False + assert profile.opcoes.semente_desafio == 0 + + +def test_temporario_incompleto_nao_substitui_perfil_valido(data_dir): + assert P.save_profile(_profile(19)) + P.profile_path().with_name(P.profile_path().name + ".part.tmp").write_bytes(b"{") + + profile, notice = P.load_profile_with_notice() + + assert profile.pontos == 19 + assert notice is None + + +def test_preview_perfil_corrompido_nao_recupera_nem_escreve(data_dir): + path = P.profile_path() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"{quebrado") + + assert P.peek_profile(P.DEFAULT_PROFILE_SLOT) is None + assert path.read_bytes() == b"{quebrado" + assert not list(data_dir.glob("*.corrompido*.json")) + + +def test_falha_ao_salvar_cancela_troca_de_perfil(app, monkeypatch): + slot = P.create_profile_slot() + assert slot is not None + original = app.profile + monkeypatch.setattr(app, "writer", lambda _profile: False) + + assert app.select_profile(slot.id) is False + assert app.profile is original + assert app.profile_slot == P.DEFAULT_PROFILE_SLOT + assert "troca foi cancelada" in app.storage_notice + + +def test_registry_scene_e_fabrica_de_cena(app): + scene = app.create_scene("perfis") + scene.build() + + assert scene.__class__.__name__ == "ProfilesScene" + assert any(button.key.startswith("perfil-") for button in scene.menu.buttons) + + scene.error = "Não foi possível salvar o piloto. A troca foi cancelada." + scene.draw(app.canvas) + scene._select(app.profile_slot) + assert app.next_scene.__class__.__name__ == "VillageScene" + + +def test_profile_switch_clears_same_segment_calibration_and_stale_controls(app, monkeypatch): + target = P.Profile() + target.controle = "tronco_pe" + slot = P.create_profile_slot() + assert slot is not None + assert P.save_profile(target, slot.id) + + source = FakeSource() + body = BodyControl(source, SEGMENTS["tronco_pe"]) + body.mapper.base = (0.28, 0.37) + body.mapper.ax, body.mapper.ay = 0.6, -0.4 + app.input.body = body + app.input.segment_key = "tronco_pe" + app.profile.controle = "tronco_pe" + app.input.pressed.add(pygame.K_LEFT) + app.input.mouse_pos = (400, 300) + monkeypatch.setattr(app, "apply_options", lambda: None) + + assert app.select_profile(slot.id) + + assert body.mapper.base is None + assert body.mapper.axes() == (0.0, 0.0) + assert not app.input.pressed + assert app.input.mouse_pos is None + + +def test_fullscreen_option_is_synced_when_profile_changes(app, monkeypatch): + calls = [] + monkeypatch.setattr(pygame.display, "get_surface", lambda: type("Display", (), {"get_flags": lambda self: 0})()) + monkeypatch.setattr(app, "toggle_fullscreen", lambda: calls.append(True)) + app.profile.opcoes.tela_cheia = True + + app._sync_fullscreen() + + assert calls == [True] + + +def test_scene_factory_is_used_by_goto_and_map_start(app): + from dobramundo.scenes import make_scene + + called = [] + + def factory(core, name, *args, **kwargs): + called.append(name) + return make_scene(core, name, *args, **kwargs) + + app.scene_factory = factory + app.create_scene("perfis").goto("vila") + app.profile.tutorial_visto = True + app.create_scene("mapa").start("amazonia") + + assert called == ["perfis", "vila", "mapa", "voo"] diff --git a/tests/test_sprint3_art.py b/tests/test_pilot_story_village.py similarity index 97% rename from tests/test_sprint3_art.py rename to tests/test_pilot_story_village.py index 3fe0d25..893ff11 100644 --- a/tests/test_sprint3_art.py +++ b/tests/test_pilot_story_village.py @@ -73,9 +73,7 @@ def test_story_uses_four_separate_backgrounds_and_draws_reduced_motion(app): for start in (0.0, PAGES[0], sum(PAGES[:2]), sum(PAGES[:3])): scene.time = start + 0.2 scene.draw(app.canvas) - assert set(scene.story_backgrounds) == { - "story_city", "story_newspaper", "story_fold", "story_launch" - } + assert set(scene.story_backgrounds) == {"story_city", "story_newspaper", "story_fold", "story_launch"} assert all(surface is not None for surface in scene.story_backgrounds.values()) app.options.reduzir_movimento = True scene.time = sum(PAGES[:2]) + 0.2 diff --git a/tests/test_progress.py b/tests/test_progress.py index d26d742..dd1146b 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -42,6 +42,19 @@ def test_catalogo_de_melhorias_coerente(): assert all(len(p.level_costs) == 2 for p in PLANE_PARTS) +def test_primeiras_obras_têm_custos_de_entrada_e_compra_nunca_deixa_saldo_negativo(): + costs = {upgrade.key: upgrade.cost for upgrade in VILLAGE_UPGRADES} + assert costs["ponto_troca"] == {"papel": 8, "plastico": 8} + assert costs["horta"] == {"papel": 24, "vidro": 16} + wallet = {"papel": 8, "plastico": 8, "vidro": 16} + for key in ("ponto_troca", "horta"): + cost = costs[key] + if can_afford(wallet, cost): + for resource, amount in cost.items(): + wallet[resource] -= amount + assert all(amount >= 0 for amount in wallet.values()) + + def test_perfil_ida_e_volta(data_dir): profile = Profile() profile.recursos["metal"] = 7 diff --git a/tests/test_renderer_contracts.py b/tests/test_renderer_contracts.py new file mode 100644 index 0000000..04ce84e --- /dev/null +++ b/tests/test_renderer_contracts.py @@ -0,0 +1,60 @@ +"""O desenho aceita dados de leitura sem importar regras de voo.""" + +import os +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pygame + +from dobramundo.content.biomes import BIOMES +from dobramundo.engine.assets import Assets +from dobramundo.engine.world_view import WorldView + + +def test_renderer_import_does_not_import_game_rules(): + result = subprocess.run( + [ + sys.executable, + "-c", + "import sys; import dobramundo.engine.world_view; " + "assert not any(k.startswith('dobramundo.game.') for k in sys.modules)", + ], + env=dict(os.environ, PYGAME_HIDE_SUPPORT_PROMPT="1"), + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr + + +def test_entity_bounds_come_from_read_contract(monkeypatch): + pygame.init() + pygame.display.set_mode((8, 8)) + view = WorldView(Assets()) + view.show_hitboxes = True + monkeypatch.setattr(view.watercolor, "load", lambda key: True) + monkeypatch.setattr(view.paper_items, "draw", lambda *args: None) + bounds = SimpleNamespace(x_min=-10, x_max=10, y_min=20, y_max=40, z_min=200, z_max=220) + observed = [] + entity = SimpleNamespace(hitbox=lambda: observed.append(bounds) or bounds) + view.draw_entity(pygame.Surface((100, 100)), SimpleNamespace(biome=BIOMES["amazonia"]), entity) + assert observed == [bounds] + + +def test_switch_biome_releases_previous_backgrounds(): + pygame.init() + pygame.display.set_mode((8, 8)) + view = WorldView(Assets()) + view.set_biome(BIOMES["amazonia"]) + sky_only = {decor.sprite for decor in BIOMES["amazonia"].sky_decor} + sky_only.add(BIOMES["amazonia"].horizon_vehicle[0]) + assert sky_only & {Path(path).stem for path in view.assets._loaded} + view.watercolor.load("amazonia") + assert "amazonia" in view.watercolor.backdrops + view.set_biome(BIOMES["caatinga"]) + assert "amazonia" not in view.watercolor.backdrops + assert view.biome is BIOMES["caatinga"] + previous_only = sky_only - {decor.sprite for decor in BIOMES["caatinga"].sky_decor} + previous_only.discard(BIOMES["caatinga"].horizon_vehicle[0]) + assert not previous_only & {Path(path).stem for path in view.assets._loaded} diff --git a/tests/test_route_safety.py b/tests/test_route_safety.py index 3ece4fd..892d35d 100644 --- a/tests/test_route_safety.py +++ b/tests/test_route_safety.py @@ -26,7 +26,7 @@ def test_reference_route_avoids_an_obstacle_and_checks_full_collision_volume(): route = find_reachable_route([entity], "dificil") assert route - assert all(abs(x - entity.x) > obstacle.width / 2 + 130 * .42 * .88 for x, _y in route) + assert all(abs(x - entity.x) > obstacle.width / 2 + 130 * 0.42 * 0.88 for x, _y in route) def test_route_model_rejects_a_wall_covering_all_lanes_and_altitudes(): @@ -119,4 +119,3 @@ def test_planner_uses_worst_case_speed_for_each_difficulty(): difficult = RoutePlanner("dificil") assert normal.speed == difficult.speed * C.NORMAL_SPEED_FACTOR - diff --git a/tests/test_sprint3_render_review.py b/tests/test_route_visuals.py similarity index 98% rename from tests/test_sprint3_render_review.py rename to tests/test_route_visuals.py index 3c13b2b..20d9a48 100644 --- a/tests/test_sprint3_render_review.py +++ b/tests/test_route_visuals.py @@ -41,6 +41,7 @@ def test_route_stage_blend_is_continuous_and_reaches_horizon_first(): def test_scenery_geometry_is_identical_across_stages_and_loops_by_world_period(display, distance): route = WatercolorWorld(Assets()).route stages = [route.placements(distance, stage) for stage in range(3)] + def geometry(placements): return [(z, x, side) for z, x, _, side in placements] @@ -80,8 +81,7 @@ def test_zoom_keeps_plane_and_world_anchors_inside_frame_at_reachable_edges(): point = (center[0] + 40, center[1] + 30) transformed = screen_point(point, rect) assert transformed == pytest.approx( - ((point[0] - rect.x) * C.WIDTH / rect.width, - (point[1] - rect.y) * C.HEIGHT / rect.height) + ((point[0] - rect.x) * C.WIDTH / rect.width, (point[1] - rect.y) * C.HEIGHT / rect.height) ) diff --git a/tests/test_runtime_resources.py b/tests/test_runtime_resources.py index be69581..a54bbb0 100644 --- a/tests/test_runtime_resources.py +++ b/tests/test_runtime_resources.py @@ -2,13 +2,19 @@ from __future__ import annotations +from pathlib import Path + import pygame import pytest +from dobramundo import config as C from dobramundo import core -from dobramundo.engine.assets import Assets, load_image +from dobramundo.content.biomes import BIOMES +from dobramundo.engine.assets import SCENERY_FOLDERS, Assets, load_image +from dobramundo.engine.cache import BoundedCache from dobramundo.engine.painted_pilot import PaintedPilot from dobramundo.engine.watercolor import WatercolorWorld +from dobramundo.engine.world_view import WorldView from dobramundo.scenes.base import Scene @@ -16,10 +22,10 @@ def test_pilot_loads_its_layers_without_decoding_other_scenes(display): assets = Assets() painter = PaintedPilot(assets) assert painter.available - loaded = {path.replace("\\", "/").rsplit("/", 1)[-1] for path in assets._loaded} - assert loaded == {"pilot_base.png", "pilot_hair_front.png", "pilot_hair_back.png", "pilot_mobility.png"} - source_cache = next(iter(assets._folders.values())) - assert "front_standing" not in source_cache # pose derivada não contamina a biblioteca + assert not assets._loaded # atlas descartados depois de recortar poses e camadas + assert not any("pilot_" in str(path) for path in assets._loaded) + assert not {"pilot_base", "pilot_hair_front", "pilot_hair_back", "pilot_mobility"} & set(painter.sprites) + assert not any("front_standing" in source_cache for source_cache in assets._folders.values()) @pytest.mark.parametrize("hole", [False, True]) @@ -67,3 +73,123 @@ def test_warmup_does_not_start_after_expensive_frame(app, monkeypatch): monkeypatch.setattr(app.view, "step_warm_up", budgets.append) app.advance(1 / 60, []) assert budgets == [0.0] + + +def test_bounded_cache_respects_decoded_pixel_budget_and_dict_mutators(display): + cache = BoundedCache(10, byte_limit=512) + surfaces = [pygame.Surface((8, 8)) for _ in range(4)] + cache.update({"a": surfaces[0], "b": surfaces[1]}) + assert cache.bytes == 512 + cache.setdefault("c", surfaces[2]) + assert cache.bytes == 512 and "a" not in cache + cache.popitem() + assert cache.bytes == 512 - surfaces[2].get_pitch() * surfaces[2].get_height() + cache |= {"too-large": pygame.Surface((40, 40))} + assert "too-large" not in cache + cache.clear() + assert not cache and cache.bytes == 0 + with pytest.raises(TypeError): + cache.pop("missing", None, None) + + +def test_assets_release_folder_drops_decoded_reference_and_reload_is_clean(display, tmp_path, monkeypatch): + source_dir = tmp_path / "override-assets" + source_dir.mkdir() + image = pygame.Surface((24, 18), pygame.SRCALPHA) + image.fill((20, 60, 100, 255)) + pygame.image.save(image, str(source_dir / "fixture.png")) + monkeypatch.setattr("dobramundo.engine.assets.asset_dir_candidates", lambda name: [source_dir]) + assets = Assets() + first = assets.sprite("watercolor", "fixture") + assert first is not None and assets.cache_stats()["loaded_images"] == 1 + assert assets.release_folder("watercolor", ("fixture",)) == 1 + assert assets.cache_stats()["loaded_images"] == 0 + second = assets.sprite("watercolor", "fixture") + assert second is not None and second.get_size() == image.get_size() + + +def test_world_view_defers_scenery_and_releases_active_biome_cache(display): + assets = Assets() + view = WorldView(assets) + assert assets._scenery is None + assert not any(Path(path).parent.name in SCENERY_FOLDERS for path in assets._loaded) + + view.set_biome(BIOMES["amazonia"]) + view.ensure_scenery() + active_count = sum(Path(path).parent.name in SCENERY_FOLDERS for path in assets._loaded) + assert active_count > 0 + view.release_biome_cache("amazonia") + assert view.biome is None and not view.scenery + assert sum(Path(path).parent.name in SCENERY_FOLDERS for path in assets._loaded) < active_count + + +def test_prepared_backdrop_raster_matches_original_runtime_scale(display): + assets = Assets() + prepared = assets.sprite("watercolor_prepared", "amazonia_0") + source = assets.sprite("watercolor", "amazonia_0") + assert prepared is not None and source is not None + expected = pygame.transform.smoothscale(source, (C.WIDTH + 32, C.HEIGHT)) + assert pygame.image.tobytes(prepared, "RGB") == pygame.image.tobytes(expected, "RGB") + + +def test_prepared_backdrop_release_removes_only_source_cache_entries(display): + painter = WatercolorWorld(Assets()) + layers = painter.load("amazonia") + assert len(layers) == 3 and all(layer.get_size() == (C.WIDTH + 32, C.HEIGHT) for layer in layers) + assert not any("amazonia_0" in key for key in painter.assets._loaded) + + +def test_prepared_plane_atlas_is_used_and_original_fallback_remains(display, monkeypatch): + from dobramundo.content.planes import PLANE_KEYS + from dobramundo.engine.painted_planes import PaintedPlanes + + source = pygame.Surface((100, 100), pygame.SRCALPHA) + pygame.draw.polygon( + source, + (70, 100, 130, 255), + [(45, 2), (35, 25), (40, 27), (35, 48), (65, 48), (60, 27), (65, 25)], + ) + prepared = source.copy() + + class FakeAssets: + def __init__(self, prepared_available): + self.prepared_available = prepared_available + self.lookups = [] + + def sprite(self, folder, name): + self.lookups.append((folder, name)) + if folder == "watercolor_prepared" and self.prepared_available: + return prepared + if folder == "watercolor": + return source + return None + + for prepared_available, expected_folder in ((True, "watercolor_prepared"), (False, "watercolor")): + assets = FakeAssets(prepared_available) + atlas = PaintedPlanes(assets)._atlas(PLANE_KEYS[0], "flight") + assert atlas is not None + assert (expected_folder, "planes_flight_a_clean") in assets.lookups + + +def test_prepared_aircraft_atlases_are_recorded_with_runtime_dimensions(): + from dobramundo.engine.assets import Assets + + assets = Assets() + image = assets.sprite("watercolor_prepared", "planes_flight_a_clean") + assert image is not None and image.get_size() == (768, 512) + + +def test_theme_tags_bias_only_existing_stage_scenery(): + from types import SimpleNamespace + + from dobramundo.game.challenges import ChallengeTheme + + specs = [("AM_Samauma", 420.0), ("CA_Aerogerador", 360.0), ("CA_Mangueira", 250.0)] + tree_theme = SimpleNamespace(challenge_theme=ChallengeTheme("trees", "Árvores", "low", ("trees",))) + combined_theme = SimpleNamespace(challenge_theme=ChallengeTheme("wind", "Energia", "tower", ("trees", "wind"))) + green = WorldView.theme_specs(tree_theme, specs, "green") + solar = WorldView.theme_specs(combined_theme, specs, "solar") + assert green.count(specs[0]) > specs.count(specs[0]) + assert solar.count(specs[0]) > specs.count(specs[0]) + assert solar.count(specs[1]) > specs.count(specs[1]) + assert solar.count(specs[2]) == specs.count(specs[2]) diff --git a/tests/test_session_experience.py b/tests/test_session_experience.py new file mode 100644 index 0000000..4c8979d --- /dev/null +++ b/tests/test_session_experience.py @@ -0,0 +1,254 @@ +from __future__ import annotations + +import random + +from dobramundo.content.biomes import BIOMES +from dobramundo.game.entities import Entity, entity_hitbox +from dobramundo.game.missions import MissionTracker +from dobramundo.game.run import FlightRun +from dobramundo.scenes.flight import FlightScene +from dobramundo.scenes.preparation import PreparationScene +from tools.balance import simulate + + +def make_run(**kwargs) -> FlightRun: + return FlightRun(BIOMES["amazonia"], "normal", intro=False, focus=False, **kwargs) + + +def test_explicit_seed_reproduces_route_and_mission_sequence(): + first = make_run(seed=31821) + second = make_run(seed=31821) + + def signature(run): + return [(entity.z, entity.x, entity.kind, entity.sprite) for entity in run.world.entities] + + assert signature(first) == signature(second) + assert first.seed == second.seed == 31821 + + +def test_community_seed_names_region_and_biases_without_removing_other_obstacles(): + seed = 20261025 + amazon = make_run(seed=seed, community_challenge=True) + caatinga = FlightRun(BIOMES["caatinga"], "normal", seed=seed, intro=False, focus=False, community_challenge=True) + assert amazon.world.challenge_theme.key == "encontro_das_aguas" + assert caatinga.world.challenge_theme.key == "pomares_do_sao_francisco" + assert amazon.world.challenge_theme.decorations == ("river", "boat") + preferred = amazon.world.challenge_theme.preferred_obstacle + assert amazon.world.choose_obstacle_kind(0.1) == preferred + assert amazon.world.choose_obstacle_kind(0.99) != preferred + assert make_run(seed=seed).world.challenge_theme is None + + +def test_entity_hitbox_method_matches_the_physics_helper(): + entity = Entity(500.0, -1, "waste", 36.0, "papel") + assert entity.hitbox() == entity_hitbox(entity) + + +def test_seed_is_recorded_when_rng_is_injected_without_changing_rng_sequence(): + left_rng = random.Random(441) + right_rng = random.Random(441) + left = FlightRun(BIOMES["amazonia"], "normal", rng=left_rng, intro=False, focus=False) + right = FlightRun(BIOMES["amazonia"], "normal", rng=right_rng, intro=False, focus=False) + assert left.seed == right.seed + assert [(e.z, e.x, e.kind) for e in left.world.entities] == [(e.z, e.x, e.kind) for e in right.world.entities] + replay = make_run(seed=left.seed) + assert [(e.z, e.x, e.kind) for e in left.world.entities] == [(e.z, e.x, e.kind) for e in replay.world.entities] + + +def test_short_session_ends_as_partial_result_not_elimination(): + run = make_run(seed=9, session_limit_s=120, exploration=True) + run.invincible = True + # Reduz o relógio só para o teste exercitar a borda sem simular dois minutos. + run.session_limit_s = 1 + for _ in range(24): + run.update(0.05) + if run.finished: + break + assert run.finished and run.timeout + assert run.interrupted and not run.complete and not run.game_over + assert run.flight_time == 1.0 + assert run.summary()["tempo_esgotado"] == 1 + + +def test_exploration_rearms_after_last_heart_and_keeps_counting_errors(): + run = make_run(seed=15, exploration=True) + run.lives = 1 + run.take_hit() + assert run.hits == 1 + assert run.lives == run.max_lives + assert not run.finished and not run.game_over + assert ("exploration_continue", 1) in run.events + + +def test_collection_counter_does_not_count_mission_reward_resources(): + run = make_run(seed=73) + waste = Entity(500.0, 0, "waste", 36.0, "papel") + run.collect_waste(waste) + assert run.waste_collected == 1 + assert run.resources["papel"] == 4 + assert run.summary()["coletas"] == 1 + + +def test_predictable_assistance_is_fixed_at_takeoff_and_visible_in_summary(): + regular = make_run(seed=18) + assisted = make_run(seed=18, predictable_assistance=True) + assert regular.max_lives == 3 + assert assisted.max_lives == 5 + assisted.take_hit() + assert assisted.lives == 4 + assert assisted.invulnerable_timer == 2.0 + assert assisted.summary()["assistencia_previsivel"] == 1 + + +def test_first_objective_waits_until_opening_lessons_end_and_uses_available_targets(): + missions = MissionTracker("normal", random.Random(4), intro=True) + missions.update(22.0, {"coletar": {"papel": 2}, "desviar": 0, "portal": 0, "powerup": 0}) + assert missions.current is None + missions.update(0.49, {"coletar": {"papel": 2}, "desviar": 0, "portal": 0, "powerup": 0}) + assert missions.current is None + missions.update(0.02, {"coletar": {"papel": 1}, "desviar": 0, "portal": 0, "powerup": 0}) + assert missions.current is not None + assert missions.current.kind == "coletar" + assert missions.current.waste == "papel" + assert missions.current.target == 1 + + +def test_tracker_waits_instead_of_offering_an_objective_with_no_supply(): + missions = MissionTracker("normal", random.Random(2)) + missions.wait = 0.0 + missions.update(0.01, {"coletar": {}, "desviar": 0, "portal": 0, "powerup": 0}) + assert missions.current is None + missions.update(0.5, {"coletar": {}, "desviar": 0, "portal": 1, "powerup": 0}) + assert missions.current is not None + assert missions.current.kind == "portal" + assert missions.current.target == 1 + + +def test_unfinished_mission_expires_without_reward_then_reoffers_from_supply(): + missions = MissionTracker("normal", random.Random(7)) + missions.current = MissionTracker("normal", random.Random(9)).pick() + missions.progress = 1 + assert missions.current is not None + assert not missions.update(59.9) + assert missions.current is not None + assert missions.update(0.1) + assert missions.current is None + assert missions.progress == 0 and missions.completed == 0 and missions.expired == 1 + supply = {"coletar": {"metal": 1}, "desviar": 0, "portal": 0, "powerup": 0} + assert not missions.update(2.49, supply) + assert missions.current is None + assert not missions.update(0.02, supply) + assert missions.current is not None + assert missions.current.target == 1 + + +def test_community_objective_can_prioritize_needed_build_material_without_forcing_it(): + missions = MissionTracker("normal", random.Random(3), preferred_waste="metal") + offered = { + "coletar": {"metal": 2, "papel": 2}, + "desviar": 3, + "portal": 1, + "powerup": 1, + } + seen = [missions.pick(offered) for _ in range(40)] + assert any(mission.kind == "coletar" and mission.waste == "metal" for mission in seen) + assert any(mission.kind != "coletar" or mission.waste != "metal" for mission in seen) + + +def test_preparation_exposes_sessions_exploration_assistance_and_community_seed(app): + scene = PreparationScene(app) + scene.build() + assert any(button.key == "meu_voo" for button in scene.menu.buttons) + scene.open_my_flight() + keys = {button.key for button in scene.menu.buttons} + assert {"duracao_voo", "exploracao", "assistencia", "desafio_comunitario"} <= keys + for button in scene.menu.buttons: + assert 0 <= button.rect.left < button.rect.right <= 1100 + assert 0 <= button.rect.top < button.rect.bottom <= 675 + for index, button in enumerate(scene.menu.buttons): + for other in scene.menu.buttons[index + 1 :]: + assert not button.rect.colliderect(other.rect) + explore = next(button for button in scene.menu.buttons if button.key == "exploracao") + scene.menu.activate(explore) + assert app.options.modo_exploracao is True + assert any(button.key == "exploracao" and button.selected for button in scene.menu.buttons) + next(button for button in scene.menu.buttons if button.key == "duracao_voo").action() + next(button for button in scene.menu.buttons if button.key == "assistencia").action() + next(button for button in scene.menu.buttons if button.key == "desafio_comunitario").action() + assert app.options.limite_voo_s == 120 + assert app.options.assistencia_previsivel is True + assert app.options.semente_desafio == 20261025 + + +def test_flight_scene_uses_selected_seed_and_replay_preserves_intro_and_preset(app): + app.profile.modo = "dificil" + app.profile.voos_fase["amazonia"] = 1 + app.options.limite_voo_s = 180 + app.options.modo_exploracao = True + app.options.assistencia_previsivel = True + app.options.semente_desafio = 20261025 + app.profile.recursos["papel"] = 0 + app.profile.recursos["plastico"] = 99 + scene = FlightScene(app, "amazonia") + run = scene.run + assert run.seed == 20261025 + assert run.session_limit_s == 180 + assert run.exploration and run.predictable_assistance + assert run.community_challenge and run.world.challenge_theme.key == "encontro_das_aguas" + assert run.mission_preferred_waste == "papel" + app.profile.recursos["papel"] = 99 + app.profile.recursos["plastico"] = 0 + replay = FlightScene( + app, + "amazonia", + seed=run.seed, + mode=run.mode, + session_limit_s=run.session_limit_s, + exploration=run.exploration, + predictable_assistance=run.predictable_assistance, + intro_override=run.intro, + community_challenge=run.community_challenge, + mission_preferred_waste=run.mission_preferred_waste, + mission_preference_fixed=True, + ) + assert replay.run.seed == run.seed + assert replay.run.intro == run.intro is False + assert replay.run.world.challenge_theme.key == run.world.challenge_theme.key + assert replay.run.mission_preferred_waste == run.mission_preferred_waste == "papel" + assert [(entity.z, entity.x, entity.kind, entity.sprite) for entity in replay.run.world.entities] == [ + (entity.z, entity.x, entity.kind, entity.sprite) for entity in run.world.entities + ] + + +def test_balance_agent_uses_motion_and_returns_partial_interruption_metrics(): + record = simulate( + "normal", + 1.0, + 42, + error_rate=0.0, + interrupt_after=5.0, + reaction_s=0.35, + latency_s=0.1, + ) + assert record["seed"] == 42 + assert 5.0 <= record["seconds_active"] <= 5.05 + assert record["interrupted"] and not record["completed"] + assert record["max_player_displacement"] > 0.0 + assert "hits" in record and "resources" in record and "pause_seconds" in record + + +def test_balance_pause_is_wall_time_not_flight_time(): + record = simulate( + "normal", + 0.0, + 2026, + pause_per_minute=2.0, + interrupt_after=61.0, + exploration=True, + assistance=True, + ) + assert record["pause_count"] == 1 + assert record["pause_seconds"] == 2.0 + assert 61.0 <= record["seconds_active"] <= 61.05 + assert 2.0 <= record["seconds_wall"] - record["seconds_active"] <= 2.1 + assert record["interrupted"] diff --git a/tests/test_six_control_routes.py b/tests/test_six_control_routes.py new file mode 100644 index 0000000..a8f4417 --- /dev/null +++ b/tests/test_six_control_routes.py @@ -0,0 +1,41 @@ +"""O mesmo espaço navegável pelos seis segmentos, com landmarks sintéticos.""" + +import pytest +from helpers import CAL_READINGS, FakeSource, landmarks + +from dobramundo import config as C +from dobramundo.engine.orientation import game_to_screen, screen_to_game +from dobramundo.input.api import SEGMENTS, InputHub + + +@pytest.mark.parametrize("segment_key", sorted(SEGMENTS)) +def test_all_body_segments_reach_every_menu_edge(segment_key): + source = FakeSource() + hub = InputHub() + hub.source_factory = lambda: source + hub.set_segment(segment_key) + segment = SEGMENTS[segment_key] + + def hold(x, y): + for _ in range(CAL_READINGS): + source.show(landmarks({index: (x, y) for index in segment.landmarks})) + hub.update(1 / 30) + + hold(0.5, 0.5) + assert hub.body.calibrated + for x, y, edge in ( + (0.8, 0.5, (C.WIDTH - 1, C.HEIGHT // 2)), + (0.2, 0.5, (0, C.HEIGHT // 2)), + (0.5, 0.2, (C.WIDTH // 2, 0)), + (0.5, 0.8, (C.WIDTH // 2, C.HEIGHT - 1)), + ): + hold(x, y) + assert hub.body_pointer() == edge + + +@pytest.mark.parametrize("rotation", [0, 90, 180, 270]) +@pytest.mark.parametrize("mirrored", [False, True]) +def test_projected_corners_and_center_keep_same_target(rotation, mirrored): + for point in ((0, 0), (0, 1), (1, 0), (1, 1), (0.5, 0.5)): + shown = game_to_screen(*point, rotation, mirrored) + assert screen_to_game(*shown, rotation, mirrored) == pytest.approx(point) diff --git a/tests/test_text_layout.py b/tests/test_text_layout.py new file mode 100644 index 0000000..d7fe748 --- /dev/null +++ b/tests/test_text_layout.py @@ -0,0 +1,34 @@ +"""Contratos de legibilidade dos textos compartilhados pelas cenas.""" + +import pytest + +from dobramundo.ui import theme as T + + +@pytest.mark.parametrize("width", [0, 4, 30, 80, 180, 600]) +def test_long_labels_stay_inside_their_card(display, width): + text = T.Text() + label, size = T.fit_text(text, "Recuperamos o progresso do último arquivo válido", width, bold=True) + assert 16 <= size <= 20 + assert text.font(size, True).size(label)[0] <= max(0, width) + + +def test_short_label_is_not_altered(display): + text = T.Text() + assert T.fit_text(text, "Voar", 200, size=24) == ("Voar", 24) + + +def test_public_input_import_does_not_load_camera(): + import subprocess + import sys + + subprocess.run( + [ + sys.executable, + "-c", + "import sys; import dobramundo.input; " + "assert 'pygame' not in sys.modules; assert 'mediapipe' not in sys.modules; " + "assert 'dobramundo.input.camera' not in sys.modules", + ], + check=True, + ) diff --git a/tests/test_tutorial_sprint2.py b/tests/test_tutorial_flow.py similarity index 100% rename from tests/test_tutorial_sprint2.py rename to tests/test_tutorial_flow.py diff --git a/tests/test_vila_aquarela.py b/tests/test_vila_aquarela.py index 59e4d37..fc3a14a 100644 --- a/tests/test_vila_aquarela.py +++ b/tests/test_vila_aquarela.py @@ -19,7 +19,7 @@ def _dwell(scene, key: str) -> None: def _assert_no_dwell_overlap(scene, keys: list[str]) -> None: buttons = [next(button for button in scene.menu.buttons if button.key == key) for key in keys] for i, first in enumerate(buttons): - for second in buttons[i + 1:]: + for second in buttons[i + 1 :]: assert not first.rect.inflate(60, 60).colliderect(second.rect.inflate(60, 60)) @@ -27,8 +27,10 @@ def test_vila_oferece_destinos_grandes_e_alvos_separados(app): scene = VillageScene(app) scene.build() _assert_no_dwell_overlap(scene, ["voar", "hangar", "piloto", "cuidar"]) - assert all(next(b for b in scene.menu.buttons if b.key == key).rect.size == (210, 86) - for key in ("voar", "hangar", "piloto", "cuidar")) + assert all( + next(b for b in scene.menu.buttons if b.key == key).rect.size == (210, 86) + for key in ("voar", "hangar", "piloto", "cuidar") + ) def test_compra_exige_confirmacao_e_nao_desconta_duas_vezes(app): @@ -46,8 +48,7 @@ def test_compra_exige_confirmacao_e_nao_desconta_duas_vezes(app): _dwell(scene, "confirmar") assert upgrade.key in app.profile.vila - assert all(app.profile.recursos[key] == before[key] - amount - for key, amount in upgrade.cost.items()) + assert all(app.profile.recursos[key] == before[key] - amount for key, amount in upgrade.cost.items()) after_purchase = dict(app.profile.recursos) # O antigo alvo de confirmação desaparece após a compra e não pode repetir o gasto. scene.menu.update(0.1, (380, 593), 0.1) diff --git a/tests/test_sprint2_vila.py b/tests/test_village_progression.py similarity index 100% rename from tests/test_sprint2_vila.py rename to tests/test_village_progression.py diff --git a/tools/README.md b/tools/README.md index c73efd1..a1c81d6 100644 --- a/tools/README.md +++ b/tools/README.md @@ -1,6 +1,6 @@ # Ferramentas de desenvolvimento e geração de assets -## Diagnóstico e validação da versão 1.5 +## Diagnóstico, estabilidade e capturas Execute a partir da raiz do repositório, sem builds/testes concorrentes para comparar tempos: @@ -9,9 +9,11 @@ python tools/benchmark_runtime.py --out build/benchmark --frames 600 --screensho python tools/benchmark_runtime.py --out build/benchmark-camera --camera --paced python tools/benchmark_camera.py --seconds 8 --output build/camera.json python tools/check_routes.py --seeds 1000 --out build/rotas.json +python tools/soak_runtime.py --out build/soak --cycles 30 --frames 1200 +python tools/capture_release.py --out build/capturas ``` -`benchmark_runtime` mede abertura, memória residente no Windows, primeiro quadro, aquecimento e custo por quadro em dois biomas com/sem alto contraste. Usa CPU/SDL dummy; `--camera` abre a webcam para medir concorrência de inferência, com comandos de voo sintéticos. A idade do snapshot mais recente após a apresentação é distinta da métrica **captura→quadro consumido** da calibração integrada. Ambas começam no retorno da leitura e excluem exposição/buffering do sensor e latência física do monitor. Componentes estão aninhados e não devem ser somados. +`benchmark_runtime` mede abertura, memória residente no Windows/Linux, primeiro quadro, aquecimento e custo por quadro em dois biomas com/sem alto contraste. Usa CPU/SDL dummy; `--camera` abre a webcam para medir concorrência de inferência, com comandos de voo sintéticos. A idade do snapshot mais recente após a apresentação é distinta da métrica **captura→quadro consumido** da calibração integrada. Ambas começam no retorno da leitura e excluem exposição/buffering do sensor e latência física do monitor. Componentes estão aninhados e não devem ser somados. `benchmark_camera` separa até 15 segundos de preparação da janela de amostragem; exige pelo menos cinco resultados publicados e encerramento confirmado. Falta de amostras ou erro retorna código 2. Essas ferramentas salvam métricas; apenas `--screenshots` grava imagens sintéticas do jogo, nunca da webcam ou dos pontos do corpo. @@ -19,6 +21,28 @@ python tools/check_routes.py --seeds 1000 --out build/rotas.json No benchmark, `--paced` cede CPU entre quadros para mirar 60 fps, excluindo esse sono dos tempos de processamento. Sem a opção, a execução é um teste de estresse sem limite de quadros. Registre a modalidade ao comparar resultados. +`soak_runtime` alterna cenas, biomas e contraste durante um percurso sintético +prolongado. Registra RSS, superfícies retidas, entidades e tempos por ciclo. +Tempo simulado e tempo de parede ficam separados; invencibilidade serve somente +ao estresse de renderização. Economia é medida separadamente por `balance.py`. + +`capture_release` captura menus, perfis, estados de erro e voos com semente fixa. +Verifica os limites dos botões, mas a revisão das imagens continua necessária +para detectar cortes de texto, glifos ausentes e contraste insuficiente. + +## Build nativo automatizado + +Instale o conjunto desktop com Python 3.12 e execute `python tools/build_desktop.py`. +Os wrappers `build_windows.bat` e `build_linux.sh` preparam esse ambiente. O comando +gera `dist/Dobramundo`, testa 1.200 quadros por bioma e exige o detector de pose; +`--sem-camera` é uma variante explícita para teclado. Usa perfil temporário, +não apaga a pasta `dist/` inteira e não lê saves reais. O relatório sanitizado +fica em `build/desktop-selftest/self_test.json`. + +A CI testa Python 3.8/3.12 com arquivos de dependências específicos, publica +cobertura e gera executáveis nativos em Windows/Linux. Segue a estrutura de +[build/test de Python do GitHub](https://docs.github.com/en/actions/tutorials/build-and-test-code/python). + ## Geração de assets Os scripts desta pasta criam parte dos arquivos de `assets/` que o jogo carrega. O jogo não precisa das ferramentas para rodar: ele usa os PNG, OGG e JSON já gerados. Use-as para regenerar ou ajustar os assets indicados na tabela abaixo. @@ -65,7 +89,7 @@ make_grass_texture.py -----------> assets/ground/grass.png make_ground_textures.py ---------> assets/ground/dry_soil.png, agreste.png (importa make_grass_texture.py) measure_obstacles.py ------------> nada gravado: confere as colisões contra os sprites -balance.py ----------------------> nada gravado: simula voos e mede duração da fase e recursos +balance.py ----------------------> relatório opcional em JSON: voo, erros, pausas e recursos build_cartridge.py --------------> build/cartucho/ e dist/dobramundo-.ttea (monta o pacote do jogo; valida e gera com o tsdk) @@ -129,10 +153,32 @@ Os PNG de `assets/dieselpunk_sprites`, `scenario_sprites`, `skyline_sprites` e ` ## Equilíbrio (`balance.py`) -Simula voos com um piloto automático que pega uma fração dos resíduos (`--coleta 0.4` = 4 de cada 10), sem colisões, e mostra por modo a duração da fase, quando cada estágio começa e quantos recursos um voo rende, além de quantos voos bastam para comprar tudo. Rode depois de mexer em `dobramundo/config.py`, `dobramundo/content/progress.py` ou `dobramundo/game/missions.py`: +Simula comandos de um piloto automático com movimento limitado pela física real, colisões, atraso de reação e erros. `--coleta 0.4` é a probabilidade de **tentar** uma coleta; não garante alcançar o item. O relógio ativo para durante a pausa; o relatório registra separadamente tempo ativo, tempo total, coletas físicas, recursos com bônus, batidas, vidas e motivo do término. Rode depois de mexer em `dobramundo/config.py`, `dobramundo/content/progress.py` ou `dobramundo/game/missions.py`: ``` -python tools/balance.py --coleta 0.4 --voos 10 +python tools/balance.py --coleta 0.4 --erro 0.15 --pausa 10 --voos 10 --out build/balance.json +python tools/balance.py --exploracao --assistencia --limite 120 --voos 10 --out build/exploracao.json ``` O teste `test_fase_dura_alguns_minutos` (em `tests/test_gameplay.py`) trava a duração da fase entre 2,5 e 6 minutos. + +O agente sintético não representa uma criança nem mede conforto motor. Interprete os resultados como regressão de economia e interrupções, junto ao aceite presencial. + +## Preparação de imagens + +`python tools/prepare_assets.py` produz seis fundos na resolução de uso e sete atlas de aviões em `assets/watercolor_prepared/`. Mantém os originais e registra tamanho, SHA-256, vista, grade e pivô no manifesto. `python tools/audit_assets.py` confere o inventário. O runtime prefere os PNG preparados e conserva os originais como fallback; não há conversão de codec presumida compatível com o console. + +## Medições e entrega + +Execute benchmarks em processos novos e sem builds ou testes concorrentes. O padrão usa um piloto sintético personalizado; `--empty-pilot` reproduz a carga sem avatar da ferramenta 1.5. Os relatórios separam abertura, primeiros quadros, aquecimento, tempos de quadro e memória. Componentes aninhados não devem ser somados. + +```powershell +python tools/benchmark_runtime.py --out build/benchmark --frames 600 +python tools/benchmark_runtime.py --out build/benchmark-camera --frames 600 --camera --paced +python tools/soak_runtime.py --out build/soak --cycles 30 --frames 2400 +python tools/capture_release.py --out build/capturas +``` + +O benchmark com câmera mede processamento concorrente e a idade do último resultado disponível; não demonstra precisão dos gestos nem latência física de sensor/projetor. O soak alterna biomas, contraste, aparências e menus usando perfis sintéticos. Ele usa invencibilidade apenas para manter a carga de renderização; a economia é medida separadamente por `balance.py`, com colisões. + +`build_desktop.py` constrói o pacote nativo, invalida resultados antigos e roda o executável com `--self-test 1200 --exigir-camera` em diretório temporário. A CI gera Windows e Linux, publica cobertura e preserva a permissão de execução do Linux em `.tar.gz`. Linux requer `libegl1 libgles2` (Debian/Ubuntu); a CI verifica as dependências de `libmediapipe.so` com `ldd` antes de empacotar. O diagnóstico manual só de Linux não substitui a matriz completa de testes e builds. diff --git a/tools/audit_assets.py b/tools/audit_assets.py new file mode 100644 index 0000000..9f0c68d --- /dev/null +++ b/tools/audit_assets.py @@ -0,0 +1,71 @@ +"""Verify original asset hashes and prepared runtime images against the manifest.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path + +os.environ.setdefault("SDL_VIDEODRIVER", "dummy") +os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1") +ROOT = Path(__file__).resolve().parents[1] +ASSET_ROOT = ROOT / "assets" +MANIFEST = ASSET_ROOT / "watercolor_prepared" / "asset_catalog.json" + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def audit(manifest_path: Path = MANIFEST) -> list[str]: + import pygame + + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + errors = [] + provenance = manifest.get("provenance", {}) + for source_record in provenance.get("generation_metadata", []): + metadata = ASSET_ROOT / "watercolor" / source_record["file"] + if not metadata.is_file() or sha256(metadata) != source_record["sha256"]: + errors.append(f"metadado de geração ausente ou hash divergente: {source_record['file']}") + for record in manifest.get("assets", []): + source = ASSET_ROOT / "watercolor" / record["file"] + if not source.is_file() or sha256(source) != record["sha256"]: + errors.append(f"original ausente ou hash divergente: {record['file']}") + continue + source_image = pygame.image.load(str(source)) + if list(source_image.get_size()) != record["dimensions"]: + errors.append(f"dimensão original divergente: {record['file']}") + variant = record.get("runtime_variant") + if variant: + prepared = ASSET_ROOT / variant["file"] + if not prepared.is_file() or sha256(prepared) != variant.get("sha256"): + errors.append(f"variante ausente ou hash divergente: {variant['file']}") + continue + if list(pygame.image.load(str(prepared)).get_size()) != variant["dimensions"]: + errors.append(f"dimensão da variante divergente: {variant['file']}") + return errors + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--manifest", type=Path, default=MANIFEST) + args = parser.parse_args() + errors = audit(args.manifest) + if errors: + for error in errors: + print(f"ERROR: {error}") + return 1 + data = json.loads(args.manifest.read_text(encoding="utf-8")) + variants = sum("runtime_variant" in asset for asset in data.get("assets", [])) + print(f"OK: {len(data.get('assets', []))} originals and {variants} prepared variants verified") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/balance.py b/tools/balance.py index ae8b026..0a79536 100644 --- a/tools/balance.py +++ b/tools/balance.py @@ -1,74 +1,330 @@ -"""Simula voos para conferir o equilíbrio: duração da fase, coletas e recursos por voo. +"""Cenários sintéticos com controle dinâmico para comparar a economia do voo. -Um "piloto" automático pega cada resíduo que chega até o avião com probabilidade ---coleta (0,4 = a criança pega 4 de cada 10) e o voo é invencível, para medir só o -ritmo da transformação. Use depois de mexer em config.py ou content/progress.py. +O agente deste simulador usa comandos de posição, resposta real do Player, atraso +de entrada, decisões perdidas, colisões do jogo, pausas e interrupções. Não é uma +criança, teste de usabilidade nem previsão de conforto motor. Os resultados só +descrevem o modelo e devem ser conferidos em uso mediado. -Uso: python tools/balance.py [--coleta 0.4] [--voos 6] +Uso: python tools/balance.py --voos 10 --erro 0.2 --pausa 10 --interromper 120 --json """ from __future__ import annotations import argparse +import json import random import sys from pathlib import Path +from typing import Dict, Optional, Tuple ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from dobramundo import config as C # noqa: E402 from dobramundo.content.biomes import BIOMES # noqa: E402 +from dobramundo.content.items import WASTE_KEYS # noqa: E402 from dobramundo.content.progress import PLANE_PARTS, VILLAGE_UPGRADES # noqa: E402 from dobramundo.game.run import FlightRun # noqa: E402 +from dobramundo.game.world import find_reachable_route # noqa: E402 DT = 1.0 / 60.0 LIMIT_S = 1200.0 +ANTICIPATION_S = 3.0 -def simulate(mode: str, share: float, seed: int, biome: str = "amazonia"): - """Devolve (segundos até 100%, coletas, recursos, segundos por estágio).""" - rng = random.Random(seed) - # como no jogo: abertura didática sempre no Normal (no Difícil, só no primeiro voo da fase) - run = FlightRun(BIOMES[biome], mode, {}, rng=random.Random(seed), intro=mode == "normal") - run.invincible = True +def command_for(player, point: Tuple[float, float]) -> Tuple[float, float]: + """Converte um ponto do mundo em comando posicional (-1..1) para o Player real.""" + x, y = point + ax = max(-1.0, min(1.0, x / C.MAX_PLAYER_X)) + top = C.MAX_ALTITUDE - C.REST_ALTITUDE if y >= C.REST_ALTITUDE else C.REST_ALTITUDE - C.MIN_ALTITUDE + ay = (y - C.REST_ALTITUDE) / max(1.0, top) + return ax, max(-1.0, min(1.0, ay)) + + +def desired_command( + run: FlightRun, + rng: random.Random, + collect_share: float, + error_rate: float, + reaction_s: float, + latency_s: float, + counts: Dict[str, int], +) -> Tuple[float, float]: + """Controlador simples; decide por alvo e deixa a física/sensores do jogo resolver o movimento.""" + threats = [ + entity + for entity in run.world.entities + if entity.spec is not None + and not entity.hit + and not entity.passed + and not entity.dodged + and entity.z > C.PLAYER_Z + ] + if threats: + obstacle = min(threats, key=lambda entity: entity.z) + eta = (obstacle.z - C.PLAYER_Z) / max(1.0, run.speed) + if eta <= reaction_s + latency_s + ANTICIPATION_S: + if "balance_decided" not in vars(obstacle): + obstacle.balance_decided = True + if rng.random() < error_rate: + obstacle.balance_missed = True + counts["decisoes_perdidas"] += 1 + else: + route = find_reachable_route([obstacle], run.mode) + if route: + obstacle.balance_point = route[0] + else: + obstacle.balance_missed = True + counts["sem_rota_simplificada"] += 1 + point = vars(obstacle).get("balance_point") + if point is not None: + return command_for(run.player, point) + + for entity in run.world.entities: + point = vars(entity).get("balance_target") + if entity.kind == "waste" and point is not None and not entity.collected and entity.z > C.PLAYER_Z: + return command_for(run.player, point) + + horizon = run.speed * (reaction_s + latency_s + ANTICIPATION_S + 0.5) + wastes = sorted( + ( + entity + for entity in run.world.entities + if entity.kind == "waste" + and not entity.collected + and entity.z > C.PLAYER_Z + and entity.z <= C.PLAYER_Z + horizon + ), + key=lambda entity: entity.z, + ) + for waste in wastes: + if "balance_decided" in vars(waste): + continue + waste.balance_decided = True + if rng.random() > collect_share: + counts["nao_tentadas"] += 1 + continue + if rng.random() < error_rate: + counts["decisoes_perdidas"] += 1 + continue + waste.balance_target = (waste.x, min(C.MAX_ALTITUDE, max(C.MIN_ALTITUDE, waste.y))) + counts["alvos_de_coleta"] += 1 + return command_for(run.player, waste.balance_target) + return command_for(run.player, (0.0, C.REST_ALTITUDE)) + + +def simulate( + mode: str, + share: float, + seed: int, + biome: str = "amazonia", + error_rate: float = 0.0, + pause_per_minute: float = 0.0, + interrupt_after: float = 0.0, + session_limit_s: int = 0, + reaction_s: float = 0.35, + latency_s: float = 0.25, + exploration: bool = False, + assistance: bool = False, +) -> dict: + """Roda um cenário sintético com a dinâmica de posição e colisões reais do jogo.""" + rng = random.Random(seed ^ 0xB41A6CE) + run = FlightRun( + BIOMES[biome], + mode, + {}, + seed=seed, + intro=mode == "normal", + focus=False, + session_limit_s=session_limit_s, + exploration=exploration, + predictable_assistance=assistance, + ) stage_times = [] - t = 0.0 - while not run.complete and t < LIMIT_S: - for entity in run.world.entities: - # a decisão fica no próprio objeto: id() se repete quando objetos antigos são liberados - if entity.kind != "waste" or hasattr(entity, "decided") or entity.z > C.PLAYER_Z + 60: - continue - entity.decided = rng.random() < share - if entity.decided: - run.player.x, run.player.y = entity.x, min(C.MAX_ALTITUDE, entity.y) + counts = {"decisoes_perdidas": 0, "sem_rota_simplificada": 0, "nao_tentadas": 0, "alvos_de_coleta": 0} + wall_s = 0.0 + pause_left = 0.0 + next_pause = 60.0 if pause_per_minute else float("inf") + requested = (0.0, 0.0) + applied = requested + pending: Optional[Tuple[Tuple[float, float], float]] = None + max_displacement = 0.0 + while not run.finished and wall_s < LIMIT_S: + if interrupt_after > 0 and run.flight_time >= interrupt_after: + run.interrupted = not run.complete + run.finished = True + break + if pause_left > 0: + pause_left = max(0.0, pause_left - DT) + wall_s += DT + continue + if run.flight_time >= next_pause: + run.pause_count += 1 + pause_left = pause_per_minute + run.pause_duration_s += pause_per_minute + next_pause += 60.0 + continue + + target = desired_command(run, rng, share, error_rate, reaction_s, latency_s, counts) + if target != requested: + requested = target + pending = (target, run.flight_time + latency_s) + if pending is not None and run.flight_time >= pending[1]: + applied, pending = pending[0], None + stage = run.stage - run.update(DT) - t += DT + run.update(DT, target=applied) + max_displacement = max( + max_displacement, + (run.player.x * run.player.x + (run.player.y - C.START_ALTITUDE) ** 2) ** 0.5, + ) + wall_s += DT if run.stage != stage: - stage_times.append(t) - collected = sum(1 for n, _ in run.events if n == "collect") - return t, sum(run.resources.values()), stage_times, collected + stage_times.append(wall_s) + if run.complete: + run.finished = True + if not run.complete and not run.game_over and not run.interrupted and wall_s >= LIMIT_S: + run.interrupted = True + run.finished = True + return { + "biome": biome, + "mode": mode, + "seed": run.seed, + "seconds_active": round(run.flight_time, 3), + "seconds_wall": round(wall_s, 3), + "max_player_displacement": round(max_displacement, 3), + "stage_times_s": [round(value, 3) for value in stage_times], + "restoration": round(run.restoration, 2), + "resources": dict(run.resources), + "resource_total": sum(run.resources.values()), + "collected": run.waste_collected, + "hits": run.hits, + "max_lives": run.max_lives, + "lives_left": run.lives, + "completed": run.complete, + "game_over": run.game_over, + "interrupted": run.interrupted, + "session_timeout": run.timeout, + "pause_count": run.pause_count, + "pause_seconds": round(run.pause_duration_s, 3), + "controller_counts": counts, + "exploration": exploration, + "assistance": assistance, + } + + +def collection_costs() -> Dict[str, int]: + costs = {key: 0 for key in WASTE_KEYS} + for upgrade in VILLAGE_UPGRADES: + for key, amount in upgrade.cost.items(): + costs[key] += amount + for part in PLANE_PARTS: + for level in part.level_costs: + for key, amount in level.items(): + costs[key] += amount + return costs def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument("--coleta", type=float, default=0.4, help="fração dos resíduos que a criança pega") + parser.add_argument("--coleta", type=float, default=0.4, help="chance de tentar alinhar com cada resíduo") + parser.add_argument("--erro", type=float, default=0.1, help="decisões de movimento perdidas (0..1)") + parser.add_argument("--pausa", type=float, default=0.0, help="segundos de pausa após cada minuto ativo") + parser.add_argument( + "--interromper", type=float, default=0.0, help="interrompe após estes segundos ativos; 0 desativa" + ) + parser.add_argument( + "--limite", type=int, choices=C.SESSION_LIMITS_S, default=0, help="limite de sessão em segundos" + ) + parser.add_argument("--reacao", type=float, default=0.35, help="atraso sintético antes de iniciar a manobra") + parser.add_argument("--latencia", type=float, default=0.25, help="atraso sintético até aplicar o comando") + parser.add_argument("--exploracao", action="store_true", help="modo que não elimina após as vidas") + parser.add_argument("--assistencia", action="store_true", help="cinco vidas e 2 s de proteção após batida") parser.add_argument("--voos", type=int, default=10) + parser.add_argument("--seed-inicial", type=int, default=1) + parser.add_argument("--bioma", choices=tuple(BIOMES), default="amazonia") + parser.add_argument("--json", action="store_true", help="imprime o relatório em JSON") + parser.add_argument("--out", type=Path, help="grava o relatório JSON neste caminho") args = parser.parse_args() - village = sum(sum(u.cost.values()) for u in VILLAGE_UPGRADES) - parts = sum(sum(c.values()) for p in PLANE_PARTS for c in p.level_costs) - print(f"Custo total: vila {village}, peças {parts} (soma {village + parts})") - for mode in ("normal", "dificil"): - results = [simulate(mode, args.coleta, seed) for seed in range(args.voos)] - minutes = sum(r[0] for r in results) / len(results) / 60 - resources = sum(r[1] for r in results) / len(results) - stages = [sum(r[2][i] for r in results if len(r[2]) > i) / len(results) / 60 for i in range(2)] - print( - f"{mode:8s} coletando {args.coleta:.0%}: fase em {minutes:4.1f} min " - f"(estágio 2 aos {stages[0]:.1f} min, 3 aos {stages[1]:.1f} min), " - f"~{resources:.0f} recursos por voo -> tudo comprado em ~{(village + parts) / max(1, resources):.0f} voos" + if not 0 <= args.coleta <= 1 or not 0 <= args.erro <= 1: + parser.error("--coleta e --erro devem estar entre 0 e 1") + if args.voos <= 0 or min(args.pausa, args.interromper, args.reacao, args.latencia) < 0: + parser.error("--voos deve ser positivo; tempos não podem ser negativos") + + records = [ + simulate( + mode, + args.coleta, + args.seed_inicial + i, + biome=args.bioma, + error_rate=args.erro, + pause_per_minute=args.pausa, + interrupt_after=args.interromper, + session_limit_s=args.limite, + reaction_s=args.reacao, + latency_s=args.latencia, + exploration=args.exploracao, + assistance=args.assistencia, ) + for mode in ("normal", "dificil") + for i in range(args.voos) + ] + costs = collection_costs() + means = { + mode: { + key: sum(record["resources"][key] for record in records if record["mode"] == mode) / args.voos + for key in costs + } + for mode in ("normal", "dificil") + } + report = { + "model": "dynamic-position-agent-v1", + "limitations": [ + "synthetic controller, not a child or usability study", + "approach decisions use simplified one-obstacle route targets", + "results do not establish comfort, fairness, or physical reachability", + ], + "parameters": { + "biome": args.bioma, + "collect_attempt_probability": args.coleta, + "deliberate_decision_error_probability": args.erro, + "pause_seconds_per_active_minute": args.pausa, + "interrupt_after_active_seconds": args.interromper, + "session_limit_seconds": args.limite, + "reaction_seconds": args.reacao, + "input_latency_seconds": args.latencia, + "exploration": args.exploracao, + "assistance": args.assistencia, + "flight_count_per_mode": args.voos, + "seed_start": args.seed_inicial, + }, + "collection_costs": costs, + "mean_resources_by_mode": means, + "runs": records, + } + if args.out: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") + if args.json: + print(json.dumps(report, ensure_ascii=False, indent=2)) + else: + print("Cenário sintético com física e colisões reais do jogo; não é teste humano nem previsão de conforto.") + print("Custos de coleção por recurso: " + ", ".join(f"{key} {amount}" for key, amount in costs.items())) + for mode in ("normal", "dificil"): + subset = [record for record in records if record["mode"] == mode] + average_wall = sum(record["seconds_wall"] for record in subset) / len(subset) / 60 + completions = sum(record["completed"] for record in subset) + game_overs = sum(record["game_over"] for record in subset) + interruptions = sum(record["interrupted"] for record in subset) + hits = sum(record["hits"] for record in subset) / len(subset) + resource_text = ", ".join(f"{key} {means[mode][key]:.1f}" for key in costs) + print( + f"{mode}: duração parede média {average_wall:.1f} min; completou {completions}/{len(subset)}, " + f"game over {game_overs}, interrupções {interruptions}, batidas médias {hits:.1f}" + ) + print(f" média de recursos por voo: {resource_text}") + if args.out: + print(f"Relatório JSON: {args.out}") if __name__ == "__main__": diff --git a/tools/benchmark_camera.py b/tools/benchmark_camera.py index daa2157..dbe3652 100644 --- a/tools/benchmark_camera.py +++ b/tools/benchmark_camera.py @@ -74,11 +74,7 @@ def benchmark(seconds: float, device: int, model_path: Optional[Path]) -> dict: sample_complete = sample_seconds >= max(0.0, seconds - POLL_INTERVAL_S * 2) stopped = not source.running successful = ( - ready - and sample_complete - and deltas["published"] >= MIN_SAMPLES - and stopped - and metrics["error"] is None + ready and sample_complete and deltas["published"] >= MIN_SAMPLES and stopped and metrics["error"] is None ) resolution = metrics["resolution"] return { @@ -109,13 +105,9 @@ def benchmark(seconds: float, device: int, model_path: Optional[Path]) -> dict: "capture_interval_ms": round(metrics["capture_interval_ms"], 2), "inference_interval_ms": round(metrics["inference_interval_ms"], 2), "last_result_age_ms": ( - round(metrics["last_result_age_ms"], 2) - if metrics["last_result_age_ms"] is not None - else None - ), - "last_published_age_ms": ( - round(metrics["result_age_ms"], 2) if metrics["result_age_ms"] is not None else None + round(metrics["last_result_age_ms"], 2) if metrics["last_result_age_ms"] is not None else None ), + "last_published_age_ms": (round(metrics["result_age_ms"], 2) if metrics["result_age_ms"] is not None else None), "error_count": metrics["errors"], "error": metrics["error"], "thread_still_running_after_stop": not stopped, diff --git a/tools/benchmark_runtime.py b/tools/benchmark_runtime.py index 5b0ac4f..18bfde5 100644 --- a/tools/benchmark_runtime.py +++ b/tools/benchmark_runtime.py @@ -11,7 +11,6 @@ import json import os import platform -import random import statistics import sys import time @@ -23,6 +22,12 @@ def resident_bytes() -> int: if os.name != "nt": + try: + # Linux: páginas residentes, não o espaço virtual reservado. + pages = int(Path("/proc/self/statm").read_text(encoding="ascii").split()[1]) + return pages * os.sysconf("SC_PAGE_SIZE") + except (OSError, ValueError, IndexError, AttributeError): + pass return 0 # indisponível nesta medição; não significa consumo zero from ctypes import wintypes @@ -84,6 +89,7 @@ def main() -> int: "--camera", action="store_true", help="abre webcam local para medir CPU concorrente; sem salvar vídeo" ) parser.add_argument("--device", type=int, default=0) + parser.add_argument("--empty-pilot", action="store_true", help="reproduz a carga sem avatar do benchmark 1.5") args = parser.parse_args() if args.frames < 1: parser.error("--frames deve ser maior que zero") @@ -104,7 +110,12 @@ def main() -> int: memory_before = resident_bytes() start = time.perf_counter() - app = App(audio=False, profile=Profile(consentimento=True, piloto_montado=True)) + profile = Profile(consentimento=True, piloto_montado=True) + if not args.empty_pilot: + profile.piloto.update( + pele="pele4", cabelo="crespo", cor_cabelo="preto", roupa="amarela", olhos="castanhos", oculos="redondo" + ) + app = App(audio=False, profile=profile) init_ms = (time.perf_counter() - start) * 1000 memory_after = resident_bytes() watercolor = [(path, surf) for path, surf in app.assets._loaded.items() if "watercolor" in path] @@ -120,6 +131,8 @@ def main() -> int: "rss_delta_bytes": memory_after - memory_before, "startup_watercolor_count": len(watercolor), "startup_watercolor_bytes": sum(s.get_pitch() * s.get_height() for _, s in watercolor), + "seed": 7, + "pilot": "empty (1.5 comparison)" if args.empty_pilot else "customized synthetic avatar", "flights": {}, } camera = None @@ -150,7 +163,7 @@ def main() -> int: for contrast in (False, True): setup_started = time.perf_counter() scene = FlightScene(app, city) - scene.run = FlightRun(BIOMES[city], "normal", {}, rng=random.Random(7), intro=False) + scene.run = FlightRun(BIOMES[city], "normal", {}, seed=7, intro=False) scene.run.invincible = True app.go(scene) app.options.alto_contraste = contrast @@ -189,6 +202,7 @@ def main() -> int: "within_60fps_budget_fraction": round(sum(v <= 1000 / 60 for v in values) / len(values), 4), "components": {k: stats(v) for k, v in samples.items()}, "rss_bytes": resident_bytes(), + "renderer_caches": app.view.cache_stats(), } if camera is not None: report["flights"][label]["latest_camera_result_age_at_present"] = stats(camera_age) diff --git a/tools/build_cartridge.py b/tools/build_cartridge.py index 3053112..f678708 100644 --- a/tools/build_cartridge.py +++ b/tools/build_cartridge.py @@ -24,7 +24,8 @@ from dobramundo import __version__ # noqa: E402 from dobramundo.content import texts # noqa: E402 -STAGE = ROOT / "build" / "cartucho" +STAGE_ROOT = ROOT / "build" +STAGE = STAGE_ROOT / "cartucho" # Partes que só o executável usa (o console não deixa o cartucho abrir janela nem câmera). DESKTOP_ONLY = {"app.py", "main.py", "__main__.py", "selftest.py", "input/camera.py"} SKIP_ASSETS = {"pose_model"} @@ -88,6 +89,10 @@ def ignore_assets(folder: str, names): def stage() -> Path: + # A exclusão é limitada ao estágio conhecido, sem seguir junction/symlink. + expected = STAGE_ROOT / "cartucho" + if STAGE.resolve() != expected.absolute() or any(p.is_symlink() for p in (STAGE_ROOT, STAGE)): + raise RuntimeError("Pasta de estágio fora do workspace ou redirecionada") if STAGE.exists(): shutil.rmtree(STAGE) STAGE.mkdir(parents=True) diff --git a/tools/build_desktop.py b/tools/build_desktop.py new file mode 100644 index 0000000..d1d18aa --- /dev/null +++ b/tools/build_desktop.py @@ -0,0 +1,119 @@ +"""Build nativo com self-test isolado; não remove dist/, saves ou outras entregas. + +Instale requirements-webcam.txt + pyinstaller com constraints-build.txt antes. +O executável é gerado em dist/Dobramundo; Python 3.12 no sistema de destino. +""" + +from __future__ import annotations + +import argparse +import ctypes +import json +import os +import shutil +import subprocess +import sys +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def require_linux_egl_runtime(require_camera: bool) -> None: + """Confere as bibliotecas gráficas de sistema usadas pelo MediaPipe no Linux.""" + if not require_camera or not sys.platform.startswith("linux"): + return + requirements = ( + ("libEGL.so.1", "libegl1"), + ("libGLESv2.so.2", "libgles2"), + ) + for library, package in requirements: + try: + ctypes.CDLL(library) + except OSError as exc: + raise RuntimeError( + f"O detector MediaPipe no Linux requer {library}; instale o pacote de sistema {package} " + "(Debian/Ubuntu) antes do build e da execução." + ) from exc + + +def build(onefile: bool = False, require_camera: bool = True) -> Path: + reports = ROOT / "build" / "desktop-selftest" + reports.mkdir(parents=True, exist_ok=True) + run_id = uuid.uuid4().hex + (reports / "self_test.json").write_text( + json.dumps({"status": "building", "run_id": run_id}) + "\n", encoding="utf-8" + ) + require_linux_egl_runtime(require_camera) + env = dict(os.environ, DOBRA_ONEFILE="1" if onefile else "0") + subprocess.run( + [ + sys.executable, + "-m", + "PyInstaller", + "--noconfirm", + "--clean", + "--workpath", + str(ROOT / "build" / "pyinstaller"), + "--distpath", + str(ROOT / "dist"), + str(ROOT / "Dobramundo.spec"), + ], + cwd=ROOT, + env=env, + check=True, + ) + folder = ROOT / "dist" if onefile else ROOT / "dist" / "Dobramundo" + executable = folder / ("Dobramundo.exe" if sys.platform == "win32" else "Dobramundo") + if not executable.is_file(): + raise RuntimeError("Executável ausente após PyInstaller") + for name in ("README.md", "LICENSE"): + shutil.copy2(ROOT / name, folder / name) + # Cada execução usa uma pasta nova; não pode confundir relatório antigo com sucesso. + import tempfile + + with tempfile.TemporaryDirectory(prefix="run-", dir=str(reports)) as temporary: + env.update(SDL_VIDEODRIVER="dummy", SDL_AUDIODRIVER="dummy", DOBRAMUNDO_DATA_DIR=temporary) + command = [str(executable), "--self-test", "1200"] + if require_camera: + command.append("--exigir-camera") + completed = subprocess.run(command, cwd=folder, env=env, check=False, timeout=180) + report = Path(temporary) / "self_test.json" + data = json.loads(report.read_text(encoding="utf-8")) + # Relatório de build público não precisa dos caminhos absolutos do executor. + for key in tuple(data): + if key in ("paths", "bundle_dir", "data_dir", "asset_dirs", "log", "profile"): + data.pop(key) + camera = data.get("camera", {}) + camera["modelo"] = bool(camera.get("modelo")) + data["run_id"] = run_id + (reports / "self_test.json").write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + completed.check_returncode() + if data.get("status") != "ok": + raise RuntimeError("Self-test do executável não confirmou status ok") + return executable + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--onefile", action="store_true") + parser.add_argument( + "--sem-camera", action="store_true", help="build de teclado, explicitamente sem exigir detector" + ) + args = parser.parse_args() + try: + print(build(args.onefile, not args.sem_camera)) + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + report = ROOT / "build" / "desktop-selftest" / "self_test.json" + data = json.loads(report.read_text(encoding="utf-8")) if report.is_file() else {} + data.update(status="failed", failure_type=type(exc).__name__) + if isinstance(exc, subprocess.CalledProcessError): + data["exit_code"] = exc.returncode + report.parent.mkdir(parents=True, exist_ok=True) + report.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + raise + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/capture_release.py b/tools/capture_release.py new file mode 100644 index 0000000..12e3825 --- /dev/null +++ b/tools/capture_release.py @@ -0,0 +1,101 @@ +"""Capturas reprodutíveis com perfil sintético; voos omitem partículas transitórias no quadro final.""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + os.environ.update( + SDL_VIDEODRIVER="dummy", + SDL_AUDIODRIVER="dummy", + PYGAME_HIDE_SUPPORT_PROMPT="1", + DOBRAMUNDO_DATA_DIR=str(args.out / "perfil-sintetico"), + ) + import pygame + + from dobramundo.app import App + from dobramundo.persistence import Profile, create_profile_slot + from dobramundo.scenes import make_scene + + profile = Profile() + profile.consentimento = True + app = App(audio=False, profile=profile) + report = { + "profile": "synthetic", + "flight_capture_note": "after 120 frames, clear transient run.beams and draw one clean final frame", + "screens": [], + "layout_failures": [], + } + + def capture(name, scene, frames=6, clean_flight=False): + app.go(scene) + for _ in range(frames): + app.step(1 / 60, []) + if clean_flight: + scene.run.beams.clear() + scene.draw(app.canvas) + screen_rect = app.canvas.get_rect() + for button in scene.menu.buttons: + if not screen_rect.contains(button.rect): + report["layout_failures"].append({"screen": name, "button": button.key, "rect": list(button.rect)}) + for index, button in enumerate(scene.menu.buttons): + for other in scene.menu.buttons[index + 1 :]: + if button.rect.colliderect(other.rect): + report["layout_failures"].append({"screen": name, "overlap": [button.key, other.key]}) + pygame.image.save(app.canvas, args.out / (name + ".png")) + report["screens"].append(name) + + try: + for name in ("vila", "mapa", "hangar", "piloto", "preparar", "opcoes"): + capture(name, make_scene(app, name)) + for enabled in (False, True): + app.options.modo_exploracao = enabled + app.options.assistencia_previsivel = enabled + app.options.limite_voo_s = 120 if enabled else 0 + scene = make_scene(app, "preparar") + scene.page = "meu_voo" + capture("meu-voo-" + str(int(enabled)), scene) + for _ in range(5): + create_profile_slot() + capture("perfis", make_scene(app, "perfis")) + scene = make_scene(app, "perfis") + scene.error = "Não foi possível salvar este piloto. A troca foi cancelada." + capture("perfis-erro", scene) + app.storage_notice = "O perfil estava danificado; recuperei o último salvamento íntegro. Confira o progresso." + capture("vila-recuperacao", make_scene(app, "vila")) + app.storage_notice = None + app.options.limite_voo_s = 0 + app.profile.piloto_montado = True + app.profile.piloto.update(pele="pele4", cabelo="crespo", cor_cabelo="preto", roupa="amarela", olhos="castanhos") + for biome in ("amazonia", "caatinga"): + for contrast in (False, True): + app.options.alto_contraste = contrast + app.apply_options() + scene = make_scene(app, "voo", biome, seed=20261025, intro_override=False) + scene.run.invincible = True + scene.run.add_restoration(68) + capture(biome + ("-contraste" if contrast else ""), scene, frames=120, clean_flight=True) + (args.out / "captures.json").write_text( + json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + finally: + app.input.stop_camera() + pygame.quit() + print(json.dumps(report, ensure_ascii=False)) + return int(bool(report["layout_failures"])) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/prepare_assets.py b/tools/prepare_assets.py new file mode 100644 index 0000000..0cf6b36 --- /dev/null +++ b/tools/prepare_assets.py @@ -0,0 +1,179 @@ +"""Prepare runtime-sized flight backdrops and aircraft atlases. + +The watercolor originals stay untouched. The generated PNGs live beside the +game assets in ``assets/watercolor_prepared`` and are optional at runtime. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import sys +from pathlib import Path + +os.environ.setdefault("SDL_VIDEODRIVER", "dummy") +os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1") +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +import pygame # noqa: E402 + +from dobramundo import config as C # noqa: E402 + +SOURCE = ROOT / "assets" / "watercolor" +OUTPUT = ROOT / "assets" / "watercolor_prepared" +BACKDROPS = tuple(f"{biome}_{stage}" for biome in ("amazonia", "caatinga") for stage in range(3)) +PREPARED_SIZES = {name: (C.WIDTH + 32, C.HEIGHT) for name in BACKDROPS} +PLANE_ATLASES = ( + "planes_flight_a", + "planes_flight_a_clean", + "planes_flight_b", + "planes_flight_c", + "planes_menu_a", + "planes_menu_b", + "planes_menu_c", +) +PREPARED_SIZES.update({name: (768, 512) for name in PLANE_ATLASES}) +BACKDROP_SIZE = (C.WIDTH + 32, C.HEIGHT) + +ATLAS_LAYOUTS = { + "banks_amazonia": {"grid": [4, 3], "pivot": "cell bottom-center", "use": "river margins"}, + "banks_caatinga": {"grid": [4, 3], "pivot": "cell bottom-center", "use": "desert margins"}, + "fauna_sprint3": {"grid": [3, 2], "pivot": "cell bottom-center", "use": "non-colliding distant fauna"}, + "items_refined": { + "grid": [4, 2], + "order": ["paper", "plastic", "metal", "glass", "shield", "magnet", "repair", "blank"], + "pivot": "cell center", + "use": "collectibles and power-ups", + }, + "obstacles_refined": { + "grid": [3, 2], + "order": ["industrial low", "industrial gate", "industrial tower", "solar low", "solar gate", "solar tower"], + "pivot": "bottom-center; gate crop ends at physical beam edge", + "use": "collision visuals", + }, + "pilot_base": { + "grid": [2, 2], + "row_split": "710/1295 of source height", + "pivot": "cropped pose origin", + "use": "customizable pilot", + }, + "pilot_hair_front": {"grid": [4, 3], "pivot": "fitted to pilot head anchor", "use": "front hair layer"}, + "pilot_hair_back": {"grid": [4, 3], "pivot": "fitted to pilot head anchor", "use": "back hair layer"}, + "pilot_mobility": {"grid": [2, 2], "pivot": "pilot pose origin", "use": "mobility aids"}, + "planes_flight_a": {"grid": [2, 2], "pivot": "plane center", "use": "flight aircraft"}, + "planes_flight_a_clean": {"grid": [2, 2], "pivot": "plane center", "use": "flight aircraft fallback"}, + "planes_flight_b": {"grid": [2, 2], "pivot": "plane center", "use": "flight aircraft"}, + "planes_flight_c": {"grid": [2, 2], "pivot": "plane center", "use": "flight aircraft"}, + "planes_menu_a": {"grid": [2, 2], "pivot": "plane center", "use": "menu aircraft"}, + "planes_menu_b": {"grid": [2, 2], "pivot": "plane center", "use": "menu aircraft"}, + "planes_menu_c": {"grid": [2, 2], "pivot": "plane center", "use": "menu aircraft"}, + "terrain_tiles_v3": {"grid": [2, 2], "pivot": "repeating tile", "use": "ground materials"}, + "terrain_tiles": {"grid": [2, 2], "pivot": "repeating tile", "use": "legacy ground fallback"}, + "village_props": {"grid": [4, 2], "pivot": "cell bottom-center", "use": "community upgrades"}, + "villagers_sprint3": {"grid": [3, 2], "pivot": "cropped cell bottom-center", "use": "village residents"}, +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def alpha_bounds(image: pygame.Surface): + if not image.get_masks()[3]: + return None + bounds = image.get_bounding_rect(min_alpha=1) + return [bounds.x, bounds.y, bounds.width, bounds.height] if bounds.width and bounds.height else None + + +def prepare_variant(image: pygame.Surface, target_size: tuple[int, int]) -> pygame.Surface: + """Smoothscale an image to its explicit target size.""" + return pygame.transform.smoothscale(image, target_size) + + +def build_manifest(generate: bool = True) -> dict: + if generate: + OUTPUT.mkdir(parents=True, exist_ok=True) + records = [] + generation_records = [] + for metadata_path in sorted(SOURCE.glob("generation*.json")): + generation_records.append({"file": metadata_path.name, "sha256": sha256(metadata_path)}) + for path in sorted(SOURCE.glob("*.png")): + image = pygame.image.load(str(path)) + record = { + "file": path.name, + "sha256": sha256(path), + "dimensions": list(image.get_size()), + "source_bytes": path.stat().st_size, + "alpha_bounds": alpha_bounds(image), + "atlas": ATLAS_LAYOUTS.get(path.stem), + } + if path.stem in PREPARED_SIZES: + output_path = OUTPUT / path.name + target = PREPARED_SIZES[path.stem] + is_backdrop = path.stem in BACKDROPS + record["runtime_variant"] = { + "file": f"watercolor_prepared/{path.name}", + "dimensions": list(target), + "pivot": None + if is_backdrop + else ("atlas cells preserve row-major order; pivot handled by runtime cropper"), + "use": ( + "flight backdrop; logical canvas plus 32 px parallax overscan" + if is_backdrop + else "aircraft atlas; 384×256 px cells, scaled from 768×512 originals" + ), + } + if generate: + pygame.image.save(prepare_variant(image, target), str(output_path)) + if output_path.is_file(): + record["runtime_variant"]["sha256"] = sha256(output_path) + record["runtime_variant"]["bytes"] = output_path.stat().st_size + records.append(record) + manifest = { + "schema": 1, + "generator": "tools/prepare_assets.py", + "generated_with": f"pygame {pygame.version.ver}", + "provenance": { + "credit_file": "assets/watercolor/CREDITOS.txt", + "generation_metadata": generation_records, + "method": ( + "project-integrated image generation; local metadata is recorded, but is not a pixel-level source map" + ), + }, + "license": "CC BY 4.0 project package; see root LICENSE and assets/watercolor/CREDITOS.txt.", + "logical_canvas": [C.WIDTH, C.HEIGHT], + "prepared_sizes": {name: list(size) for name, size in sorted(PREPARED_SIZES.items())}, + "backdrop_target": list(BACKDROP_SIZE), + "backdrop_method": "pygame.transform.smoothscale; same raster operation as runtime fallback", + "assets": records, + } + if generate: + payload = json.dumps(manifest, ensure_ascii=False, indent=2) + "\n" + (OUTPUT / "asset_catalog.json").write_text(payload, encoding="utf-8") + return manifest + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--manifest-only", + action="store_true", + help="inspect source metadata without changing prepared outputs", + ) + args = parser.parse_args() + manifest = build_manifest(generate=not args.manifest_only) + generated = sum(1 for item in manifest["assets"] if "runtime_variant" in item) + print(f"Assets cataloged: {len(manifest['assets'])}; prepared runtime variants: {generated}; output: {OUTPUT}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/qa_sprint3.py b/tools/qa_sprint3.py index 45a9f24..680d214 100644 --- a/tools/qa_sprint3.py +++ b/tools/qa_sprint3.py @@ -22,8 +22,12 @@ parser.add_argument("--record", action="store_true") args = parser.parse_args() args.out.mkdir(parents=True, exist_ok=True) -os.environ.update(SDL_VIDEODRIVER="dummy", SDL_AUDIODRIVER="dummy", - DOBRAMUNDO_DATA_DIR=str(args.out / "perfil-qa"), PYGAME_HIDE_SUPPORT_PROMPT="1") +os.environ.update( + SDL_VIDEODRIVER="dummy", + SDL_AUDIODRIVER="dummy", + DOBRAMUNDO_DATA_DIR=str(args.out / "perfil-qa"), + PYGAME_HIDE_SUPPORT_PROMPT="1", +) import pygame # noqa: E402 @@ -47,9 +51,12 @@ def stats(values): values = sorted(values) - return {"median_ms": round(statistics.median(values), 3), - "p95_ms": round(values[int(len(values) * .95)], 3), - "p99_ms": round(values[int(len(values) * .99)], 3), "max_ms": round(max(values), 3)} + return { + "median_ms": round(statistics.median(values), 3), + "p95_ms": round(values[int(len(values) * 0.95)], 3), + "p99_ms": round(values[int(len(values) * 0.99)], 3), + "max_ms": round(max(values), 3), + } def capture(name): @@ -77,9 +84,14 @@ def capture(name): app.step(1 / 60, []) capture("piloto-acessivel") profile.piloto = look -for name, scene in (("mapa", MapScene(app)), ("hangar", HangarScene(app)), - ("opcoes", OptionsScene(app)), ("preparar", PreparationScene(app)), - ("mirar", DwellPracticeScene(app)), ("pecas", UpgradesScene(app, "aviao"))): +for name, scene in ( + ("mapa", MapScene(app)), + ("hangar", HangarScene(app)), + ("opcoes", OptionsScene(app)), + ("preparar", PreparationScene(app)), + ("mirar", DwellPracticeScene(app)), + ("pecas", UpgradesScene(app, "aviao")), +): app.go(scene) app.step(1 / 60, []) capture(name) @@ -88,7 +100,7 @@ def capture(name): app.step(1 / 60, []) for page in range(4): intro._manual_page = page - intro.time = sum(PAGES[:page]) + PAGES[page] * .62 + intro.time = sum(PAGES[:page]) + PAGES[page] * 0.62 intro.build() intro.draw(app.canvas) capture("historia-" + str(page + 1)) @@ -112,20 +124,28 @@ def capture(name): values.append((time.perf_counter() - start) * 1000) if args.record and not high_contrast and _frame >= 60 and _frame % 3 == 0: from PIL import Image + preview = pygame.transform.smoothscale(app.canvas, (660, 390)) gameplay_frames.append(Image.frombytes("RGB", preview.get_size(), pygame.image.tobytes(preview, "RGB"))) report["flights"][city + ("_contrast" if high_contrast else "_normal")] = stats(values[60:]) capture(city + ("-contraste" if high_contrast else "-normal")) if gameplay_frames: - gameplay_frames[0].save(args.out / ("voo-" + city + ".webp"), save_all=True, - append_images=gameplay_frames[1:], duration=50, loop=0, quality=74, method=3) + gameplay_frames[0].save( + args.out / ("voo-" + city + ".webp"), + save_all=True, + append_images=gameplay_frames[1:], + duration=50, + loop=0, + quality=74, + method=3, + ) gameplay_frames.clear() # Stress: player at each useful extreme, strongest allowed enlargement. app.options.escala_contraste = 1.6 app.apply_options() for x, y, name in ((-220, 22, "esq-baixo"), (220, 155, "dir-cima")): flight.run.player.x, flight.run.player.y = x, y - flight.run.player.cam_x = x * .12 + flight.run.player.cam_x = x * 0.12 flight.draw(app.canvas) capture(city + "-contraste-" + name) app.options.alto_contraste = False @@ -133,9 +153,11 @@ def capture(name): app.apply_options() flight.run.player.x, flight.run.player.y = 0, 95 flight.run.player.cam_x = 0 - flight.run.world.entities = [Entity(500, -1, "waste", y=100, sprite="papel"), - Entity(850, 0, "magnet", y=105), - Entity(600, 1, "low", spec=flight.biome.industrial_obstacles["low"][0])] + flight.run.world.entities = [ + Entity(500, -1, "waste", y=100, sprite="papel"), + Entity(850, 0, "magnet", y=105), + Entity(600, 1, "low", spec=flight.biome.industrial_obstacles["low"][0]), + ] flight.run.shield_timer, flight.run.magnet_timer = 4, 5 for contrast in (False, True): app.options.alto_contraste = contrast @@ -147,6 +169,7 @@ def capture(name): flight.run.shield_timer = flight.run.magnet_timer = 0 if args.record: from PIL import Image + # 96 s at 340 units/s = 6 cycles of the bank-layout period (24*220). # We sample native world drawing at 10fps; the stage progression is # forced for QA, not claimed to be a player completing a flight. @@ -171,11 +194,23 @@ def capture(name): frames.append(Image.frombytes("RGB", preview.get_size(), pygame.image.tobytes(preview, "RGB"))) if frame in (310, 355, 675, 740): capture(f"{city}-transicao-{frame}") - frames[0].save(args.out / ("percurso-" + city + ".webp"), save_all=True, append_images=frames[1:], - duration=100, loop=0, quality=72, method=3) - report[city + "_route"] = {"duration_s": 96, "distance": 32606, "bank_cycles": 6.17, - "capture_size": [660, 390], "capture_fps": 10, - "render": stats(render_times[60:])} + frames[0].save( + args.out / ("percurso-" + city + ".webp"), + save_all=True, + append_images=frames[1:], + duration=100, + loop=0, + quality=72, + method=3, + ) + report[city + "_route"] = { + "duration_s": 96, + "distance": 32606, + "bank_cycles": 6.17, + "capture_size": [660, 390], + "capture_fps": 10, + "render": stats(render_times[60:]), + } frames.clear() print(city, report["flights"], flush=True) diff --git a/tools/soak_runtime.py b/tools/soak_runtime.py new file mode 100644 index 0000000..994d50f --- /dev/null +++ b/tools/soak_runtime.py @@ -0,0 +1,137 @@ +"""Percurso prolongado com trocas de cenas; métricas sem câmera ou perfil real. + +python tools/soak_runtime.py --out --cycles 12 --frames 1200 +Tempo simulado difere de tempo de parede. RSS inclui caches/allocator do processo. +Não prova estabilidade no console físico nem ergonomia dos controles. +""" + +from __future__ import annotations + +import argparse +import gc +import json +import math +import os +import sys +import time +from pathlib import Path + +from benchmark_runtime import resident_bytes, stats + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--cycles", type=int, default=12) + parser.add_argument("--frames", type=int, default=1200) + args = parser.parse_args() + if args.cycles < 2 or args.frames < 1: + parser.error("Use pelo menos 2 ciclos e 1 quadro") + args.out.mkdir(parents=True, exist_ok=True) + os.environ.update( + SDL_VIDEODRIVER="dummy", + SDL_AUDIODRIVER="dummy", + DOBRAMUNDO_DATA_DIR=str(args.out / "perfil-sintetico"), + PYGAME_HIDE_SUPPORT_PROMPT="1", + ) + import pygame + + from dobramundo import __version__ + from dobramundo.app import App + from dobramundo.content.pilot import HAIR_STYLES, SKIN_TONES + from dobramundo.persistence import Profile + from dobramundo.scenes import make_scene + + profile = Profile() + profile.consentimento = True + profile.piloto_montado = True + profile.tutorial_visto = True + profile.opcoes.limite_voo_s = 0 + app = App(audio=False, profile=profile) + app.save = lambda: None # a medição não é um save de jogador + started = time.perf_counter() + report = { + "version": __version__, + "cycles": [], + "camera": False, + "dt_s": 1 / 60, + "scope": "synthetic rendering and scene lifecycle; not physical acceptance", + } + dt = 1 / 60 + failures = [] + try: + for cycle in range(args.cycles): + biome = ("amazonia", "caatinga")[cycle % 2] + profile.piloto.update( + pele=SKIN_TONES[cycle % len(SKIN_TONES)].key, + cabelo=HAIR_STYLES[cycle % len(HAIR_STYLES)].key, + cor_cabelo="preto", + roupa="amarela", + olhos="castanhos", + cadeira="sim" if cycle % 3 == 1 else "nao", + andador="sim" if cycle % 3 == 2 else "nao", + ) + app.options.alto_contraste = bool((cycle // 2) % 2) + app.apply_options() + samples = [] + for name in ("vila", "mapa", "piloto", "hangar", "preparar"): + app.go(make_scene(app, name)) + for _ in range(6): + app.step(dt, []) + scene = make_scene(app, "voo", biome) + scene.run.invincible = True # render stress only; economy uses tools/balance.py + scene.run.focus.enabled = False + app.go(scene) + for frame in range(args.frames): + if frame in (args.frames // 3, 2 * args.frames // 3): + scene.run.add_restoration(34) + app.input.pressed = {pygame.K_LEFT if math.sin(frame / 50) < 0 else pygame.K_RIGHT} + tick = time.perf_counter() + app.step(dt, []) + samples.append((time.perf_counter() - tick) * 1000) + entity_count = len(scene.run.world.entities) + if entity_count > 300: + failures.append(f"objetos sem poda no ciclo {cycle}: {entity_count}") + app.input.pressed.clear() + app.go(make_scene(app, "vila")) + app.step(dt, []) + del scene + gc.collect() + loaded = getattr(app.assets, "_loaded", {}) + surface_bytes = sum(s.get_pitch() * s.get_height() for s in loaded.values() if s is not None) + report["cycles"].append( + { + "cycle": cycle, + "biome": biome, + "contrast": app.options.alto_contraste, + "rss_bytes": resident_bytes() or None, + "loaded_surface_bytes": surface_bytes, + "loaded_images": len(loaded), + "renderer_caches": app.view.cache_stats(), + "entities": entity_count, + **stats(samples), + } + ) + print( + f"Ciclo {cycle + 1}/{args.cycles}: {biome}; " + f"RSS {report['cycles'][-1]['rss_bytes']}; objetos {entity_count}", + file=sys.stderr, + flush=True, + ) + report["wall_seconds"] = round(time.perf_counter() - started, 3) + report["simulated_seconds"] = round(args.cycles * (args.frames + 31) * dt, 3) + report["failures"] = failures + report["status"] = "ok" if not failures else "failed" + (args.out / "soak.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, ensure_ascii=False, indent=2)) + finally: + app.input.stop_camera() + pygame.quit() + return int(bool(failures)) + + +if __name__ == "__main__": + raise SystemExit(main())