adjustments on docs

This commit is contained in:
bQUARKz 2026-03-03 16:01:27 +00:00
parent f6751a03a4
commit a6ad14fcb2
Signed by: bquarkz
SSH Key Fingerprint: SHA256:Z7dgqoglWwoK6j6u4QC87OveEq74WOhFN+gitsxtkf8
33 changed files with 831 additions and 1330 deletions

View File

@ -1,81 +0,0 @@
# Agenda - Single Canonical Architecture
## Problema
Hoje a arquitetura do runtime está fragmentada em documentos com níveis diferentes de autoridade.
Na prática existem pelo menos dois problemas:
- mais de um documento tenta falar pela arquitetura;
- um deles ainda se apresenta como `stub`, enquanto outro se declara baseline canônico.
## Dor
- Contribuidores perdem tempo tentando descobrir qual documento manda.
- PR arquitetural pode ser validada por um texto e contrariar outro.
- A documentação deixa de servir como guardrail e passa a gerar ambiguidade.
- O projeto perde disciplina exatamente na camada que deveria fixar invariantes.
## Alvo da Discussao
Definir um único documento canônico de arquitetura do runtime, com papel explícito para cada outro documento remanescente.
O alvo é matar a ambiguidade, não só mover arquivos.
Ao final da discussão deve ficar claro:
- qual documento é canônico;
- quais docs são derivativos, históricos ou de apoio;
- o que deve ser removido, fundido ou rebaixado de autoridade.
## O Que Precisa Ser Definido
1. Documento canônico.
Onde vive a arquitetura mandatória do runtime.
2. Escopo do documento.
Quais invariantes ele deve cobrir:
- execution model
- memory model
- safepoints
- scheduler
- verifier
- syscall ABI
- firmware/runtime boundary
3. Papel dos demais docs.
O que é:
- arquitetura normativa
- roadmap
- histórico
- specification detalhada
- material pedagógico
4. Política de atualização.
Mudança arquitetural deve exigir atualização do doc canônico no mesmo PR?
5. Estratégia de remoção do `stub`.
Se será apagado, redirecionado ou transformado em índice.
## O Que Necessita Para Resolver
- inventário dos docs que hoje competem por autoridade;
- decisão de taxonomia documental;
- definição do local canônico;
- plano de migração de conteúdo sem perder contexto útil;
- regra de governança para futuras PRs arquiteturais.
## Fora de Escopo
- reorganização completa de todo o diretório `docs/`;
- rewrite estilístico de todo material pedagógico;
- padronização editorial fina além do necessário para eliminar ambiguidade.
## Critério de Saida Desta Agenda
Pode virar PR quando houver:
- definição do documento canônico;
- lista do que será removido, fundido ou rebaixado;
- regra explícita de atualização futura;
- plano curto de migração sem deixar lacuna documental.

View File

@ -1,77 +0,0 @@
# Agenda - Hardware Specs Reorganization
## Problema
As specs de hardware hoje estão com cara de colcha de retalhos.
Há material útil, mas a organização mistura:
- capítulos extensos e narrativos;
- conteúdo normativo e conteúdo pedagógico;
- temas de VM, firmware, cartridge, assets e ABI no mesmo bloco de "hardware";
- granularidade desigual entre capítulos.
## Dor
- Fica difícil saber o que é norma e o que é explicação.
- A navegação está ruim para quem precisa alterar um domínio específico.
- Ownership documental por área não está claro.
- Revisões futuras tendem a acrescentar mais remendos em vez de consolidar o modelo.
- O risco de contradição entre spec, arquitetura e implementação cresce.
## Alvo da Discussao
Definir uma organização coerente para as specs do sistema, com separação clara entre:
- spec normativa;
- material conceitual/pedagógico;
- arquitetura de runtime;
- domínios de hardware/periféricos;
- firmware, cartridge e tooling-related specs.
## O Que Precisa Ser Definido
1. Taxonomia das specs.
Quais grandes categorias devem existir:
- machine/runtime
- hardware/peripherals
- firmware/system
- cartridge/package
- host ABI
- assets/tooling
2. Critério de corte.
O que pertence a "hardware" de fato e o que deve sair desse pacote.
3. Estrutura de navegação.
Como organizar índice, capítulos, subpastas e documentos canônicos por domínio.
4. Nível de autoridade.
Quais documentos são normativos e quais são apenas explicativos.
5. Estratégia de migração.
Como reorganizar sem quebrar referências, sem perder contexto e sem reescrever tudo de uma vez.
## O Que Necessita Para Resolver
- inventário da estrutura atual;
- proposta de taxonomia e árvore de diretórios;
- mapeamento capítulo atual -> destino futuro;
- política para docs históricos ou híbridos;
- critério mínimo de consistência editorial para novos documentos.
## Fora de Escopo
- reescrever toda a spec de hardware imediatamente;
- normalizar cada frase ou estilo de escrita;
- atualizar todo conteúdo técnico de cada capítulo nesta mesma discussão.
## Critério de Saida Desta Agenda
Pode virar PR quando houver:
- taxonomia alvo aprovada;
- nova árvore de organização definida;
- mapa de migração dos capítulos atuais;
- decisão sobre normativo vs pedagógico;
- plano incremental de execução.

View File

@ -0,0 +1,39 @@
# PROMETEU Learn
Esta área reúne material didático sobre a máquina PROMETEU.
Ela existe para explicar o modelo mental da fantasy handheld, suas influências, tradeoffs e implicações de design sem contaminar as specs normativas com framing pedagógico.
## Authority
- `docs/runtime/learn/` não é fonte canônica de contrato técnico.
- As superfícies normativas da máquina vivem em [`../specs/`](../specs/README.md).
- As invariantes internas da VM/runtime vivem em [`../virtual-machine/ARCHITECTURE.md`](../virtual-machine/ARCHITECTURE.md).
## Current Guides
- [`gfx-mental-model.md`](gfx-mental-model.md)
- [`audio-mental-model.md`](audio-mental-model.md)
- [`input-mental-model.md`](input-mental-model.md)
- [`touch-mental-model.md`](touch-mental-model.md)
- [`save-memory-and-memcard.md`](save-memory-and-memcard.md)
- [`observability-and-debugging.md`](observability-and-debugging.md)
- [`portability-and-cross-platform.md`](portability-and-cross-platform.md)
- [`time-model-and-cycles.md`](time-model-and-cycles.md)
## Rules
- material em `learn` pode explicar, comparar, ensinar e contextualizar;
- material em `learn` não deve redefinir o contrato normativo dos specs;
- quando um tema tiver spec e guia didático, o guia deve apontar para o spec correspondente.
## When To Create A Pair
Criar um par `spec` + `learn` quando o tema:
- precisa de contrato técnico estável e também de modelo mental;
- tem forte carga histórica, pedagógica ou de design rationale;
- corre risco de virar manifesto dentro do spec normativo;
- exige exemplos, comparações ou intuição que não pertencem ao contrato.
Se o tema for pequeno e estritamente contratual, o capítulo pode nascer só em `specs`.

View File

@ -0,0 +1,55 @@
# Audio Mental Model
Status: pedagogical
Companion spec: [`../specs/05-audio-peripheral.md`](../specs/05-audio-peripheral.md)
O modelo mental correto para áudio em PROMETEU é o de um periférico ativo com orçamento, não o de “som automático”.
## Philosophy
Som:
- consome tempo;
- consome memória;
- usa canais finitos;
- depende de comandos explícitos.
Isso aproxima PROMETEU de consoles e arcades clássicos em que o jogo “conversa” com um bloco de áudio com regras próprias.
## Audio CPU Metaphor
Uma metáfora útil é pensar em:
```text
[Game CPU] -> envia comandos em 60 Hz -> [AUDIO Peripheral]
|
v
Voices + Mixer
|
v
PCM Output
```
Essa metáfora não exige um thread dedicado. Ela só separa responsabilidades:
- a máquina define o modelo lógico;
- o host decide como entregar buffers contínuos;
- o jogo fala em comandos, não em manipulação direta do backend.
## Good Habits
- reutilizar samples;
- limitar vozes simultâneas;
- tratar som como evento intencional;
- separar música e efeitos;
- evitar disparar o mesmo som todo frame.
## Historical Direction
As influências principais aqui são:
- NES, pela clareza de canais limitados;
- SNES, por playback de sample e mistura;
- CPS-2 e Neo Geo, pela sensação de folga e presença de sample playback.
PROMETEU abstrai essas referências. Ele não tenta reproduzir nenhum desses sistemas literalmente.

View File

@ -0,0 +1,65 @@
# GFX Mental Model
Status: pedagogical
Companion spec: [`../specs/04-gfx-peripheral.md`](../specs/04-gfx-peripheral.md)
PROMETEU trata gráficos como um periférico explícito, não como uma GPU moderna.
O modelo mental correto é o de uma máquina 2D retro com:
- framebuffer;
- tile banks;
- tile layers;
- sprites por ordem de desenho;
- composição determinística por frame.
## Why This Exists
O objetivo não é imitar hardware histórico byte a byte. O objetivo é capturar a família de restrições e de linguagem visual de consoles como SNES, CPS-2 e Neo Geo, mas em um contrato pequeno, portátil e implementável em desktop e hardware DIY.
Isso produz algumas consequências importantes:
- desenho por ordem importa mais do que “efeitos”;
- paletas importam como parte do asset design;
- o programador pensa em rasterização, não em shaders;
- o custo visual fica mais observável.
## What The GFX Is Not
PROMETEU GFX não é:
- pipeline moderno de GPU;
- framebuffer RGBA com alpha arbitrário;
- sistema de shaders;
- composição automática pós-processada.
Essas ausências são deliberadas. Elas forçam uma linguagem visual mais próxima de console clássico e mantêm o contrato executável em ambientes modestos.
## Practical Intuition
- Tile layers existem para mundo e cenário.
- HUD existe para informação fixa e deve permanecer desacoplado da câmera.
- Sprites existem para entidades móveis e sua profundidade depende da ordem e da prioridade.
- Paletas existem para variar estado visual sem duplicar tile art.
- Fade existe como efeito especial discreto, não como alpha genérico.
## Palette Thinking
Uma boa maneira de pensar PROMETEU é: arte e cor não são a mesma coisa.
O tile é a forma. A paleta é o estado visual.
Isso habilita:
- variação de inimigos;
- mudança de bioma;
- dano, gelo, veneno, power-up;
- temas de HUD;
- ciclos de dia e noite.
## Use Cases
- troca de área com `Scene Fade`;
- troca de HUD com `HUD Fade`;
- flash de dano ou teleporte;
- swap global de paleta para clima ou estado de mundo.

View File

@ -0,0 +1,43 @@
# Input Mental Model
Status: pedagogical
Companion spec: [`../specs/06-input-peripheral.md`](../specs/06-input-peripheral.md)
PROMETEU trata input como estado amostrado, não como evento assíncrono.
## State Versus Event
O modelo mais importante para entender é:
- botão não “dispara” uma ação sozinho;
- botão muda de estado;
- o jogo consulta esse estado durante o frame.
Isso se parece muito mais com polling de registrador em console clássico do que com callbacks de UI moderna.
## Why This Matters
Esse modelo:
- melhora determinismo;
- simplifica replay;
- facilita depuração;
- torna o frame loop mais legível.
Também encaixa melhor na identidade de PROMETEU como máquina com forte inspiração em hardware retro e em construção DIY.
## Good Habits
- ler input em `UPDATE`;
- mapear ações, não teclas físicas;
- separar leitura de input de lógica pesada;
- tratar polling como parte do frame budget.
## Teaching Value
O periférico de input ajuda a ensinar:
- diferença entre estado e evento;
- amostragem temporal;
- sincronização entre input e lógica;
- determinismo em sistemas interativos.

View File

@ -0,0 +1,33 @@
# Observability and Debugging
Status: pedagogical
Companion spec: [`../specs/10-debug-inspection-and-profiling.md`](../specs/10-debug-inspection-and-profiling.md)
PROMETEU foi desenhado para ser observável.
## Debug Philosophy
Há três ideias centrais aqui:
1. estado vem antes de abstração;
2. tempo é cidadão de primeira classe;
3. observar não deve alterar o resultado lógico.
Isso puxa o projeto para um estilo de depuração mais próximo de máquina e menos próximo de “tentativa e erro”.
## Why This Matters
Quando a máquina expõe pilhas, heap, ciclos, buffers e faults de forma consistente, o programador consegue:
- localizar custo real;
- correlacionar tempo e memória;
- justificar decisão técnica;
- depurar sem inventar explicações mágicas.
## Teaching Value
Essa superfície didática existe porque PROMETEU quer ensinar também como sistemas são analisados:
- debugging como observação informada;
- profiling como leitura de evidência;
- certification como relatório técnico reproduzível.

View File

@ -0,0 +1,52 @@
# Portability and Cross-Platform Execution
Status: pedagogical
Companion spec: [`../specs/11-portability-and-cross-platform-execution.md`](../specs/11-portability-and-cross-platform-execution.md)
PROMETEU trata portabilidade como propriedade arquitetural da máquina, não como adaptação posterior.
## Core Idea
O ponto principal é simples:
- a máquina define a semântica;
- o host realiza apresentação e integração física;
- o cartridge não negocia comportamento com o sistema operacional.
Isso evita a noção comum de que cada plataforma “tem sua versão” da lógica do jogo.
## Why This Matters
Quando tempo, memória, input, áudio e gráficos são definidos pela máquina, ficam mais fáceis:
- replay determinístico;
- certification reproduzível;
- execução em desktop, mobile e hardware DIY;
- separação limpa entre semântica e adaptação.
## Practical Separation
Uma forma útil de pensar é:
- cartridge carrega programa e assets;
- a VM/runtime executa a lógica;
- o host mostra pixels, entrega áudio e coleta input físico;
- o host não redefine as regras do jogo.
## What Portability Does Not Mean
PROMETEU não promete:
- a mesma latência física;
- o mesmo consumo energético;
- o mesmo throughput bruto do host.
Ele promete consistência lógica. Isso é o que importa para a identidade da máquina.
## Teaching Value
Esse modelo ajuda a ensinar:
- diferença entre lógica e apresentação;
- por que engines modernas frequentemente perdem determinismo;
- como projetar software portátil sem depender de sorte.

View File

@ -0,0 +1,43 @@
# Save Memory and MEMCARD
Status: pedagogical
Companion spec: [`../specs/08-save-memory-and-memcard.md`](../specs/08-save-memory-and-memcard.md)
PROMETEU trata persistência como hardware explícito, não como save invisível.
## Mental Model
O MEMCARD não é save state. Ele é um dispositivo de persistência controlado pelo jogo.
Isso implica:
- tamanho conhecido;
- custo observável;
- necessidade de `commit()`;
- possibilidade de falha;
- formato de dados sob controle do jogo.
## Why Explicit Commit Matters
O `commit()` existe para tornar persistência uma decisão técnica visível.
Sem ele, não há ilusão de que “salvar simplesmente aconteceu”. O jogo precisa assumir quando quer:
- materializar escrita;
- aceitar custo;
- lidar com risco de perda ou corrupção.
## Tooling Surface
Ferramentas externas podem expor utilidades como:
- criar ou resetar MEMCARD;
- importar e exportar `.mem`;
- inspecionar tamanho e uso;
- associar cartões a projetos.
Essas superfícies são auxiliares. Elas não mudam o contrato da máquina.
## Why This Fits PROMETEU
Esse modelo conversa bem com a herança de console e com o foco DIY do projeto: persistência é parte do design da máquina, não conveniência escondida do host.

View File

@ -0,0 +1,50 @@
# Time Model and Cycles
Status: pedagogical
Companion spec: [`../specs/01-time-model-and-cycles.md`](../specs/01-time-model-and-cycles.md)
PROMETEU trata tempo como parte explícita da máquina.
## Core Idea
Nada acontece “de graça” ou “instantaneamente”. O programador deve pensar em:
- ritmo da máquina;
- custo por frame;
- distribuição de trabalho ao longo do tempo;
- impacto arquitetural de quando cada sistema roda.
## Why Cycles Instead of Milliseconds
Milissegundos variam com plataforma, jitter e hardware real. Cycles dão uma métrica de custo que pertence à máquina PROMETEU, não ao host.
Isso torna mais fácil comparar soluções, ensinar custo e raciocinar sobre performance sem esconder a conta atrás do sistema operacional.
## Temporal Distribution As Design
Uma das intuições mais importantes em PROMETEU é: otimização não é só “fazer menos”, é decidir **quando** fazer.
Exemplos úteis:
- IA em 30 Hz;
- pathfinding em 15 Hz;
- timers dirigidos por frame count;
- separação entre atualização pesada e apresentação.
## Why CAP Fits Here
O CAP reforça essa leitura de tempo como evidência técnica. Ele não existe para bloquear execução, e sim para tornar visíveis:
- picos;
- gargalos;
- distribuição de custo;
- decisões de arquitetura temporal.
## Teaching Value
Esse modelo ajuda a ensinar:
- planejamento de execução;
- trade-offs técnicos;
- leitura de perfil real;
- organização temporal como ferramenta arquitetural.

View File

@ -0,0 +1,40 @@
# Touch Mental Model
Status: pedagogical
Companion spec: [`../specs/07-touch-peripheral.md`](../specs/07-touch-peripheral.md)
PROMETEU usa TOUCH como um ponteiro absoluto e determinístico, não como uma superfície rica em gestos.
## Design Intuition
O princípio central é simples:
- um único ponteiro ativo;
- sem gestos implícitos;
- sem aceleração;
- sem heurística;
- mesmo comportamento em desktop, mobile e hardware dedicado.
Se o comportamento não puder ser garantido de forma portátil, ele não entra na máquina.
## Why Single Pointer
Multitouch físico pode existir no host, mas a máquina escolhe um único ponteiro lógico para evitar:
- ambiguidades de captura;
- diferenças entre plataformas;
- mudanças semânticas entre mouse, touch real e touchscreen embutido.
## Good Uses
TOUCH funciona bem para:
- UI;
- seleção direta;
- drag-and-drop;
- puzzles de apontamento;
- trilhas, cortes e mecânicas baseadas em contato.
## What Games Must Do Themselves
Se um jogo quiser gesto, swipe, long-press ou smoothing, ele deve construir isso por cima do estado bruto por frame. O periférico não interpreta intenção.

View File

@ -1,80 +0,0 @@
# PR-017 [ARCHITECTURE]: Establish Single Canonical Runtime Architecture
## Briefing
O runtime hoje tem mais de um documento tentando orientar a arquitetura, com niveis diferentes de autoridade e maturidade. Na pratica, isso cria um problema de governanca tecnica: contribuidores podem consultar documentos distintos, chegar a conclusoes diferentes e ainda assim parecer "alinhados com a arquitetura".
Esta PR fecha essa ambiguidade. O objetivo nao e produzir mais texto, e sim definir um unico documento canonico de arquitetura do runtime e rebaixar, fundir ou remover o que hoje compete com ele.
## Problema
- ha mais de um documento arquitetural relevante no repositorio;
- pelo menos um deles ainda se apresenta como `stub`, enquanto outro se declara baseline autoritativo;
- a fronteira entre:
- arquitetura normativa;
- roadmap;
- documento de apoio;
- material pedagogico;
nao esta explicitamente fechada;
- sem um documento canonico, a arquitetura deixa de ser guardrail e vira opiniao distribuida.
## Alvo
- documentos arquiteturais do runtime no raiz e em `docs/`;
- definicao de autoridade documental para runtime/VM/ABI/scheduler/GC/verifier;
- governanca minima para futuras PRs arquiteturais.
- todo conteudo em ingles.
-
## Escopo
- Escolher um unico documento canonico para a arquitetura do runtime.
- Definir o papel explicito dos demais documentos relacionados:
- canonico;
- derivado;
- historico;
- roadmap;
- pedagogico.
- Consolidar ou remover o documento `stub` que hoje compete com o baseline.
- Garantir que as invariantes arquiteturais centrais tenham um unico lar.
- Registrar a regra de manutencao: mudanca arquitetural exige atualizacao do documento canonico no mesmo PR.
## Fora de Escopo
- Reorganizar todo o diretorio `docs/`.
- Reescrever todas as specs detalhadas do projeto.
- Revisar estilo textual de todo material pedagogico.
- Introduzir mudancas comportamentais na VM, runtime ou firmware.
## Abordagem
1. Inventariar os documentos que hoje falam pela arquitetura do runtime.
2. Definir uma taxonomia minima de documentos para o repositorio:
- normativo;
- especificacao;
- roadmap;
- historico;
- pedagogico.
3. Escolher o documento canonico e migrar para ele apenas as invariantes que realmente governam o sistema.
4. Rebaixar, fundir ou remover o documento `stub` e qualquer outro texto que gere concorrencia de autoridade.
5. Deixar links e notas de transicao claros para evitar pontos cegos.
## Criterios de Aceite
- Existe exatamente um documento canonico de arquitetura do runtime.
- O papel dos demais documentos arquiteturais esta explicito.
- O documento `stub` deixa de competir por autoridade:
- removido; ou
- convertido em indice/redirecionamento sem ambiguidade.
- As invariantes centrais do runtime ficam localizadas no documento canonico.
- Fica documentada a regra de que PR arquitetural deve atualizar o documento canonico quando alterar invariantes.
## Tests
- Revisao estrutural dos links e referencias entre documentos afetados.
- Confirmacao manual de que nao restaram dois documentos com claims conflitantes de autoridade.
- Se a PR mover ou renomear arquivos, validar que referencias internas em `README`, `ARCHITECTURE` e `docs/` continuam corretas.
## Risco
Medio. O risco principal e produzir consolidacao superficial, deixando ambiguidade semantica mesmo depois da reorganizacao. A PR deve ser severa: se dois documentos ainda puderem ser lidos como "fonte final", a mudanca falhou.

View File

@ -1,250 +1,156 @@
# Time Model and Cycles
## 1 Overview
Domain: machine timing and cycles
Function: normative
PROMETEU is a **time-oriented** system.
Didactic companion: [`../learn/time-model-and-cycles.md`](../learn/time-model-and-cycles.md)
Nothing happens "instantly".
## 1 Scope
Every action consumes **measurable time**, expressed in **execution cycles**.
This chapter defines the temporal contract of the PROMETEU machine.
This chapter defines:
It covers:
- the system's **base clock**
- the concept of a **PROMETEU cycle**
- how time is distributed across frames
- how the **CAP (Execution Cap)** relates to this model
- machine base clock;
- logical frame structure;
- cycle accounting;
- per-frame budget;
- CAP interaction with time measurement.
---
## 2 System Base Clock
## 2. System Base Clock
PROMETEU operates with a **fixed clock of 60 Hz**.
PROMETEU operates with a fixed **60 Hz** logical clock.
This means:
- 60 iterations of the main loop per second
- each iteration corresponds to **one frame**
- the clock is **deterministic and stable**, regardless of the platform
- 60 iterations of the machine loop per second;
- each iteration corresponds to one logical frame;
- the logical clock is stable regardless of host platform.
> The clock defines the machine's rhythm,
not the amount of mandatory work per frame.
>
## 3 Logical Frame
---
A PROMETEU frame represents a complete unit of machine execution.
## 3. The PROMETEU Frame
Conceptual stage order:
A **PROMETEU frame** represents a complete unit of execution.
Each frame conceptually executes the following stages:
```
```text
FRAME N
──────────────
INPUT
UPDATE
DRAW
AUDIO
SYNC
──────────────
```
The system guarantees:
The machine guarantees:
- fixed order
- predictable repetition
- absence of "ghost" frames
- fixed stage order;
- deterministic repetition;
- no implicit extra frames between logical frame boundaries.
---
## 4. PROMETEU Cycles
## 4 PROMETEU Cycles
### 4.1 Definition
A **PROMETEU cycle** is the smallest abstract unit of time in the system.
A **PROMETEU cycle** is the abstract unit used to measure execution cost inside the machine.
- each VM instruction consumes a fixed number of cycles
- peripheral calls also have a cost
- the cost is **documented and stable**
- VM instructions consume documented cycle cost;
- peripheral operations also consume cycle cost;
- cycle cost is independent of host wall-clock timing.
### 4.2 Properties
Cycles are:
- **countable**
- **comparable**
- **independent of real hardware**
- countable;
- comparable;
- stable across supported hosts;
- suitable for certification and profiling.
---
## 5 Per-Frame Budget
### 4.2 Why cycles, and not milliseconds?
PROMETEU does not measure time in milliseconds because:
- milliseconds vary between platforms
- real clocks differ
- jitter and latency hide the real cost
Cycles allow stating:
> "This program is more expensive than that one,
>
>
> regardless of where it runs."
>
---
## 5. Per-Frame Budget
Each frame has a **maximum cycle budget**.
Each frame has a maximum cycle budget.
This budget:
- is reset every frame
- does not accumulate unused cycles
- represents the capacity of the "virtual CPU"
- is reset every frame;
- does not accumulate unused cycles;
- represents the capacity of the virtual execution envelope for that frame.
### Conceptual example
### 5.1 Conceptual Example
```
Frame Budget:10,000cycles
```text
Frame Budget: 10,000 cycles
Used:
-Update logic:4,200
-Draw calls:3,100
-Audio:900
- Update logic: 4,200
- Draw calls: 3,100
- Audio: 900
Remaining:
1,800cycles
1,800 cycles
```
---
## 6 Work Distribution Over Time
## 6. Separation between Clock and Work
PROMETEU does not require all logic to run every frame.
PROMETEU **does not require** all logic to run every frame.
Machine-visible work may be distributed over time, for example:
The programmer is **explicitly encouraged** to distribute work over time.
- enemy logic every 2 frames;
- pathfinding every 4 frames;
- timers based on frame count;
- subsystem-specific update cadence.
### Common examples
Such distribution changes cycle pressure and is part of the observable execution model.
- enemy logic every 2 frames (30 Hz)
- pathfinding every 4 frames (15 Hz)
- animations independent of AI
- timers based on frame count
## 7 CAP Interaction
This reflects real-world practices from:
The **CAP** defines contextual technical limits such as:
- classic consoles
- embedded systems
- microcontroller firmware
- maximum cycle budget per frame;
- memory limits;
- peripheral call limits.
> Not everything needs to happen now.
>
---
## 7. Temporal Distribution as Architecture
PROMETEU treats **work distribution over time** as an architectural decision.
This means that:
- code that runs every frame is more expensive
- distributed code is more efficient
- optimization is, first and foremost, **temporal organization**
PROMETEU teaches:
> performance doesn't just come from "less code",
>
>
> but from **when** the code runs.
>
---
## 8. Execution CAP (Contextual Budget)
### 8.1 What is the CAP
The **CAP** defines a set of technical limits associated with a **specific context**, such as:
- Game Jams
- academic evaluations
- technical challenges
The CAP can define:
- maximum cycle budget per frame
- memory limit
- peripheral call limits
---
### 8.2 CAP does not block execution
### 7.1 CAP Does Not Block Execution
Fundamental rules:
- the game **always runs**
- the game **can always be packaged**
- the game **can always be played**
- the game always runs;
- the game can always be packaged;
- the game can always be played.
The CAP **never prevents** execution.
CAP does not prevent execution.
---
### 7.2 CAP Generates Evidence
### 8.3 CAP generates evidence, not punishment
When CAP is active, PROMETEU measures and records:
When a CAP is active, PROMETEU:
- average cycle usage per frame;
- cycle peaks;
- problematic frames;
- cost distribution.
- measures execution
- records peaks
- identifies bottlenecks
- generates a **certification report**
These data feed certification artifacts without changing cartridge semantics.
This report:
## 8 Time-Based Certification
- does not block the game
- does not invalidate the delivery
- **documents compliance or non-compliance**
PROMETEU certification may analyze:
---
- average cycle usage per frame;
- maximum peaks;
- problematic frames;
- dominant cost sources.
## 9. Time-Based Certification
### 8.1 Conceptual Example
PROMETEU certification analyzes:
- average cycle usage per frame
- maximum peaks
- problematic frames
- cost distribution
Example:
```
Target CAP:PROMETEU-LITE
Frame Budget:5,000cycles
```text
Target CAP: PROMETEU-LITE
Frame Budget: 5,000 cycles
Frame 18231:
Used:5,612cycles
Used: 5,612 cycles
Primary cause:
enemy.updateAI():1,012cycles
enemy.updateAI(): 1,012 cycles
```
This certification accompanies the game as a **technical artifact**.
---
## 10. Pedagogical Implications
The time and cycles model allows teaching:
- execution planning
- time-oriented architecture
- technical trade-offs
- reading real profiles

View File

@ -1,5 +1,8 @@
# Prometeu Virtual Machine (PVM)
Domain: VM subsystem overview
Function: normative
This chapter defines the VM as an execution subsystem inside the PROMETEU machine.
It is intentionally narrower than the broader machine specs:

View File

@ -1,5 +1,8 @@
# VM Values and Calling Convention
Domain: VM values and calling convention
Function: normative
This chapter isolates the slot/value model and the rules for calls, returns, tuples, and frames.
## 1 Value Types

View File

@ -1,5 +1,8 @@
# VM Function Values and Closures
Domain: VM closures and function values
Function: normative
This chapter defines how the PVM models first-class function values.
## 1 First-Class Function Model

View File

@ -1,5 +1,8 @@
# Memory Model
Domain: VM memory model
Function: normative
This chapter defines the VM memory architecture: stack, heap, handles, object layout, allocation, and garbage collection.
It intentionally focuses on VM-managed memory.

View File

@ -1,19 +1,15 @@
# GFX Peripheral (Graphics System)
Domain: virtual hardware: graphics
Function: normative
Didactic companion: [`../learn/gfx-mental-model.md`](../learn/gfx-mental-model.md)
## 1. Overview
The **GFX** peripheral is responsible for generating images in PROMETEU.
It models **simple graphics hardware**, inspired by classic consoles
(SNES, CPS-2, Neo-Geo), prioritizing:
- determinism
- low computational cost
- didactics
- portability
The GFX **is not a modern GPU**.
It is an explicit device, based on:
It is an explicit 2D graphics device based on:
- framebuffer
- tilemaps
@ -388,23 +384,6 @@ Rules:
---
### 17.4 Use Cases
- HUD Switch:
- decrease `HUD_FADE_LEVEL` to 0
- switch HUD/tilemap
- increase `HUD_FADE_LEVEL` to 31
- Area Switch:
- decrease `SCENE_FADE_LEVEL` to 0
- switch scenery
- increase `SCENE_FADE_LEVEL` to 31
- Flash / damage / teleport:
- use `fade_color = WHITE` or another thematic color
---
## 18. Palette System
### 18.1. Overview
@ -414,13 +393,6 @@ PROMETEU uses **exclusively** palette-indexed graphics.
There is no direct RGB-per-pixel mode.
Every graphical pixel is an **index** pointing to a real color in a palette.
Objectives:
- reduce RAM and storage usage
- allow color swapping without shaders
- maintain retro identity
- facilitate effects like variation, damage, day/night
---
### 18.2. Pixel Format
@ -531,41 +503,7 @@ Tile Banks are "strong assets":
---
### 18.8. Possible Effects with Palettes
Without shaders, it is possible to:
- Palette swap:
- enemies with color variation
- States:
- damage, ice, poison, power-up
- Day / night:
- swap palettes globally
- Biomes:
- same art, different climate
- UI themes
All this without changing tiles.
---
### 18.9. Artistic Limitations
- Each tile/sprite:
- maximum of 16 colors
- Smooth gradients require:
- dithering
- discrete blend
- glow/emission
This limitation is intentional and part of the PROMETEU identity.
---
### 18.10. Metrics for Certification (CAP)
### 18.8. Metrics for Certification (CAP)
The system can measure:
@ -573,24 +511,3 @@ The system can measure:
- `palettes_referenced_this_frame`
- `tiles_drawn_by_palette_id`
- `sprites_drawn_by_palette_id`
This allows:
- analyzing artistic cost
- teaching the impact of excessive variety
- suggesting best practices for visual cohesion
---
## 19. Summary
PROMETEU's GFX is simple **by choice**, not by limitation.
- RGB565 Framebuffer with double buffer
- Color key for transparency
- SNES-style discrete blending
- Up to 16 tile banks
- 4 Tile Layers + 1 HUD
- Layer = tilemap + cache + scroll
- Rasterized projection per frame
- Depth defined by drawing order

View File

@ -1,36 +1,25 @@
# Audio Peripheral (Audio System)
## 1. Overview
Domain: virtual hardware: audio
Function: normative
The **AUDIO Peripheral** is responsible for **sound generation and mixing** in PROMETEU.
Didactic companion: [`../learn/audio-mental-model.md`](../learn/audio-mental-model.md)
Just like the other subsystems:
## 1 Scope
- it is not automatic
- it is not free
- it is not magic
This chapter defines the runtime-facing audio contract of PROMETEU.
Each sound is the result of **explicit commands**, executed under a **time and resource budget**.
The AUDIO peripheral is responsible for sound generation and mixing under explicit machine limits.
> Sound consumes time.
> Sound consumes memory.
Core contract:
---
- command-driven control from the game loop;
- fixed output format;
- finite voice count;
- deterministic voice conflict policy;
- explicit cost in cycles and certification surface.
## 2. Philosophy
PROMETEU treats audio as:
- an **active peripheral**
- with **limited channels**
- **deterministic** behavior
- **explicit** control
Objective: architectural and didactic clarity, not absolute realism.
---
## 3. General Architecture
## 2 General Architecture
The audio system is composed of:
@ -39,31 +28,20 @@ The audio system is composed of:
- **Mixer** — summation of voices
- **Output** — PCM stereo buffer
Conceptual separation:
Timing boundary:
- Game sends **commands at 60Hz**
- Audio is **generated continuously** at 48kHz
- game sends commands at **60 Hz**;
- audio generates PCM at **48 kHz**.
---
## 4. Output Format
## 3 Output Format
- Sample rate: **48,000 Hz**
- Format: **PCM16 stereo (signed i16)**
- Clipping: saturation/clamp
This format is compatible with:
## 4 Voices
- common I2S DACs
- HDMI audio
- USB audio
- DIY SBCs (Raspberry Pi, Orange Pi, etc.)
---
## 5. Voices (Channels)
### 5.1 Quantity
### 4.1 Quantity
```
MAX_VOICES = 16
@ -75,9 +53,7 @@ Each voice:
- is independent
- is mixed into the final output
---
### 5.2 Voice State
### 4.2 Voice State
Each voice maintains:
@ -90,9 +66,7 @@ Each voice maintains:
- `loop_start`, `loop_end`
- `priority` (optional)
---
### 5.3 Voice Conflict
### 4.3 Voice Conflict
If all voices are occupied:
@ -101,67 +75,9 @@ If all voices are occupied:
- `STEAL_QUIETEST`
- `STEAL_LOWEST_PRIORITY`
## 5 Samples
PROMETEU does not resolve this automatically without a defined rule.
---
## 6. Conceptual Model: “Audio CPU”
The PROMETEU AUDIO is conceived as an **independent peripheral**, just as classic consoles had:
- Main game CPU
- Dedicated sound CPU
In PROMETEU:
- The **logical core** assumes this conceptual separation
- The **host decides** how to implement it:
- same thread
- separate thread
- separate core
### 6.1 Hardware Metaphor
Conceptually:
```
[Game CPU] → sends 60Hz commands → [AUDIO Peripheral]
|
v
Voices + Mixer
|
v
PCM Output
```
### 6.2 Implementation is the Host's Role
The core:
- defines the **model**
- defines the **commands**
- defines the **limits**
The host:
- chooses:
- threads
- CPU affinity
- audio backend
- guarantees continuous delivery of buffers
Thus:
> PROMETEU models the hardware.
> The host decides how to physically realize it.
---
## 7. Samples
### 7.1 Format
### 5.1 Format
PROMETEU samples:
@ -175,27 +91,20 @@ Fields:
- `frames_len`
- `loop_start`, `loop_end` (optional)
---
### 5.2 Command Surface
### 7.2 Usage
Representative command surface:
Example:
```
audio.play(sample_id, voice_id, volume, pan, pitch, priority)
```text
audio.play(sample, voice, volume, pan, pitch, priority)
audio.stop(voice)
audio.setVolume(voice, value)
audio.setPan(voice, value)
audio.setPitch(voice, value)
audio.isPlaying(voice)
```
Or:
```
audio.playAuto(sample_id, volume, pan, pitch, priority)
```
(uses stealing policy)
---
## 8. Pitch and Interpolation
## 6 Pitch and Interpolation
- `rate = 1.0` → normal speed
- `rate > 1.0` → higher pitch
@ -205,9 +114,7 @@ As position becomes fractional:
- **linear interpolation** is used between two neighboring samples
---
## 9. Mixer
## 7 Mixer
For each output frame (48kHz):
@ -225,9 +132,7 @@ Cost depends on:
- number of active voices
- use of interpolation
---
## 10. Synchronization with the Game
## 8 Synchronization with the Game
- Game runs at **60Hz**
- Audio generates data at **48kHz**
@ -243,25 +148,17 @@ Every frame (60Hz):
The audio applies these commands and continues playing.
---
## 9 Host Responsibilities
## 11. Basic Commands
The PROMETEU machine defines the audio model, commands, and limits.
Conceptual examples:
The host is responsible for:
```
audio.play(sample, voice, volume, pan, pitch, priority)
audio.stop(voice)
audio.setVolume(voice, v)
audio.setPan(voice, p)
audio.setPitch(voice, p)
audio.isPlaying(voice)
```
- choosing the concrete audio backend;
- scheduling buffer delivery;
- keeping PCM output continuous without changing logical behavior.
---
## 12. Audio and CAP
## 10 Audio and CAP
Audio participates in the Execution CAP:
@ -277,51 +174,3 @@ voices_active: 9
mix_cycles: 410
audio_commands: 6
```
---
## 13. Best Practices
Recommended:
- reuse samples
- limit simultaneous voices
- treat sound as an event
- separate music and effects
Avoid:
- playing sound every frame
- abusing voices
- giant samples for simple effects
---
## 14. Historical Inspiration
The PROMETEU model is inspired by:
- NES: fixed channels
- SNES: sample playback + mixing
- CPS2: comfortable polyphony
- Neo Geo: heavy samples (not fully copied)
But abstracted for:
- clarity
- simplicity
- teaching
---
## 15. Summary
- Output: stereo PCM16 @ 48kHz
- 16 voices
- mono PCM16 samples
- Volume, pan, pitch
- Linear interpolation
- Explicit mixer
- "Audio CPU" concept
- Implementation is the host's role

View File

@ -1,38 +1,22 @@
# Input Peripheral (Input System)
## 1. Overview
Domain: virtual hardware: input
Function: normative
The **INPUT Peripheral** is responsible for **collecting and providing the state of controls** to the PROMETEU program.
Didactic companion: [`../learn/input-mental-model.md`](../learn/input-mental-model.md)
In PROMETEU:
## 1 Scope
- input is **state**, not an implicit event
- input is **sampled over time**, not delivered asynchronously
- input has a **defined order, cost, and moment**
This chapter defines the runtime-facing input contract of PROMETEU.
> Buttons do not “trigger events”.
> They change state.
>
Core contract:
---
- input is exposed as state, not asynchronous callback flow;
- sampling occurs at a defined moment in the logical frame;
- queries are deterministic during the frame;
- logical identifiers are stable across host devices.
## 2. Philosophy of the Input System
PROMETEU models input like classic hardware:
- the state of controls is read **once per frame**
- the program queries this state during `UPDATE`
- there are no asynchronous input callbacks
This model:
- is deterministic
- is simple to understand
- reflects microcontrollers and classic consoles
---
## 3. Input Devices
## 2 Input Devices
PROMETEU abstracts different devices into a common interface.
@ -43,13 +27,11 @@ Typical devices:
- gamepad
- touch (mobile, mapped)
Regardless of the origin, PROMETEU exposes **the same logical model**.
Regardless of source, PROMETEU exposes the same logical model.
---
## 3 State Model
## 4. State Model
### 4.1 Per-Frame State
### 3.1 Per-Frame State
For each frame, the system maintains:
@ -62,9 +44,7 @@ This allows querying:
- button released
- button held down
---
### 4.2 Query Types
### 3.2 Query Types
Typical operations:
@ -80,9 +60,7 @@ These functions:
- do not change state
- have an explicit cost
---
## 5. Sampling Moment
## 4 Sampling Moment
The input state is captured **at the beginning of each frame**, before the `UPDATE` phase.
@ -102,12 +80,7 @@ Throughout the entire frame:
- the input state is immutable
- repeated calls return the same value
> Input does not change in the middle of the frame.
>
---
## 6. Determinism and Reproducibility
## 5 Determinism and Reproducibility
The PROMETEU input model guarantees:
@ -127,9 +100,7 @@ Input can be:
- played back
- artificially injected
---
## 7. Input and CAP
## 6 Input and CAP
Input operations:
@ -146,11 +117,9 @@ input.btn():12cycles
Although cheap, input **is not free**.
---
## 7 Button Mapping
## 8. Button Mapping
### 8.1 Logical Identifiers
### 7.1 Logical Identifiers
PROMETEU defines logical button identifiers:
@ -164,9 +133,7 @@ The physical mapping:
- is resolved outside the VM
- is transparent to the program
---
### 8.2 Portability
### 7.2 Portability
The same PROMETEU cartridge:
@ -176,9 +143,7 @@ The same PROMETEU cartridge:
Without any code changes.
---
## 9. Analog Input (Optional)
## 8 Analog Input (Optional)
PROMETEU can expose analog axes explicitly:
@ -197,60 +162,3 @@ Analog input:
- is not mandatory
- does not replace digital input
- must be used consciously
---
## 10. Input Best Practices
PROMETEU encourages:
- treating input as state
- querying input only in `UPDATE`
- separating input from heavy logic
- mapping actions, not keys
And discourages:
- logic dependent on excessive polling
- reading input in DRAW
- direct coupling to physical hardware
---
## 11. Relationship with Classic Consoles
The PROMETEU model reflects:
- reading input registers
- per-frame polling
- absence of asynchronous events
This model:
- simplifies reasoning
- increases predictability
- facilitates debugging
---
## 12. Pedagogical Implications
The INPUT Peripheral allows teaching:
- the difference between event and state
- temporal sampling
- determinism in interactive systems
- synchronization between input and logic
With clear and reproducible feedback.
---
## 13. Summary
- input is state, not an event
- sampled once per frame
- immutable during the frame
- queries have an explicit cost
- input participates in the CAP
- model is deterministic

View File

@ -1,52 +1,23 @@
# Touch Peripheral (Absolute Pointer Input System)
## 1. Overview
Domain: virtual hardware: touch
Function: normative
The **TOUCH** peripheral provides PROMETEU with an **absolute pointer**, based on screen coordinates, intended for:
Didactic companion: [`../learn/touch-mental-model.md`](../learn/touch-mental-model.md)
- UI interaction
- direct element selection
- contextual actions in the scenery
- drag-based mechanics (drag, slash, trail)
## 1 Scope
The TOUCH is a **first-class peripheral**, as valid as D-Pad and buttons.
This chapter defines the runtime-facing TOUCH contract of PROMETEU.
---
Core contract:
## 2. Design Principles
- one absolute pointer at a time;
- framebuffer-aligned coordinates;
- per-frame state exposure;
- no gesture semantics;
- no acceleration or smoothing semantics.
TOUCH in PROMETEU follows strict principles:
- ✅ **Universal single-touch**
- ✅ **Deterministic**
- ✅ **Per-frame state**
- ✅ **No gestures**
- ✅ **No acceleration**
- ✅ **No heuristics**
- ✅ **Same behavior on all platforms**
> If a behavior cannot be guaranteed on all platforms, it does not exist in PROMETEU.
>
---
## 3. Conceptual Model
PROMETEU exposes **only one active pointer at a time**, regardless of how many physical touches the hardware recognizes.
- Hardware may detect multitouch
- Runtime selects **only one active touch**
- The API **never exposes multitouch**
This model guarantees:
- total portability
- predictability
- absence of ambiguities
---
## 4. Coordinate Space
## 2 Coordinate Space
- TOUCH coordinates use **the same space as the framebuffer**
- Resolution: **320×180**
@ -57,14 +28,12 @@ This model guarantees:
TOUCH is **absolute**:
> (x, y) represents the exact position of contact, without dynamic transformation.
>
- `(x, y)` represents the current contact position after normalization;
- the runtime does not apply dynamic transformation to that coordinate pair.
---
## 3 TOUCH Peripheral API
## 5. TOUCH Peripheral API
### 5.1 Exposed Structure
### 3.1 Exposed Structure
```
TOUCH:
@ -76,10 +45,7 @@ TOUCH:
y : int
```
---
### 5.2 Field Semantics
### 3.2 Field Semantics
- **present**
- `true` if the TOUCH peripheral is available
@ -94,17 +60,13 @@ TOUCH:
- current position of the active pointer
- valid only when `down == true`
---
## 6. Pointer Selection Policy
## 4 Pointer Selection Policy
### *Single Pointer Capture Policy*
When multiple physical touches occur, PROMETEU applies the following policy:
---
### 6.1 Initial Capture
### 4.1 Initial Capture
1. If **no pointer is active**
2. And a **new physical touch** occurs
@ -116,9 +78,7 @@ This frame generates:
- `pressed = true`
- `down = true`
---
### 6.2 Capture Maintenance
### 4.2 Capture Maintenance
While the active pointer is pressed:
@ -126,9 +86,7 @@ While the active pointer is pressed:
- All other physical touches are ignored
- `x, y` follow only the active pointer
---
### 6.3 Release
### 4.3 Release
When the active pointer is released:
@ -136,21 +94,14 @@ When the active pointer is released:
- `down = false`
- The system enters a **no active pointer** state
---
### 6.4 Recapture (Important Rule)
### 4.4 Recapture
After release:
- Touches that **were already present** are ignored
- A new pointer is only captured with a **new touch event**
> This avoids unexpected pointer jumps and accidental actions.
>
---
## 7. Deliberately NOT Supported Behaviors
## 5 Deliberately Unsupported Behaviors
The TOUCH peripheral **does not implement**:
@ -172,9 +123,7 @@ If a game wants any of these behaviors, it must:
- using only per-frame state
- without implicit hardware support
---
## 8. “No Gesture” — Formal Definition
## 6 “No Gesture” — Formal Definition
PROMETEU **does not interpret temporal patterns**.
@ -192,9 +141,7 @@ It only reports:
All semantics are the game's responsibility.
---
## 9. “No Acceleration” — Formal Definition
## 7 “No Acceleration” — Formal Definition
PROMETEU **does not modify** the TOUCH input.
@ -204,9 +151,7 @@ PROMETEU **does not modify** the TOUCH input.
The relationship between the physical touch and `(x, y)` is **1:1** after normalization.
---
## 10. Integration with Other Input Forms
## 8 Integration with Other Input Forms
- Desktop:
- mouse can emulate TOUCH
@ -217,42 +162,10 @@ The relationship between the physical touch and `(x, y)` is **1:1** after normal
- PROMETEU Hardware:
- optional touch, but supported
From PROMETEU's point of view:
> TOUCH is always TOUCH.
>
---
## 11. Expected Uses
The TOUCH peripheral is suitable for:
- UI (menus, inventory, maps)
- drag-and-drop
- direct selection
- “click to investigate”
- pointing-based puzzles
- trail mechanics (e.g.: Fruit Ninja-like)
---
## 12. Portability Guarantees
## 9 Portability Guarantees
Every PROMETEU game that uses TOUCH:
- behaves identically on all platforms
- does not depend on host-specific capabilities
- does not suffer semantic variation between desktop, mobile, and dedicated hardware
---
## 13. Summary
The TOUCH in PROMETEU is:
- simple
- explicit
- predictable
- universal
- deterministic

View File

@ -1,45 +1,28 @@
# Save Memory and MEMCARD
## 1. Overview
Domain: virtual hardware: save memory
Function: normative
The **MEMCARD** is the peripheral responsible for the **explicit persistence of game data** in PROMETEU.
Didactic companion: [`../learn/save-memory-and-memcard.md`](../learn/save-memory-and-memcard.md)
It simulates the behavior of classic *memory cards* (PS1, GameCube), providing:
## 1 Scope
- limited storage
- explicit I/O cost
- full game control over when to save
- portability across platforms
This chapter defines the runtime-facing persistent save surface of PROMETEU.
The MEMCARD **is not a save state**.
The MEMCARD contract is:
It represents **data that the game itself decides to persist**.
- explicit persistence controlled by the game;
- fixed capacity determined by profile;
- host-backed slot storage;
- mandatory `commit()` to persist writes;
- explicit cost and integrity metadata.
---
Current model:
## 2. Design Principles
- Slot A is the required primary save device;
- additional slots remain future-facing surface.
The MEMCARD peripheral follows these principles:
- ✅ **Explicit persistence** (nothing automatic)
- ✅ **Limited and known size**
- ✅ **Mandatory commit**
- ✅ **Measurable time cost (cycles)**
- ✅ **Stable and documented format**
- ✅ **Platform independent**
- ❌ No complex file system (in v0.1)
- ❌ No multiple internal files (in v0.1)
---
## 3. Conceptual Model
Each PROMETEU cartridge can access **one or more MEMCARD slots**, the default model being:
- **Slot A** — main
- **Slot B** — optional (future)
Each slot corresponds to **a file on the host**:
Each slot corresponds to a host file such as:
```
MyGame_A.mem
@ -48,13 +31,11 @@ MyGame_B.mem
The runtime mounts this file as a **persistent storage device**.
---
## 4. Capacity and CAP
## 2 Capacity and CAP
The size of the MEMCARD is **fixed**, defined by the execution profile (CAP).
### Suggested sizes
### 2.1 Suggested sizes
| Profile | Size |
| --- | --- |
@ -66,11 +47,9 @@ The game **cannot exceed** this size.
Attempts to write above the limit result in an error.
---
## 3 Peripheral API (v0.1)
## 5. Peripheral API (v0.1)
### 5.1 Logical Interface
### 3.1 Logical Interface
The MEMCARD exposes a **simple single-blob API**:
@ -82,49 +61,37 @@ mem.clear()
mem.size() -> int
```
---
### 3.2 Operation Semantics
### 5.2 Operation Semantics
### `read_all()`
#### `read_all()`
- Returns all persisted content
- If the card is empty, returns a zeroed buffer
- Cycle cost proportional to size
---
### `write_all(bytes)`
#### `write_all(bytes)`
- Writes the buffer **to temporary memory**
- Does not persist immediately
- Fails if `bytes.length > mem.size()`
---
### `commit()`
#### `commit()`
- Persists data to the device
- **Mandatory** operation
- Simulates hardware flush
- May fail (e.g., I/O, simulated corruption)
---
### `clear()`
#### `clear()`
- Zeroes the card content
- Requires `commit()` to persist
---
### `size()`
#### `size()`
- Returns total card capacity in bytes
---
## 6. Explicit Commit (Fundamental Rule)
## 4 Explicit Commit Rule
PROMETEU **does not save automatically**.
@ -134,20 +101,11 @@ Without `commit()`:
- can be lost upon exiting the game
- simulates abrupt hardware shutdown
👉 This teaches:
- data flushing
- atomicity
- risk of corruption
- real cost of persistence
---
## 7. Execution Cost (Cycles)
## 5 Execution Cost (Cycles)
All MEMCARD operations have an explicit cost.
### Example (illustrative values)
### 5.1 Example (illustrative values)
| Operation | Cost |
| --- | --- |
@ -161,13 +119,11 @@ These costs appear:
- in the frame timeline
- in the CAP report
---
## 8. `.mem` File Format
## 6 `.mem` File Format
The MEMCARD file has a simple and robust format.
### 8.1 Header
### 6.1 Header
| Field | Size |
| --- | --- |
@ -177,17 +133,13 @@ The MEMCARD file has a simple and robust format.
| Payload Size | 4 bytes |
| CRC32 | 4 bytes |
---
### 8.2 Payload
### 6.2 Payload
- Binary buffer defined by the game
- Fixed size
- Content interpreted only by the game
---
## 9. Integrity and Security
## 7 Integrity and Security
- CRC validates corruption
- Cart ID prevents using wrong save
@ -195,40 +147,3 @@ The MEMCARD file has a simple and robust format.
- Runtime can:
- warn of corruption
- allow card reset
---
## 10. Integration with the Editor / GUI
The main tool can provide a **Memory Card Manager**:
- create/reset card
- see size and usage
- import/export `.mem`
- visualize last commits
- associate cards with projects
None of these operations change the runtime.
---
## 11. Planned Evolutions (outside v0.1)
- Block API (`read_block`, `write_block`)
- multiple internal slots
- wear simulation
- save versioning
- optional encryption (educational)
---
## 12. Summary
The MEMCARD peripheral in PROMETEU:
- simulates real hardware
- forces design decisions
- teaches persistence correctly
- is simple to use
- is hard to abuse
- grows without breaking compatibility

View File

@ -1,5 +1,8 @@
# Events and Scheduling
Domain: machine events and frame scheduling
Function: normative
This chapter defines events, timers, faults, and the frame-boundary model of the PROMETEU machine.
Coroutine lifecycle and cooperative scheduling details now live in a dedicated companion chapter.

View File

@ -1,5 +1,8 @@
# Coroutines and Cooperative Scheduling
Domain: VM coroutine model
Function: normative
This chapter isolates PROMETEU coroutine semantics from the broader event/frame model.
## 1 Coroutine Model

View File

@ -1,71 +1,42 @@
# Debug, Inspection, and Profiling
## 1. Overview
Domain: machine diagnostics
Function: normative
PROMETEU was designed to **be observed**.
Didactic companion: [`../learn/observability-and-debugging.md`](../learn/observability-and-debugging.md)
Debug, inspection, and profiling **are not optional external tools**
## 1 Scope
they are **integral parts of the machine**.
This chapter defines the machine-visible debugging, inspection, and profiling surface of PROMETEU.
Nothing happens without leaving traces.
It covers:
Nothing consumes resources without being measured.
- execution modes;
- pause and stepping;
- state inspection;
- graphics inspection;
- profiling;
- breakpoints and watchpoints;
- event and fault visibility;
- certification-facing diagnostics.
Nothing fails without explanation.
> PROMETEU does not hide state.
> PROMETEU exposes behavior.
>
---
## 2. Debug Philosophy in PROMETEU
PROMETEU follows three fundamental debug principles:
1. **State before abstraction**
The programmer sees the machine before seeing “features”.
2. **Time as first class**
Every action is analyzed in the context of the frame and cycles.
3. **Observation does not alter execution**
Debug never changes the behavior of the system.
---
## 3. Execution Modes
## 2 Execution Modes
PROMETEU operates in three main modes:
### 3.1 Normal Mode
### 2.1 Normal Mode
- continuous execution
- no detailed inspection
- focus on game and experience
---
### 3.2 Debug Mode
### 2.2 Debug Mode
- controlled execution
- access to internal state
- pauses and stepping
This mode is used for:
- learning
- investigation
- error correction
---
### 3.3 Certification Mode
### 2.3 Certification Mode
- deterministic execution
- collected metrics
@ -73,11 +44,9 @@ This mode is used for:
No mode alters the logical result of the program.
---
## 3 Execution Debug
## 4. Execution Debug
### 4.1 Pause and Resume
### 3.1 Pause and Resume
The system can be paused at safepoints:
@ -92,9 +61,7 @@ During pause:
- buffers are not swapped
- logical time does not advance
---
### 4.2 Step-by-Step
### 3.2 Step-by-Step
PROMETEU allows stepping at different levels:
@ -109,11 +76,9 @@ Stepping by instruction reveals:
- operand stack
- call stack
---
## 4 State Inspection
## 5. State Inspection
### 5.1 Stacks
### 4.1 Stacks
PROMETEU allows inspecting:
@ -126,11 +91,7 @@ For each frame:
- depth
- growth and cleanup
Stack overflow and underflow are immediately visible.
---
### 5.2 Heap
### 4.2 Heap
The heap can be inspected in real time:
@ -145,9 +106,7 @@ The programmer can observe:
- fragmentation
- GC pressure
---
### 5.3 Global Space
### 4.3 Global Space
Global variables:
@ -155,11 +114,7 @@ Global variables:
- references
- initialization
Globals are visible as **static RAM**.
---
## 6. Graphics Debug
## 5 Graphics Debug
PROMETEU allows inspecting the graphics system:
@ -174,11 +129,9 @@ It is possible to:
- observe buffers separately
- identify excessive redraw
---
## 6 Time Profiling (Cycles)
## 7. Time Profiling (Cycles)
### 7.1 Per-Frame Measurement
### 6.1 Per-Frame Measurement
For each frame, PROMETEU records:
@ -197,9 +150,7 @@ AUDIO:920
SYSTEM:612
```
---
### 7.2 Per-Function Profiling
### 6.2 Per-Function Profiling
PROMETEU can associate cycles with:
@ -207,14 +158,7 @@ PROMETEU can associate cycles with:
- methods
- logical blocks
This allows answering:
> “where is the time being spent?”
>
---
### 7.3 Per-Instruction Profiling
### 6.3 Per-Instruction Profiling
At the lowest level, the system can display:
@ -222,15 +166,7 @@ At the lowest level, the system can display:
- individual cost
- frequency
This level is especially useful for:
- VM teaching
- deep optimization
- bytecode analysis
---
## 8. Memory Profiling
## 7 Memory Profiling
PROMETEU records:
@ -250,11 +186,9 @@ Limit:32KB
These data directly feed the certification.
---
## 8 Breakpoints and Watchpoints
## 9. Breakpoints and Watchpoints
### 9.1 Breakpoints
### 8.1 Breakpoints
PROMETEU supports breakpoints in:
@ -268,9 +202,7 @@ Breakpoints:
- preserve state
- do not change behavior
---
### 9.2 Watchpoints
### 8.2 Watchpoints
Watchpoints monitor:
@ -283,9 +215,7 @@ Execution can pause when:
- a value changes
- a limit is exceeded
---
## 10. Event and Fault Debugging
## 9 Event and Fault Debugging
PROMETEU allows observing:
@ -300,47 +230,10 @@ Each event has:
- cost
- consequence
Nothing happens “silently”.
---
## 11. Integration with CAP and Certification
## 10 Integration with CAP and Certification
All debug and profiling data:
- feed the certification report
- are collected deterministically
- do not depend on external tools
The final report is:
- reproducible
- auditable
- explainable
---
## 12. Pedagogical Use
This system allows teaching:
- how to debug real systems
- how to read metrics
- how to correlate time and memory
- how to justify technical decisions
The student learns:
> debug is not trial and error,
> it is informed observation.
>
---
## 13. Summary
- debug is part of the system
- inspection is complete
- profiling is deterministic
- time and memory are visible
- certification is evidence-based

View File

@ -1,43 +1,24 @@
# Portability Guarantees and Cross-Platform Execution
## 1. Overview
Domain: portability contract
Function: normative
PROMETEU was designed from the beginning to be **portable by construction**, not by later adaptation.
Didactic companion: [`../learn/portability-and-cross-platform.md`](../learn/portability-and-cross-platform.md)
A PROMETEU cartridge:
## 1 Scope
- executes the same way on any supported platform
- produces the same results for the same inputs
- maintains predictable technical behavior
This chapter defines the portability contract of the PROMETEU machine across supported hosts.
> PROMETEU does not depend on the platform.
> The platform depends on PROMETEU.
>
Portability means:
This chapter defines the system's **portability contract**.
- same cartridge;
- same machine rules;
- same logical inputs;
- same logical results.
---
The contract is about logical behavior, not identical physical latency or throughput.
## 2. Fundamental Principle of Portability
Portability in PROMETEU is based on a simple rule:
> Only the PROMETEU VM defines the program's behavior.
>
This means:
- source languages do not matter after compilation
- real hardware does not influence logic
- the operating system does not change semantics
Everything that does not belong to the VM is **adaptation**, not execution.
---
## 3. Separation of Responsibilities
PROMETEU strictly separates three layers:
## 2 Separation of Responsibilities
```
+----------------------------+
@ -56,7 +37,7 @@ PROMETEU strictly separates three layers:
+----------------------------+
```
### What the VM controls
### 2.1 What the machine controls
- bytecode execution
- logical time (frames, cycles)
@ -64,18 +45,16 @@ PROMETEU strictly separates three layers:
- determinism
- costs and metrics
### What the platform provides
### 2.2 What the host provides
- pixel display
- audio output
- physical input collection
- access to the sandbox file system
The platform **never decides behavior**.
The host provides realization of machine surfaces. It does not redefine cartridge semantics.
---
## 4. Determinism as the Basis of Portability
## 3 Determinism as the Basis of Portability
PROMETEU guarantees determinism through:
@ -85,14 +64,7 @@ PROMETEU guarantees determinism through:
- absence of implicit concurrency
- absence of system-dependent operations
This allows stating:
> “If the cartridge is the same, the game is the same.”
>
---
## 5. Independence from Real Hardware
## 4 Independence from Real Hardware
PROMETEU **does not use**:
@ -103,14 +75,7 @@ PROMETEU **does not use**:
All performance is measured in **PROMETEU cycles**, not in milliseconds.
The real hardware:
- only executes the VM
- never interferes with semantics
---
## 6. Floating Point Precision
## 5 Floating Point Precision
To guarantee numerical consistency:
@ -124,9 +89,7 @@ This avoids:
- unpredictable cumulative errors
- subtle differences between platforms
---
## 7. Cross-Platform Input
## 6 Cross-Platform Input
PROMETEU abstracts physical input into **logical state**.
@ -134,14 +97,7 @@ PROMETEU abstracts physical input into **logical state**.
- the cartridge only sees logical buttons and axes
- the reading moment is fixed per frame
The same cartridge:
- reacts the same way on PC, mobile, or console
- does not contain device-dependent logic
---
## 8. Cross-Platform Audio
## 7 Cross-Platform Audio
The audio system:
@ -155,9 +111,7 @@ Hardware differences:
- do not change sound sequence
- do not affect certification
---
## 9. Cross-Platform Graphics
## 8 Cross-Platform Graphics
The graphics system:
@ -170,11 +124,7 @@ The platform layer:
- only displays the framebuffer
- does not reinterpret graphics commands
PROMETEU **does not delegate graphics decisions to the hardware**.
---
## 10. File System and Persistence
## 9 File System and Persistence
PROMETEU defines a **sandbox logical filesystem**:
@ -190,9 +140,7 @@ The platform maps this filesystem to:
Without changing semantics.
---
## 11. Certification and Portability
## 10 Certification and Portability
The **PROMETEU Certification** is valid for all platforms.
@ -206,14 +154,7 @@ It:
- will pass on all
- will produce the same reports
This is possible because:
> the certification validates the VM, not the environment.
>
---
## 12. What PROMETEU DOES NOT guarantee
## 11 What PROMETEU Does Not Guarantee
PROMETEU **does not promise**:
@ -225,30 +166,3 @@ PROMETEU promises:
- **identical logical behavior**
- **reproducible technical decisions**
---
## 13. Pedagogical Implications
This model allows teaching:
- the difference between logic and presentation
- why modern engines break determinism
- how to isolate systems
- how to design portable software
The student learns:
> portability is not luck — it is architecture.
>
---
## 14. Summary
- PROMETEU defines behavior in the VM
- platforms only execute
- time is logical, not physical
- input, audio, and graphics are abstracted
- certification is universal
- portability is guaranteed by design

View File

@ -1,5 +1,8 @@
# Firmware - POS and PrometeuHub
Domain: firmware and system orchestration
Function: normative
This chapter defines the firmware layer of the PROMETEU machine.
It covers:

View File

@ -1,5 +1,8 @@
# Cartridges
Domain: cartridge package
Function: normative
This chapter defines the cartridge contract consumed by the current runtime.
## 1 Scope

View File

@ -1,5 +1,8 @@
# Boot Profiles
Domain: firmware boot flow
Function: normative
This chapter defines how PROMETEU chooses what to execute at startup.
## 1 Boot Target

View File

@ -1,5 +1,8 @@
# Asset Management
Domain: asset runtime surface
Function: normative
This chapter defines the runtime-facing asset model of PROMETEU.
## 1 Scope

View File

@ -1,5 +1,8 @@
# Host ABI and Syscalls
Domain: host ABI structure
Function: normative
This chapter defines the structural ABI between the PVM and the host environment.
It focuses on:

View File

@ -1,5 +1,8 @@
# Syscall Policies
Domain: host ABI operational policy
Function: normative
This chapter defines the operational policies that sit on top of the host ABI.
It complements [`16-host-abi-and-syscalls.md`](16-host-abi-and-syscalls.md), which defines the structural ABI itself.

View File

@ -1,48 +1,116 @@
# PROMETEU Runtime Specs
# PROMETEU Machine Specs
Este diretório reúne as specs da maquina PROMETEU no nível de sistema, hardware virtual, firmware, cartridge e ABI de host.
Este diretório reúne as specs técnicas da máquina PROMETEU.
PROMETEU não é apenas a VM. A VM é um subsistema da fantasy handheld / fantasy console. As specs aqui descrevem a maquina maior e sua superfície técnica.
PROMETEU é uma fantasy handheld / fantasy console. A VM é apenas um subsistema dessa máquina. Por isso, esta superfície documental cobre mais do que bytecode e runtime: ela cobre tempo, hardware virtual, firmware, cartridge, assets e ABI com o host.
Princípios desta organização:
A organização aqui é intencionalmente plana. A taxonomia é conceitual, não estrutural.
## Scope Boundary
Pertence a `docs/runtime/specs/`:
- contrato técnico da máquina PROMETEU;
- hardware virtual e seus periféricos;
- envelope de firmware e boot;
- cartridge, assets e superfícies de carga;
- ABI da VM com o host.
Não pertence a `docs/runtime/specs/` como fonte canônica principal:
- invariantes arquiteturais internas da VM/runtime:
[`../virtual-machine/ARCHITECTURE.md`](../virtual-machine/ARCHITECTURE.md);
- ISA em nível de bytecode:
[`../virtual-machine/ISA_CORE.md`](../virtual-machine/ISA_CORE.md);
- guias didáticos e material de aprendizagem:
[`../learn/README.md`](../learn/README.md);
- agendas, propostas e planos:
`docs/runtime/agendas/` e `docs/runtime/pull-requests/`.
## Organization Rules
- estrutura plana;
- sem pasta `topics/`;
- sem navegação embutida `Back` / `Next` / `Summary`;
- nomes de arquivos semânticos;
- cada capítulo deve poder ser aberto isoladamente.
- cada capítulo deve poder ser aberto isoladamente;
- cada capítulo deve declarar seu domínio e sua função documental no topo do arquivo;
- a taxonomia deve viver no `README`, não em uma árvore de diretórios artificial.
Arquivos atuais:
## Taxonomy
- [`01-time-model-and-cycles.md`](01-time-model-and-cycles.md)
- [`02-vm-instruction-set.md`](02-vm-instruction-set.md)
- [`02a-vm-values-and-calling-convention.md`](02a-vm-values-and-calling-convention.md)
- [`02b-vm-function-values-and-closures.md`](02b-vm-function-values-and-closures.md)
- [`03-memory-stack-heap-and-allocation.md`](03-memory-stack-heap-and-allocation.md)
- [`04-gfx-peripheral.md`](04-gfx-peripheral.md)
- [`05-audio-peripheral.md`](05-audio-peripheral.md)
- [`06-input-peripheral.md`](06-input-peripheral.md)
- [`07-touch-peripheral.md`](07-touch-peripheral.md)
- [`08-save-memory-and-memcard.md`](08-save-memory-and-memcard.md)
- [`09-events-and-concurrency.md`](09-events-and-concurrency.md)
- [`09a-coroutines-and-cooperative-scheduling.md`](09a-coroutines-and-cooperative-scheduling.md)
- [`10-debug-inspection-and-profiling.md`](10-debug-inspection-and-profiling.md)
- [`11-portability-and-cross-platform-execution.md`](11-portability-and-cross-platform-execution.md)
- [`12-firmware-pos-and-prometeuhub.md`](12-firmware-pos-and-prometeuhub.md)
- [`13-cartridge.md`](13-cartridge.md)
- [`14-boot-profiles.md`](14-boot-profiles.md)
- [`15-asset-management.md`](15-asset-management.md)
- [`16-host-abi-and-syscalls.md`](16-host-abi-and-syscalls.md)
- [`16a-syscall-policies.md`](16a-syscall-policies.md)
| Range | Domain |
| --- | --- |
| `01` | machine timing and cycle budget |
| `02` to `03`, `09a`, `16` to `16a` | VM subsystem and host ABI |
| `04` to `08` | virtual hardware peripherals |
| `09` to `11` | machine execution envelope, diagnostics, and portability |
| `12` and `14` | firmware and boot orchestration |
| `13` and `15` | cartridge package and asset surface |
Relação com outros docs:
Hardware, aqui, não é um saco genérico para tudo. No pacote atual, “hardware” significa os periféricos virtuais da máquina: GFX, AUDIO, INPUT, TOUCH e MEMCARD/save memory. VM, firmware, cartridge e ABI ficam em categorias irmãs, não dentro da categoria de hardware.
- [`../virtual-machine/ARCHITECTURE.md`](../virtual-machine/ARCHITECTURE.md) define as invariantes canônicas da VM/runtime.
- [`../virtual-machine/ISA_CORE.md`](../virtual-machine/ISA_CORE.md) define a ISA no nível de bytecode.
- As specs deste diretório podem aprofundar o modelo da máquina, mas não devem contradizer as invariantes canônicas da VM/runtime quando tratarem dessa camada.
## Document Functions
Critério para novos capítulos:
- `normative`: define contrato técnico, comportamento esperado ou superfície compatível com implementação.
- `mixed (normative + explanatory)`: contém contrato técnico, mas preserva framing didático para explicar o modelo da máquina.
- `historical`: material arquivado; não é autoridade para implementação nova.
- `pedagogical`: material de ensino; não define sozinho contrato técnico.
No estado atual, nenhum capítulo sob a raiz ativa de `docs/runtime/specs/` é `historical` puro. Se material histórico surgir, ele não deve competir com a superfície normativa principal.
## Current Chapter Map
| File | Domain | Function |
| --- | --- | --- |
| [`01-time-model-and-cycles.md`](01-time-model-and-cycles.md) | machine timing and cycles | normative |
| [`02-vm-instruction-set.md`](02-vm-instruction-set.md) | VM subsystem overview | normative |
| [`02a-vm-values-and-calling-convention.md`](02a-vm-values-and-calling-convention.md) | VM values and calling convention | normative |
| [`02b-vm-function-values-and-closures.md`](02b-vm-function-values-and-closures.md) | VM closures and function values | normative |
| [`03-memory-stack-heap-and-allocation.md`](03-memory-stack-heap-and-allocation.md) | VM memory model | normative |
| [`04-gfx-peripheral.md`](04-gfx-peripheral.md) | virtual hardware: graphics | normative |
| [`05-audio-peripheral.md`](05-audio-peripheral.md) | virtual hardware: audio | normative |
| [`06-input-peripheral.md`](06-input-peripheral.md) | virtual hardware: input | normative |
| [`07-touch-peripheral.md`](07-touch-peripheral.md) | virtual hardware: touch | normative |
| [`08-save-memory-and-memcard.md`](08-save-memory-and-memcard.md) | virtual hardware: save memory | normative |
| [`09-events-and-concurrency.md`](09-events-and-concurrency.md) | machine events and frame scheduling | normative |
| [`09a-coroutines-and-cooperative-scheduling.md`](09a-coroutines-and-cooperative-scheduling.md) | VM coroutine model | normative |
| [`10-debug-inspection-and-profiling.md`](10-debug-inspection-and-profiling.md) | machine diagnostics | normative |
| [`11-portability-and-cross-platform-execution.md`](11-portability-and-cross-platform-execution.md) | portability contract | normative |
| [`12-firmware-pos-and-prometeuhub.md`](12-firmware-pos-and-prometeuhub.md) | firmware and system orchestration | normative |
| [`13-cartridge.md`](13-cartridge.md) | cartridge package | normative |
| [`14-boot-profiles.md`](14-boot-profiles.md) | firmware boot flow | normative |
| [`15-asset-management.md`](15-asset-management.md) | asset runtime surface | normative |
| [`16-host-abi-and-syscalls.md`](16-host-abi-and-syscalls.md) | host ABI structure | normative |
| [`16a-syscall-policies.md`](16a-syscall-policies.md) | host ABI operational policy | normative |
## Authority Model
- `docs/runtime/specs/` define a máquina PROMETEU e suas superfícies externas de execução.
- [`../virtual-machine/ARCHITECTURE.md`](../virtual-machine/ARCHITECTURE.md) continua sendo a autoridade canônica das invariantes internas da VM/runtime.
- [`../virtual-machine/ISA_CORE.md`](../virtual-machine/ISA_CORE.md) continua sendo a autoridade para a ISA de bytecode.
- Quando um capítulo daqui tocar a VM, ele pode complementar, mas não contradizer, a arquitetura canônica da VM/runtime.
## Rules for Future Chapters
- o nome do arquivo deve comunicar o domínio;
- o capítulo deve ser legível sem depender de trilha de navegação;
- links internos devem ser usados apenas quando agregarem contexto real, não como mecanismo obrigatório de leitura sequencial.
- o capítulo deve declarar `Domain` e `Function` no topo;
- capítulos sobre hardware devem tratar de periféricos ou superfícies de máquina observáveis, não de qualquer tema técnico solto;
- capítulos históricos ou puramente pedagógicos não devem disputar autoridade com capítulos normativos;
- links internos devem agregar contexto real, não servir como navegação obrigatória.
## Pairing Rule
Um tema deve nascer como par `spec` + `learn` quando:
- o contrato normativo é importante, mas o modelo mental também é;
- o texto precisa de contexto histórico, comparação com hardware clássico ou design rationale extenso;
- o material didático ameaça inflar ou confundir o capítulo normativo;
- o assunto serve tanto como superfície técnica quanto como ferramenta de ensino.
Nesses casos:
- `docs/runtime/specs/` define o contrato;
- `docs/runtime/learn/` explica o porquê, a intuição e os exemplos;
- o spec deve apontar para o companion didático no topo;
- o guia didático deve apontar de volta para o spec canônico.