translate to english!
This commit is contained in:
@@ -1,14 +1,14 @@
|
||||
# PROMETEU Core
|
||||
|
||||
Este crate contém a biblioteca central que define o comportamento do hardware e software do PROMETEU.
|
||||
This crate contains the core library that defines the behavior of PROMETEU's hardware and software.
|
||||
|
||||
## Responsabilidades
|
||||
## Responsibilities
|
||||
|
||||
- **Hardware Lógico**: Definição de GFX, Input, Audio e Touch.
|
||||
- **Máquina Virtual**: Execução de bytecode customizado (PBC - Prometeu Byte Code).
|
||||
- **Virtual FS**: Gerenciamento de arquivos e acesso ao "cartucho".
|
||||
- **Firmware/OS**: O sistema operacional interno que gerencia o ciclo de vida das aplicações, splash screens e o Hub Home.
|
||||
- **Logical Hardware**: Definition of GFX, Input, Audio, and Touch.
|
||||
- **Virtual Machine**: Execution of custom bytecode (PBC - Prometeu Byte Code).
|
||||
- **Virtual FS**: File management and "cartridge" access.
|
||||
- **Firmware/OS**: The internal operating system that manages the application lifecycle, splash screens, and the Hub Home.
|
||||
|
||||
## Arquitetura
|
||||
## Architecture
|
||||
|
||||
O core é projetado para ser determinístico e portátil. Ele não faz chamadas diretas ao sistema operacional do host; em vez disso, define traços (traits) que os hosts devem implementar (ex: `FsBackend`).
|
||||
The core is designed to be deterministic and portable. It does not make direct calls to the host operating system; instead, it defines traits that hosts must implement (e.g., `FsBackend`).
|
||||
|
||||
@@ -31,7 +31,7 @@ impl Firmware {
|
||||
}
|
||||
|
||||
pub fn step_frame(&mut self, signals: &InputSignals, hw: &mut dyn HardwareBridge) {
|
||||
// Atualiza input uma vez por frame de host
|
||||
// Updates input once per host frame
|
||||
hw.pad_mut().begin_frame(signals);
|
||||
hw.touch_mut().begin_frame(signals);
|
||||
|
||||
@@ -50,7 +50,7 @@ impl Firmware {
|
||||
self.state = new_state;
|
||||
self.state_initialized = false;
|
||||
|
||||
// Entra no novo estado imediatamente
|
||||
// Enters the new state immediately
|
||||
self.on_enter(signals, hw);
|
||||
self.state_initialized = true;
|
||||
}
|
||||
|
||||
@@ -14,16 +14,16 @@ impl AppCrashesStep {
|
||||
}
|
||||
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
// Atualiza periféricos para input na tela de crash
|
||||
// Update peripherals for input on the crash screen
|
||||
ctx.hw.pad_mut().begin_frame(ctx.signals);
|
||||
|
||||
// Tela de erro: fundo vermelho, texto branco
|
||||
// Error screen: red background, white text
|
||||
ctx.hw.gfx_mut().clear(Color::RED);
|
||||
// Por enquanto apenas logamos ou mostramos algo simples
|
||||
// No futuro, usar draw_text
|
||||
// For now we just log or show something simple
|
||||
// In the future, use draw_text
|
||||
ctx.hw.gfx_mut().present();
|
||||
|
||||
// Se apertar START, volta pro Hub
|
||||
// If START is pressed, return to the Hub
|
||||
if ctx.hw.pad().start.down {
|
||||
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
||||
}
|
||||
|
||||
@@ -13,19 +13,19 @@ impl HubHomeStep {
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
let mut error = None;
|
||||
|
||||
// Sempre atualiza a GUI do Hub (limpa a tela e processa input se não houver foco)
|
||||
// Always updates the Hub GUI (clears screen and processes input if no focus)
|
||||
ctx.hub.gui_update(ctx.os, ctx.hw);
|
||||
|
||||
if let Some(focused_id) = ctx.hub.window_manager.focused {
|
||||
if ctx.hw.pad().start.down {
|
||||
ctx.hub.window_manager.remove_window(focused_id);
|
||||
} else {
|
||||
// System App roda aqui, desenhando sobre o fundo do Hub
|
||||
// System App runs here, drawing over the Hub background
|
||||
error = ctx.os.step_frame(ctx.vm, ctx.signals, ctx.hw);
|
||||
}
|
||||
}
|
||||
|
||||
// Renderiza as bordas das janelas do System App
|
||||
// Renders the System App window borders
|
||||
ctx.hub.render(ctx.os, ctx.hw);
|
||||
|
||||
ctx.hw.gfx_mut().present();
|
||||
|
||||
@@ -17,8 +17,8 @@ impl LaunchHubStep {
|
||||
if let BootTarget::Cartridge { path, .. } = ctx.boot_target {
|
||||
match CartridgeLoader::load(path) {
|
||||
Ok(cartridge) => {
|
||||
// No caso de debug, aqui poderíamos pausar, mas o requisito diz
|
||||
// para o Runtime abrir o socket e aguardar.
|
||||
// In the case of debug, we could pause here, but the requirement says
|
||||
// for the Runtime to open the socket and wait.
|
||||
return Some(FirmwareState::LoadCartridge(LoadCartridgeStep { cartridge }));
|
||||
}
|
||||
Err(e) => {
|
||||
|
||||
@@ -23,8 +23,8 @@ impl LoadCartridgeStep {
|
||||
);
|
||||
ctx.hub.window_manager.set_focus(id);
|
||||
|
||||
// Apps de sistema não mudam o estado do firmware para GameRunning.
|
||||
// Eles rodam em background ou via janelas no Hub.
|
||||
// System apps do not change the firmware state to GameRunning.
|
||||
// They run in the background or via windows in the Hub.
|
||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||
}
|
||||
|
||||
|
||||
@@ -12,23 +12,23 @@ pub struct SplashScreenStep {
|
||||
impl SplashScreenStep {
|
||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Showing SplashScreen".to_string());
|
||||
// Tocar som no enter
|
||||
// Play sound on enter
|
||||
if let Some(sample) = ctx.os.sample_square.clone() {
|
||||
ctx.hw.audio_mut().play(sample, 0, 255, 127, 1.0, 0, LoopMode::Off);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
const ANIMATION_DURATION: u32 = 60; // 1 segundo a 60fps
|
||||
const TOTAL_DURATION: u32 = 240; // 2 segundos totais (conforme ctxuisito anterior)
|
||||
const ANIMATION_DURATION: u32 = 60; // 1 second at 60fps
|
||||
const TOTAL_DURATION: u32 = 240; // 4 seconds total (updated from 2s based on total_duration logic)
|
||||
|
||||
// Atualiza periféricos para input
|
||||
// Update peripherals for input
|
||||
ctx.hw.pad_mut().begin_frame(ctx.signals);
|
||||
|
||||
// Limpar tela
|
||||
// Clear screen
|
||||
ctx.hw.gfx_mut().clear(Color::BLACK);
|
||||
|
||||
// Desenhar quadrado aumentando
|
||||
// Draw expanding square
|
||||
let (sw, sh) = ctx.hw.gfx().size();
|
||||
let max_size = (sw.min(sh) as i32 / 2).max(1);
|
||||
|
||||
@@ -44,8 +44,8 @@ impl SplashScreenStep {
|
||||
ctx.hw.gfx_mut().fill_rect(x, y, current_size, current_size, Color::WHITE);
|
||||
ctx.hw.gfx_mut().present();
|
||||
|
||||
// Lógica de transição
|
||||
// Caso o botão start seja pressionado a qualquer momento depois da animação terminar
|
||||
// Transition logic
|
||||
// If any button is pressed at any time after the animation ends
|
||||
if self.frame >= ANIMATION_DURATION && ctx.hw.pad().any() {
|
||||
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ impl Audio {
|
||||
}
|
||||
}
|
||||
|
||||
/// Limpa a fila de comandos. O Host deve consumir isso a cada frame.
|
||||
/// Clears the command queue. The Host should consume this every frame.
|
||||
pub fn clear_commands(&mut self) {
|
||||
self.commands.clear();
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ pub struct Gfx {
|
||||
pub hud_fade_level: u8, // 0..31
|
||||
pub hud_fade_color: Color,
|
||||
|
||||
// Cache de prioridades para evitar alocações por frame
|
||||
// Priority cache to avoid per-frame allocations
|
||||
priority_buckets: [Vec<usize>; 5],
|
||||
}
|
||||
|
||||
@@ -51,17 +51,19 @@ impl Gfx {
|
||||
};
|
||||
|
||||
let len = w * h;
|
||||
let mut layers = [
|
||||
ScrollableTileLayer::new(64, 64, TileSize::Size16),
|
||||
ScrollableTileLayer::new(64, 64, TileSize::Size16),
|
||||
ScrollableTileLayer::new(64, 64, TileSize::Size16),
|
||||
ScrollableTileLayer::new(64, 64, TileSize::Size16),
|
||||
];
|
||||
|
||||
Self {
|
||||
w,
|
||||
h,
|
||||
front: vec![0; len],
|
||||
back: vec![0; len],
|
||||
layers: [
|
||||
ScrollableTileLayer::new(64, 64, TileSize::Size16),
|
||||
ScrollableTileLayer::new(64, 64, TileSize::Size16),
|
||||
ScrollableTileLayer::new(64, 64, TileSize::Size16),
|
||||
ScrollableTileLayer::new(64, 64, TileSize::Size16),
|
||||
],
|
||||
layers,
|
||||
hud: HudTileLayer::new(64, 32),
|
||||
banks: [EMPTY_BANK; 16],
|
||||
sprites: [EMPTY_SPRITE; 512],
|
||||
@@ -83,7 +85,7 @@ impl Gfx {
|
||||
(self.w, self.h)
|
||||
}
|
||||
|
||||
/// O buffer que o host deve exibir (RGB565).
|
||||
/// The buffer that the host should display (RGB565).
|
||||
pub fn front_buffer(&self) -> &[u16] {
|
||||
&self.front
|
||||
}
|
||||
@@ -92,7 +94,7 @@ impl Gfx {
|
||||
self.back.fill(color.0);
|
||||
}
|
||||
|
||||
/// Retângulo com modo de blend.
|
||||
/// Rectangle with blend mode.
|
||||
pub fn fill_rect_blend(
|
||||
&mut self,
|
||||
x: i32,
|
||||
@@ -122,21 +124,21 @@ impl Gfx {
|
||||
}
|
||||
}
|
||||
|
||||
/// Conveniência: retângulo normal (sem blend).
|
||||
/// Convenience: normal rectangle (no blend).
|
||||
pub fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color) {
|
||||
self.fill_rect_blend(x, y, w, h, color, BlendMode::None);
|
||||
}
|
||||
|
||||
/// Double buffer swap (O(1), sem cópia de pixels).
|
||||
/// Double buffer swap (O(1), no pixel copying).
|
||||
pub fn present(&mut self) {
|
||||
std::mem::swap(&mut self.front, &mut self.back);
|
||||
}
|
||||
|
||||
/// Pipeline principal de renderização do frame.
|
||||
/// Segue a ordem de prioridade do manual (Capítulo 4.11).
|
||||
/// Main frame rendering pipeline.
|
||||
/// Follows the priority order from the manual (Chapter 4.11).
|
||||
pub fn render_all(&mut self) {
|
||||
// 0. Fase de Preparação: Organiza quem deve ser desenhado em cada camada
|
||||
// Limpa os buckets sem desalocar memória
|
||||
// 0. Preparation Phase: Organizes what should be drawn in each layer
|
||||
// Clears the buckets without deallocating memory
|
||||
for bucket in self.priority_buckets.iter_mut() {
|
||||
bucket.clear();
|
||||
}
|
||||
@@ -147,27 +149,27 @@ impl Gfx {
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Sprites de prioridade 0 (Atrás da Layer 0 - o fundo do fundo)
|
||||
// 1. Priority 0 sprites (Behind Layer 0 - the very back)
|
||||
Self::draw_bucket_on_buffer(&mut self.back, self.w, self.h, &self.priority_buckets[0], &self.sprites, &self.banks);
|
||||
|
||||
for i in 0..self.layers.len() {
|
||||
// 2. Layers de jogo (0 a 3)
|
||||
// 2. Game Layers (0 to 3)
|
||||
let bank_id = self.layers[i].bank_id as usize;
|
||||
if let Some(Some(bank)) = self.banks.get(bank_id) {
|
||||
Self::draw_tile_map(&mut self.back, self.w, self.h, &self.layers[i].map, bank, self.layers[i].scroll_x, self.layers[i].scroll_y);
|
||||
}
|
||||
|
||||
// 3. Sprites de acordo com prioridade
|
||||
// 3. Sprites according to priority
|
||||
Self::draw_bucket_on_buffer(&mut self.back, self.w, self.h, &self.priority_buckets[i + 1], &self.sprites, &self.banks);
|
||||
}
|
||||
|
||||
// 4. Aplica Scene Fade (Afeta tudo desenhado até agora)
|
||||
// 4. Applies Scene Fade (Affects everything drawn so far)
|
||||
Self::apply_fade_to_buffer(&mut self.back, self.scene_fade_level, self.scene_fade_color);
|
||||
|
||||
// 5. HUD (Sempre por cima)
|
||||
// 5. HUD (Always on top)
|
||||
self.render_hud();
|
||||
|
||||
// 6. Aplica HUD Fade (Opcional, apenas para o HUD)
|
||||
// 6. Applies HUD Fade (Optional, HUD only)
|
||||
Self::apply_fade_to_buffer(&mut self.back, self.hud_fade_level, self.hud_fade_color);
|
||||
}
|
||||
|
||||
@@ -186,7 +188,7 @@ impl Gfx {
|
||||
Self::draw_tile_map(&mut self.back, self.w, self.h, &self.layers[layer_idx].map, bank, scroll_x, scroll_y);
|
||||
}
|
||||
|
||||
/// Renderiza o HUD (sem scroll).
|
||||
/// Renders the HUD (no scroll).
|
||||
pub fn render_hud(&mut self) {
|
||||
let bank_id = self.hud.bank_id as usize;
|
||||
let bank = match self.banks.get(bank_id) {
|
||||
@@ -208,30 +210,30 @@ impl Gfx {
|
||||
) {
|
||||
let tile_size = bank.tile_size as usize;
|
||||
|
||||
// 1. Calcular quantos tiles cabem na tela (com margem de 1 para o scroll)
|
||||
// 1. Calculate how many tiles fit on the screen (with margin of 1 for scroll)
|
||||
let visible_tiles_x = (screen_w / tile_size) + 1;
|
||||
let visible_tiles_y = (screen_h / tile_size) + 1;
|
||||
|
||||
// 2. Calcular o offset inicial (onde o primeiro tile começa a ser desenhado)
|
||||
// 2. Calculate the initial offset (where the first tile starts being drawn)
|
||||
let start_tile_x = scroll_x / tile_size as i32;
|
||||
let start_tile_y = scroll_y / tile_size as i32;
|
||||
|
||||
let fine_scroll_x = scroll_x % tile_size as i32;
|
||||
let fine_scroll_y = scroll_y % tile_size as i32;
|
||||
|
||||
// 3. Loop por Tile (Muito mais eficiente)
|
||||
// 3. Loop by Tile (Much more efficient)
|
||||
for ty in 0..visible_tiles_y {
|
||||
for tx in 0..visible_tiles_x {
|
||||
let map_x = (start_tile_x + tx as i32) as usize;
|
||||
let map_y = (start_tile_y + ty as i32) as usize;
|
||||
|
||||
// Skip se estiver fora dos limites do mapa
|
||||
// Skip if outside map bounds
|
||||
if map_x >= map.width || map_y >= map.height { continue; }
|
||||
|
||||
let tile = map.tiles[map_y * map.width + map_x];
|
||||
if tile.id == 0 { continue; }
|
||||
|
||||
// 4. Desenha o bloco do tile na tela
|
||||
// 4. Draws the tile block on the screen
|
||||
let screen_tile_x = (tx as i32 * tile_size as i32) - fine_scroll_x;
|
||||
let screen_tile_y = (ty as i32 * tile_size as i32) - fine_scroll_y;
|
||||
|
||||
@@ -240,7 +242,7 @@ impl Gfx {
|
||||
}
|
||||
}
|
||||
|
||||
// Função auxiliar para desenhar um bloco de 8x8, 16x16 ou 32x32 pixels
|
||||
// Helper function to draw a block of 8x8, 16x16 or 32x32 pixels
|
||||
fn draw_tile_pixels(back: &mut [u16], screen_w: usize, screen_h: usize, x: i32, y: i32, tile: crate::model::Tile, bank: &TileBank) {
|
||||
let size = bank.tile_size as usize;
|
||||
|
||||
@@ -255,13 +257,13 @@ impl Gfx {
|
||||
let fetch_x = if tile.flip_x { size - 1 - local_x } else { local_x };
|
||||
let fetch_y = if tile.flip_y { size - 1 - local_y } else { local_y };
|
||||
|
||||
// 1. Pega o índice do pixel no banco
|
||||
// 1. Gets the pixel index in the bank
|
||||
let px_index = bank.get_pixel_index(tile.id, fetch_x, fetch_y);
|
||||
|
||||
// 2. Regra: Índice 0 é transparente
|
||||
// 2. Rule: Index 0 is transparent
|
||||
if px_index == 0 { continue; }
|
||||
|
||||
// 3. Resolve a cor usando a paleta do tile
|
||||
// 3. Resolves the color using the tile's palette
|
||||
let color = bank.resolve_color(tile.palette_id, px_index);
|
||||
|
||||
back[world_y as usize * screen_w + world_x as usize] = color.raw();
|
||||
@@ -293,7 +295,7 @@ impl Gfx {
|
||||
sprite: &Sprite,
|
||||
bank: &TileBank
|
||||
) {
|
||||
// ... (mesmo cálculo de bounds/clipping que já tínhamos) ...
|
||||
// ... (same bounds/clipping calculation we already had) ...
|
||||
let size = bank.tile_size as usize;
|
||||
let start_x = sprite.x.max(0);
|
||||
let start_y = sprite.y.max(0);
|
||||
@@ -308,13 +310,13 @@ impl Gfx {
|
||||
let fetch_x = if sprite.flip_x { size - 1 - local_x } else { local_x };
|
||||
let fetch_y = if sprite.flip_y { size - 1 - local_y } else { local_y };
|
||||
|
||||
// 1. Pega o índice
|
||||
// 1. Get index
|
||||
let px_index = bank.get_pixel_index(sprite.tile.id, fetch_x, fetch_y);
|
||||
|
||||
// 2. Transparência
|
||||
// 2. Transparency
|
||||
if px_index == 0 { continue; }
|
||||
|
||||
// 3. Resolve cor via paleta (do tile dentro do sprite)
|
||||
// 3. Resolve color via palette (from the tile inside the sprite)
|
||||
let color = bank.resolve_color(sprite.tile.palette_id, px_index);
|
||||
|
||||
back[world_y as usize * screen_w + world_x as usize] = color.raw();
|
||||
@@ -322,10 +324,10 @@ impl Gfx {
|
||||
}
|
||||
}
|
||||
|
||||
/// Aplica o efeito de fade em todo o back buffer.
|
||||
/// level: 0 (cor total) até 31 (visível)
|
||||
/// Applies the fade effect to the entire back buffer.
|
||||
/// level: 0 (full color) to 31 (visible)
|
||||
fn apply_fade_to_buffer(back: &mut [u16], level: u8, fade_color: Color) {
|
||||
if level >= 31 { return; } // Totalmente visível, pula processamento
|
||||
if level >= 31 { return; } // Fully visible, skip processing
|
||||
|
||||
let weight = level as u16;
|
||||
let inv_weight = 31 - weight;
|
||||
@@ -334,7 +336,7 @@ impl Gfx {
|
||||
for px in back.iter_mut() {
|
||||
let (sr, sg, sb) = Color::unpack_to_native(*px);
|
||||
|
||||
// Fórmula: (src * weight + fade * inv_weight) / 31
|
||||
// Formula: (src * weight + fade * inv_weight) / 31
|
||||
let r = ((sr as u16 * weight + fr as u16 * inv_weight) / 31) as u8;
|
||||
let g = ((sg as u16 * weight + fg as u16 * inv_weight) / 31) as u8;
|
||||
let b = ((sb as u16 * weight + fb as u16 * inv_weight) / 31) as u8;
|
||||
@@ -343,19 +345,19 @@ impl Gfx {
|
||||
}
|
||||
}
|
||||
|
||||
/// Retorna o uso real de memória das estruturas gráficas em bytes.
|
||||
/// Reflete os buffers de índices, paletas e OAM conforme Capítulo 10.8.
|
||||
/// Returns the actual memory usage of the graphics structures in bytes.
|
||||
/// Reflects index buffers, palettes, and OAM as per Chapter 10.8.
|
||||
pub fn memory_usage_bytes(&self) -> usize {
|
||||
let mut total = 0;
|
||||
|
||||
// 1. Framebuffers (Front + Back)
|
||||
// Cada um é Vec<u16>, ocupando 2 bytes por pixel.
|
||||
// Each is Vec<u16>, occupying 2 bytes per pixel.
|
||||
total += self.front.len() * 2;
|
||||
total += self.back.len() * 2;
|
||||
|
||||
// 2. Tile Layers (4 Game Layers)
|
||||
for layer in &self.layers {
|
||||
// Tamanho da struct + os dados do mapa (Vec<Tile>)
|
||||
// Struct size + map data (Vec<Tile>)
|
||||
total += size_of::<ScrollableTileLayer>();
|
||||
total += layer.map.tiles.len() * size_of::<crate::model::Tile>();
|
||||
}
|
||||
@@ -364,19 +366,19 @@ impl Gfx {
|
||||
total += size_of::<HudTileLayer>();
|
||||
total += self.hud.map.tiles.len() * size_of::<crate::model::Tile>();
|
||||
|
||||
// 4. Tile Banks (Assets e Paletas)
|
||||
// 4. Tile Banks (Assets and Palettes)
|
||||
for bank_opt in &self.banks {
|
||||
if let Some(bank) = bank_opt {
|
||||
total += size_of::<TileBank>();
|
||||
total += bank.pixel_indices.len();
|
||||
|
||||
// Tabela de Paletas: 256 paletas * 16 cores * tamanho da struct Color
|
||||
// Palette Table: 256 palettes * 16 colors * Color struct size
|
||||
total += 256 * 16 * size_of::<Color>();
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Sprites (OAM)
|
||||
// Array fixo de 512 Sprites.
|
||||
// Fixed array of 512 Sprites.
|
||||
total += self.sprites.len() * size_of::<Sprite>();
|
||||
|
||||
total
|
||||
@@ -457,8 +459,8 @@ impl Gfx {
|
||||
}
|
||||
}
|
||||
|
||||
/// Faz blend em RGB565 por canal com saturação.
|
||||
/// `dst` e `src` são pixels RGB565 (u16).
|
||||
/// Blends in RGB565 per channel with saturation.
|
||||
/// `dst` and `src` are RGB565 pixels (u16).
|
||||
fn blend_rgb565(dst: u16, src: u16, mode: BlendMode) -> u16 {
|
||||
match mode {
|
||||
BlendMode::None => src,
|
||||
|
||||
@@ -9,7 +9,7 @@ pub struct Touch {
|
||||
}
|
||||
|
||||
impl Touch {
|
||||
/// Flags transitórias devem durar apenas 1 frame.
|
||||
/// Transient flags should last only 1 frame.
|
||||
pub fn begin_frame(&mut self, signals: &InputSignals) {
|
||||
self.f.begin_frame(signals.f_signal);
|
||||
self.x = signals.x_pos.clone();
|
||||
|
||||
@@ -85,7 +85,7 @@ mod tests {
|
||||
service.log(i as u64, 1, LogLevel::Info, LogSource::Pos, 0, format!("Log {}", i));
|
||||
}
|
||||
|
||||
let after = service.get_after(2); // seqs são 0, 1, 2, 3, 4. Deve retornar 3 e 4.
|
||||
let after = service.get_after(2); // seqs are 0, 1, 2, 3, 4. Should return 3 and 4.
|
||||
assert_eq!(after.len(), 2);
|
||||
assert_eq!(after[0].msg, "Log 3");
|
||||
assert_eq!(after[1].msg, "Log 4");
|
||||
|
||||
@@ -33,7 +33,7 @@ impl DirectoryCartridgeLoader {
|
||||
let manifest_content = fs::read_to_string(manifest_path).map_err(|_| CartridgeError::IoError)?;
|
||||
let manifest: CartridgeManifest = serde_json::from_str(&manifest_content).map_err(|_| CartridgeError::InvalidManifest)?;
|
||||
|
||||
// Validação adicional conforme requisitos
|
||||
// Additional validation as per requirements
|
||||
if manifest.magic != "PMTU" {
|
||||
return Err(CartridgeError::InvalidManifest);
|
||||
}
|
||||
@@ -73,7 +73,6 @@ pub struct PackedCartridgeLoader;
|
||||
|
||||
impl PackedCartridgeLoader {
|
||||
pub fn load(_path: &Path) -> Result<Cartridge, CartridgeError> {
|
||||
// Stub inicialmente, como solicitado
|
||||
Err(CartridgeError::InvalidFormat)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/// Cor simples em RGB565 (0bRRRRRGGGGGGBBBBB).
|
||||
/// Simple RGB565 color (0bRRRRRGGGGGGBBBBB).
|
||||
/// - 5 bits Red
|
||||
/// - 6 bits Green
|
||||
/// - 5 bits Blue
|
||||
///
|
||||
/// Não há canal alpha.
|
||||
/// Transparência é tratada via Color Key ou Blend Mode.
|
||||
/// There is no alpha channel.
|
||||
/// Transparency is handled via Color Key or Blend Mode.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Color(pub u16);
|
||||
|
||||
@@ -23,7 +23,7 @@ impl Color {
|
||||
pub const COLOR_KEY: Self = Self::MAGENTA;
|
||||
pub const TRANSPARENT: Self = Self::MAGENTA;
|
||||
|
||||
/// Extrai canais já na faixa nativa do RGB565:
|
||||
/// Extracts channels in the native RGB565 range:
|
||||
/// R: 0..31, G: 0..63, B: 0..31
|
||||
#[inline(always)]
|
||||
pub const fn unpack_to_native(px: u16) -> (u8, u8, u8) {
|
||||
@@ -33,14 +33,14 @@ impl Color {
|
||||
(r, g, b)
|
||||
}
|
||||
|
||||
/// Incorpora canais já na faixa nativa do RGB565 em um pixel:
|
||||
/// Packs channels from the native RGB565 range into a pixel:
|
||||
/// R: 0..31, G: 0..63, B: 0..31
|
||||
#[inline(always)]
|
||||
pub const fn pack_from_native(r: u8, g: u8, b: u8) -> u16 {
|
||||
((r as u16 & 0x1F) << 11) | ((g as u16 & 0x3F) << 5) | (b as u16 & 0x1F)
|
||||
}
|
||||
|
||||
/// Cria uma cor RGB565 a partir de componentes 8-bit (0..255).
|
||||
/// Creates an RGB565 color from 8-bit components (0..255).
|
||||
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
|
||||
let r5 = (r as u16 >> 3) & 0x1F;
|
||||
let g6 = (g as u16 >> 2) & 0x3F;
|
||||
|
||||
@@ -9,13 +9,12 @@ pub enum TileSize {
|
||||
|
||||
pub struct TileBank {
|
||||
pub tile_size: TileSize,
|
||||
pub width: usize, // em pixels
|
||||
pub height: usize, // em pixels
|
||||
// pub pixels: Vec<Color>,
|
||||
pub width: usize, // in pixels
|
||||
pub height: usize, // in pixels
|
||||
|
||||
/// Agora guardamos índices de 0 a 15 (4 bits por pixel simulados em 8 bits)
|
||||
/// Now we store indices from 0 to 15 (4 bits per pixel simulated in 8 bits)
|
||||
pub pixel_indices: Vec<u8>,
|
||||
/// 256 paletas, cada uma com 16 cores (RGB565 como u16)
|
||||
/// 256 palettes, each with 16 colors (RGB565 as u16)
|
||||
pub palettes: [[Color; 16]; 256],
|
||||
}
|
||||
|
||||
@@ -25,14 +24,14 @@ impl TileBank {
|
||||
tile_size,
|
||||
width,
|
||||
height,
|
||||
pixel_indices: vec![0; width * height], // Índice 0 = Transparente
|
||||
pixel_indices: vec![0; width * height], // Index 0 = Transparent
|
||||
palettes: [[Color::BLACK; 16]; 256],
|
||||
}
|
||||
}
|
||||
|
||||
/// Retorna a cor de um pixel específico dentro de um tile.
|
||||
/// tile_id: o índice do tile no banco
|
||||
/// local_x, local_y: a posição do pixel dentro do tile (0 até tile_size-1)
|
||||
/// Returns the color of a specific pixel inside a tile.
|
||||
/// tile_id: the tile index in the bank
|
||||
/// local_x, local_y: the pixel position inside the tile (0 to tile_size-1)
|
||||
pub fn get_pixel_index(&self, tile_id: u16, local_x: usize, local_y: usize) -> u8 {
|
||||
let size = self.tile_size as usize;
|
||||
let tiles_per_row = self.width / size;
|
||||
@@ -45,13 +44,13 @@ impl TileBank {
|
||||
if pixel_x < self.width && pixel_y < self.height {
|
||||
self.pixel_indices[pixel_y * self.width + pixel_x]
|
||||
} else {
|
||||
0 // Fora do banco = Transparente
|
||||
0 // Outside the bank = Transparent
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve um índice de pixel para uma Color real usando uma paleta.
|
||||
/// Resolves a pixel index to a real Color using a palette.
|
||||
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Color {
|
||||
// Regra: Índice 0 é sempre transparente (usamos MAGENTA/COLOR_KEY como vácuo)
|
||||
// Rule: Index 0 is always transparent (we use MAGENTA/COLOR_KEY as vacuum)
|
||||
if pixel_index == 0 {
|
||||
return Color::COLOR_KEY;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::log::{LogLevel, LogSource};
|
||||
use crate::model::{Color, Rect, Window, WindowId};
|
||||
use crate::prometeu_os::PrometeuOS;
|
||||
|
||||
/// Gerenciador de janelas do PROMETEU.
|
||||
/// PROMETEU Window Manager.
|
||||
pub struct WindowManager {
|
||||
pub windows: Vec<Window>,
|
||||
pub focused: Option<WindowId>,
|
||||
@@ -50,7 +50,7 @@ impl WindowManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// PrometeuHub: Launcher e ambiente de UI do sistema.
|
||||
/// PrometeuHub: Launcher and system UI environment.
|
||||
pub struct PrometeuHub {
|
||||
pub window_manager: WindowManager,
|
||||
}
|
||||
@@ -63,7 +63,7 @@ impl PrometeuHub {
|
||||
}
|
||||
|
||||
pub fn init(&mut self) {
|
||||
// Inicializa o Window System e lista apps
|
||||
// Initializes the Window System and lists apps
|
||||
}
|
||||
|
||||
pub fn gui_update(&mut self, os: &mut PrometeuOS, hw: &mut dyn HardwareBridge) {
|
||||
|
||||
@@ -9,8 +9,8 @@ use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
/// PrometeuOS (POS): O firmware/base do sistema.
|
||||
/// Autoridade máxima do boot, periféricos, execução da PVM e tratamento de falhas.
|
||||
/// PrometeuOS (POS): The system firmware/base.
|
||||
/// Maximum authority for boot, peripherals, PVM execution, and fault handling.
|
||||
pub struct PrometeuOS {
|
||||
pub tick_index: u64,
|
||||
pub logical_frame_index: u64,
|
||||
@@ -18,7 +18,7 @@ pub struct PrometeuOS {
|
||||
pub logical_frame_remaining_cycles: u64,
|
||||
pub last_frame_cpu_time_us: u64,
|
||||
|
||||
// Assets de exemplo (mantidos para compatibilidade com syscalls de áudio v0)
|
||||
// Example assets (kept for compatibility with v0 audio syscalls)
|
||||
pub sample_square: Option<Arc<Sample>>,
|
||||
pub sample_kick: Option<Arc<Sample>>,
|
||||
pub sample_snare: Option<Arc<Sample>>,
|
||||
@@ -37,7 +37,7 @@ pub struct PrometeuOS {
|
||||
pub current_cartridge_app_mode: crate::model::AppMode,
|
||||
pub logs_written_this_frame: HashMap<u32, u32>,
|
||||
|
||||
// Telemetria e Certificação
|
||||
// Telemetry and Certification
|
||||
pub telemetry_current: TelemetryFrame,
|
||||
pub telemetry_last: TelemetryFrame,
|
||||
pub certifier: Certifier,
|
||||
@@ -49,7 +49,7 @@ pub struct PrometeuOS {
|
||||
|
||||
impl PrometeuOS {
|
||||
pub const CYCLES_PER_LOGICAL_FRAME: u64 = 100_000;
|
||||
pub const SLICE_PER_TICK: u64 = 100_000; // Por enquanto, o mesmo, mas permite granularidade diferente
|
||||
pub const SLICE_PER_TICK: u64 = 100_000; // For now the same, but allows different granularity
|
||||
|
||||
pub const MAX_LOG_LEN: usize = 256;
|
||||
pub const MAX_LOGS_PER_FRAME: u32 = 10;
|
||||
@@ -83,7 +83,7 @@ impl PrometeuOS {
|
||||
boot_time,
|
||||
};
|
||||
|
||||
// Inicializa samples básicos (mesma lógica do LogicalHardware)
|
||||
// Initializes basic samples (same logic as LogicalHardware)
|
||||
os.sample_square = Some(Arc::new(Self::create_square_sample(440.0, 0.1)));
|
||||
|
||||
os.log(LogLevel::Info, LogSource::Pos, 0, "PrometeuOS starting...".to_string());
|
||||
@@ -135,18 +135,18 @@ impl PrometeuOS {
|
||||
self.last_frame_cpu_time_us = 0;
|
||||
}
|
||||
|
||||
/// Carrega um cartucho na PVM e reseta o estado de execução.
|
||||
/// Loads a cartridge into the PVM and resets the execution state.
|
||||
pub fn initialize_vm(&mut self, vm: &mut VirtualMachine, cartridge: &Cartridge) {
|
||||
vm.initialize(cartridge.program.clone(), &cartridge.entrypoint);
|
||||
|
||||
// Determina o app_id numérico
|
||||
// Determines the numeric app_id
|
||||
self.current_app_id = cartridge.app_id;
|
||||
self.current_cartridge_title = cartridge.title.clone();
|
||||
self.current_cartridge_app_version = cartridge.app_version.clone();
|
||||
self.current_cartridge_app_mode = cartridge.app_mode;
|
||||
}
|
||||
|
||||
/// Executa uma única instrução da VM (Debug).
|
||||
/// Executes a single VM instruction (Debug).
|
||||
pub fn debug_step_instruction(&mut self, vm: &mut VirtualMachine, hw: &mut dyn HardwareBridge) -> Option<String> {
|
||||
match vm.step(self, hw) {
|
||||
Ok(_) => None,
|
||||
@@ -158,7 +158,7 @@ impl PrometeuOS {
|
||||
}
|
||||
}
|
||||
|
||||
/// Executa um tick do host (60Hz).
|
||||
/// Executes a host tick (60Hz).
|
||||
pub fn step_frame(&mut self, vm: &mut VirtualMachine, signals: &InputSignals, hw: &mut dyn HardwareBridge) -> Option<String> {
|
||||
let start = std::time::Instant::now();
|
||||
self.tick_index += 1;
|
||||
@@ -174,25 +174,25 @@ impl PrometeuOS {
|
||||
self.logical_frame_remaining_cycles = Self::CYCLES_PER_LOGICAL_FRAME;
|
||||
self.begin_logical_frame(signals, hw);
|
||||
|
||||
// Início do frame: resetar acumulador da telemetria (mas manter frame_index)
|
||||
// Beginning of frame: reset telemetry accumulator (but keep frame_index)
|
||||
self.telemetry_current = TelemetryFrame {
|
||||
frame_index: self.logical_frame_index,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
// Budget para este tick: o mínimo entre a fatia do tick e o que resta no frame lógico
|
||||
// Budget for this tick: the minimum between the tick slice and what remains in the logical frame
|
||||
let budget = std::cmp::min(Self::SLICE_PER_TICK, self.logical_frame_remaining_cycles);
|
||||
|
||||
if budget > 0 {
|
||||
// Executa budget
|
||||
// Execute budget
|
||||
let run_result = vm.run_budget(budget, self, hw);
|
||||
|
||||
match run_result {
|
||||
Ok(run) => {
|
||||
self.logical_frame_remaining_cycles = self.logical_frame_remaining_cycles.saturating_sub(run.cycles_used);
|
||||
|
||||
// Acumula métricas
|
||||
// Accumulates metrics
|
||||
self.telemetry_current.cycles_used += run.cycles_used;
|
||||
self.telemetry_current.vm_steps += run.steps_executed;
|
||||
|
||||
@@ -205,14 +205,14 @@ impl PrometeuOS {
|
||||
if run.reason == crate::virtual_machine::LogicalFrameEndingReason::FrameSync {
|
||||
hw.gfx_mut().render_all();
|
||||
|
||||
// Finaliza telemetria do frame (host_cpu_time será refinado no final do tick)
|
||||
// Finalizes frame telemetry (host_cpu_time will be refined at the end of the tick)
|
||||
self.telemetry_current.host_cpu_time_us = start.elapsed().as_micros() as u64;
|
||||
|
||||
// Certificação (CAP)
|
||||
// Certification (CAP)
|
||||
let ts_ms = self.boot_time.elapsed().as_millis() as u64;
|
||||
self.telemetry_current.violations = self.certifier.evaluate(&self.telemetry_current, &mut self.log_service, ts_ms) as u32;
|
||||
|
||||
// Latch: o que o overlay lê
|
||||
// Latch: what the overlay reads
|
||||
self.telemetry_last = self.telemetry_current;
|
||||
|
||||
self.logical_frame_index += 1;
|
||||
@@ -235,7 +235,7 @@ impl PrometeuOS {
|
||||
|
||||
self.last_frame_cpu_time_us = start.elapsed().as_micros() as u64;
|
||||
|
||||
// Se o frame acabou neste tick, atualizamos o tempo real final no latch
|
||||
// If the frame ended in this tick, we update the final real time in the latch
|
||||
if !self.logical_frame_active && self.telemetry_last.frame_index == self.logical_frame_index.wrapping_sub(1) {
|
||||
self.telemetry_last.host_cpu_time_us = self.last_frame_cpu_time_us;
|
||||
}
|
||||
@@ -367,16 +367,16 @@ mod tests {
|
||||
};
|
||||
os.initialize_vm(&mut vm, &cartridge);
|
||||
|
||||
// Primeiro tick
|
||||
// First tick
|
||||
os.step_frame(&mut vm, &signals, &mut hw);
|
||||
let cycles_after_tick_1 = vm.cycles;
|
||||
assert!(cycles_after_tick_1 >= PrometeuOS::CYCLES_PER_LOGICAL_FRAME);
|
||||
|
||||
// Segundo tick - Agora ele NÃO deve ganhar mais budget
|
||||
// Second tick - Now it SHOULD NOT gain more budget
|
||||
os.step_frame(&mut vm, &signals, &mut hw);
|
||||
let cycles_after_tick_2 = vm.cycles;
|
||||
|
||||
// CORREÇÃO: Ele não deve ter consumido ciclos no segundo tick porque o budget do frame lógico acabou
|
||||
// FIX: It should not have consumed cycles in the second tick because the logical frame budget ended
|
||||
println!("Cycles after tick 1: {}, tick 2: {}", cycles_after_tick_1, cycles_after_tick_2);
|
||||
assert_eq!(cycles_after_tick_2, cycles_after_tick_1, "VM should NOT have consumed more cycles in the second tick because logical frame budget is exhausted");
|
||||
}
|
||||
@@ -388,7 +388,7 @@ mod tests {
|
||||
let mut hw = Hardware::new();
|
||||
let signals = InputSignals::default();
|
||||
|
||||
// Loop que chama FrameSync:
|
||||
// Loop that calls FrameSync:
|
||||
// PUSH_CONST 0 (dummy)
|
||||
// FrameSync (0x80)
|
||||
// JMP 0
|
||||
@@ -407,15 +407,15 @@ mod tests {
|
||||
};
|
||||
os.initialize_vm(&mut vm, &cartridge);
|
||||
|
||||
// Primeiro tick
|
||||
// First tick
|
||||
os.step_frame(&mut vm, &signals, &mut hw);
|
||||
let cycles_after_tick_1 = vm.cycles;
|
||||
|
||||
// Deve ter parado no FrameSync
|
||||
// Should have stopped at FrameSync
|
||||
assert!(cycles_after_tick_1 > 0, "VM should have consumed some cycles");
|
||||
assert!(cycles_after_tick_1 < PrometeuOS::CYCLES_PER_LOGICAL_FRAME);
|
||||
|
||||
// Segundo tick - Deve resetar o budget e rodar mais um pouco até o próximo FrameSync
|
||||
// Second tick - Should reset the budget and run a bit more until the next FrameSync
|
||||
os.step_frame(&mut vm, &signals, &mut hw);
|
||||
let cycles_after_tick_2 = vm.cycles;
|
||||
|
||||
@@ -430,7 +430,7 @@ mod tests {
|
||||
|
||||
os.current_app_id = 123;
|
||||
|
||||
// 1. Teste de log normal
|
||||
// 1. Normal log test
|
||||
vm.push(Value::Integer(2)); // Info
|
||||
vm.push(Value::String("Hello Log".to_string()));
|
||||
let res = os.syscall(0x5001, &mut vm, &mut hw);
|
||||
@@ -441,7 +441,7 @@ mod tests {
|
||||
assert_eq!(recent[0].level, LogLevel::Info);
|
||||
assert_eq!(recent[0].source, LogSource::App { app_id: 123 });
|
||||
|
||||
// 2. Teste de truncamento
|
||||
// 2. Truncation test
|
||||
let long_msg = "A".repeat(300);
|
||||
vm.push(Value::Integer(3)); // Warn
|
||||
vm.push(Value::String(long_msg));
|
||||
@@ -451,27 +451,27 @@ mod tests {
|
||||
assert_eq!(recent[0].msg.len(), 256);
|
||||
assert!(recent[0].msg.starts_with("AAAAA"));
|
||||
|
||||
// 3. Teste de Rate Limit
|
||||
// Já fizemos 2 logs. O limite é 10.
|
||||
// 3. Rate Limit Test
|
||||
// We already made 2 logs. The limit is 10.
|
||||
for i in 0..8 {
|
||||
vm.push(Value::Integer(2));
|
||||
vm.push(Value::String(format!("Log {}", i)));
|
||||
os.syscall(0x5001, &mut vm, &mut hw).unwrap();
|
||||
}
|
||||
|
||||
// O 11º log deve ser ignorado (e deve gerar um aviso do sistema)
|
||||
// The 11th log should be ignored (and generate a system warning)
|
||||
vm.push(Value::Integer(2));
|
||||
vm.push(Value::String("Eleventh log".to_string()));
|
||||
os.syscall(0x5001, &mut vm, &mut hw).unwrap();
|
||||
|
||||
let recent = os.log_service.get_recent(2);
|
||||
// O último log deve ser o aviso de rate limit (veio depois do 10º log tentado)
|
||||
// The last log should be the rate limit warning (came after the 10th log attempted)
|
||||
assert_eq!(recent[1].msg, "App exceeded log limit per frame");
|
||||
assert_eq!(recent[1].level, LogLevel::Warn);
|
||||
// O log "Eleventh log" não deve estar lá
|
||||
// The log "Eleventh log" should not be there
|
||||
assert_ne!(recent[0].msg, "Eleventh log");
|
||||
|
||||
// 4. Teste de reset do rate limit no próximo frame
|
||||
// 4. Rate limit reset test in the next frame
|
||||
os.begin_logical_frame(&InputSignals::default(), &mut hw);
|
||||
vm.push(Value::Integer(2));
|
||||
vm.push(Value::String("New frame log".to_string()));
|
||||
@@ -480,7 +480,7 @@ mod tests {
|
||||
let recent = os.log_service.get_recent(1);
|
||||
assert_eq!(recent[0].msg, "New frame log");
|
||||
|
||||
// 5. Teste de LOG_WRITE_TAG
|
||||
// 5. LOG_WRITE_TAG test
|
||||
vm.push(Value::Integer(2)); // Info
|
||||
vm.push(Value::Integer(42)); // Tag
|
||||
vm.push(Value::String("Tagged Log".to_string()));
|
||||
@@ -623,7 +623,7 @@ impl NativeInterface for PrometeuOS {
|
||||
};
|
||||
match self.fs.list_dir(&path) {
|
||||
Ok(entries) => {
|
||||
// Por enquanto, retorna uma string separada por ';'
|
||||
// For now, returns a string separated by ';'
|
||||
let names: Vec<String> = entries.into_iter().map(|e| e.name).collect();
|
||||
vm.push(Value::String(names.join(";")));
|
||||
Ok(500)
|
||||
|
||||
@@ -2,25 +2,25 @@
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(u16)]
|
||||
pub enum OpCode {
|
||||
// 6.1 Controle de Execução
|
||||
// 6.1 Execution Control
|
||||
Nop = 0x00,
|
||||
Halt = 0x01,
|
||||
Jmp = 0x02,
|
||||
JmpIfFalse = 0x03,
|
||||
|
||||
// 6.2 Pilha
|
||||
// 6.2 Stack
|
||||
PushConst = 0x10,
|
||||
Pop = 0x11,
|
||||
Dup = 0x12,
|
||||
Swap = 0x13,
|
||||
|
||||
// 6.3 Aritmética
|
||||
// 6.3 Arithmetic
|
||||
Add = 0x20,
|
||||
Sub = 0x21,
|
||||
Mul = 0x22,
|
||||
Div = 0x23,
|
||||
|
||||
// 6.4 Comparação e Lógica
|
||||
// 6.4 Comparison and Logic
|
||||
Eq = 0x30,
|
||||
Neq = 0x31,
|
||||
Lt = 0x32,
|
||||
@@ -29,13 +29,13 @@ pub enum OpCode {
|
||||
Or = 0x35,
|
||||
Not = 0x36,
|
||||
|
||||
// 6.5 Variáveis
|
||||
// 6.5 Variables
|
||||
GetGlobal = 0x40,
|
||||
SetGlobal = 0x41,
|
||||
GetLocal = 0x42,
|
||||
SetLocal = 0x43,
|
||||
|
||||
// 6.6 Funções
|
||||
// 6.6 Functions
|
||||
Call = 0x50,
|
||||
Ret = 0x51,
|
||||
PushScope = 0x52,
|
||||
@@ -46,7 +46,7 @@ pub enum OpCode {
|
||||
LoadRef = 0x61,
|
||||
StoreRef = 0x62,
|
||||
|
||||
// 6.8 Periféricos e Sistema
|
||||
// 6.8 Peripherals and System
|
||||
Syscall = 0x70,
|
||||
FrameSync = 0x80,
|
||||
}
|
||||
@@ -126,7 +126,7 @@ impl OpCode {
|
||||
OpCode::Alloc => 10,
|
||||
OpCode::LoadRef => 3,
|
||||
OpCode::StoreRef => 3,
|
||||
OpCode::Syscall => 1, // Variável, mas vamos usar 1 como base ou definir via ID
|
||||
OpCode::Syscall => 1, // Variable, but we'll use 1 as base or define via ID
|
||||
OpCode::FrameSync => 1,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ pub enum Value {
|
||||
Float(f64),
|
||||
Boolean(bool),
|
||||
String(String),
|
||||
Ref(usize), // Referência ao heap
|
||||
Ref(usize), // Heap reference
|
||||
Null,
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ pub struct VirtualMachine {
|
||||
pub call_stack: Vec<CallFrame>,
|
||||
pub globals: Vec<Value>,
|
||||
pub program: Program,
|
||||
pub heap: Vec<Value>, // Simplificado para demo, futuramente RAM/Heap real
|
||||
pub heap: Vec<Value>, // Simplified for demo, future real RAM/Heap
|
||||
pub cycles: u64,
|
||||
pub halted: bool,
|
||||
pub breakpoints: std::collections::HashSet<usize>,
|
||||
@@ -56,12 +56,12 @@ impl VirtualMachine {
|
||||
self.program = Program::new(program_bytes, vec![]);
|
||||
}
|
||||
} else {
|
||||
// Por enquanto, tratamos os bytes como a ROM diretamente.
|
||||
// For now, we treat the bytes as the ROM directly.
|
||||
self.program = Program::new(program_bytes, vec![]);
|
||||
}
|
||||
|
||||
// Se o entrypoint for numérico, podemos tentar usá-lo como PC inicial.
|
||||
// Se não, por enquanto ignoramos ou começamos do 0.
|
||||
// If the entrypoint is numeric, we can try to use it as the initial PC.
|
||||
// If not, for now we ignore it or start from 0.
|
||||
if let Ok(addr) = entrypoint.parse::<usize>() {
|
||||
self.pc = addr;
|
||||
} else {
|
||||
@@ -173,7 +173,7 @@ impl VirtualMachine {
|
||||
let pc_before = self.pc;
|
||||
let cycles_before = self.cycles;
|
||||
|
||||
// Fast-path: FRAME_SYNC encerra o frame lógico
|
||||
// Fast-path: FRAME_SYNC ends the logical frame
|
||||
let opcode_val = self.peek_u16()?;
|
||||
let opcode = OpCode::try_from(opcode_val)?;
|
||||
if opcode == OpCode::FrameSync {
|
||||
@@ -187,7 +187,7 @@ impl VirtualMachine {
|
||||
self.step(native, hw)?;
|
||||
steps_executed += 1;
|
||||
|
||||
// garante progresso real
|
||||
// ensures real progress
|
||||
if self.pc == pc_before && self.cycles == cycles_before && !self.halted {
|
||||
return Err(format!("VM stuck at PC 0x{:08X}", self.pc));
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
# PROMETEU Desktop Runtime
|
||||
|
||||
Esta é a implementação de host para plataformas desktop, permitindo que o PROMETEU rode em Windows, Linux e macOS.
|
||||
This is the host implementation for desktop platforms, allowing PROMETEU to run on Windows, Linux, and macOS.
|
||||
|
||||
## Funcionalidades
|
||||
## Features
|
||||
|
||||
- **Renderização**: Utiliza a GPU via biblioteca `pixels` para apresentar o framebuffer de baixa resolução.
|
||||
- **Input**: Traduz eventos de teclado e controle (via `winit`) para os sinais de hardware do PROMETEU.
|
||||
- **Áudio**: Interface com o sistema de som do host (via `cpal`).
|
||||
- **Debugging**: Hospeda um servidor TCP que implementa o **DevTools Protocol**, permitindo conexões de IDEs ou debuggers externos.
|
||||
- **Rendering**: Uses the GPU via the `pixels` library to present the low-resolution framebuffer.
|
||||
- **Input**: Translates keyboard and controller events (via `winit`) into PROMETEU hardware signals.
|
||||
- **Audio**: Interfaces with the host's sound system (via `cpal`).
|
||||
- **Debugging**: Hosts a TCP server that implements the **DevTools Protocol**, allowing connections from external IDEs or debuggers.
|
||||
|
||||
## Como rodar
|
||||
## How to run
|
||||
|
||||
Geralmente executado via CLI principal (`prometeu`), mas pode ser chamado diretamente para testes:
|
||||
Generally executed via the main CLI (`prometeu`), but can be called directly for testing:
|
||||
|
||||
```bash
|
||||
cargo run -- --run path/to/cart
|
||||
|
||||
@@ -39,7 +39,7 @@ impl HostAudio {
|
||||
|
||||
let mut mixer = AudioMixer::new();
|
||||
|
||||
// Para passar dados de performance da thread de áudio para a principal
|
||||
// To pass performance data from the audio thread to the main thread
|
||||
let audio_perf_rb = HeapRb::<u64>::new(64);
|
||||
let (mut perf_prod, perf_cons) = audio_perf_rb.split();
|
||||
|
||||
@@ -47,13 +47,13 @@ impl HostAudio {
|
||||
.build_output_stream(
|
||||
&config,
|
||||
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
|
||||
// Consome comandos da ringbuffer
|
||||
// Consumes commands from ringbuffer
|
||||
while let Some(cmd) = cons.try_pop() {
|
||||
mixer.process_command(cmd);
|
||||
}
|
||||
// Mixa áudio
|
||||
// Mixes audio
|
||||
mixer.fill_buffer(data);
|
||||
// Envia tempo de processamento em microssegundos
|
||||
// Sends processing time in microseconds
|
||||
let _ = perf_prod.try_push(mixer.last_processing_time.as_micros() as u64);
|
||||
},
|
||||
|err| eprintln!("audio stream error: {}", err),
|
||||
@@ -144,7 +144,7 @@ impl AudioMixer {
|
||||
|
||||
pub fn fill_buffer(&mut self, buffer: &mut [f32]) {
|
||||
let start = std::time::Instant::now();
|
||||
// Zera o buffer (estéreo)
|
||||
// Zeroes the buffer (stereo)
|
||||
for sample in buffer.iter_mut() {
|
||||
*sample = 0.0;
|
||||
}
|
||||
@@ -172,7 +172,7 @@ impl AudioMixer {
|
||||
break;
|
||||
}
|
||||
|
||||
// Interpolação Linear
|
||||
// Linear Interpolation
|
||||
let s1 = sample_data.data[pos_int] as f32 / 32768.0;
|
||||
let s2 = if pos_int + 1 < sample_data.data.len() {
|
||||
sample_data.data[pos_int + 1] as f32 / 32768.0
|
||||
@@ -204,7 +204,7 @@ impl AudioMixer {
|
||||
}
|
||||
}
|
||||
|
||||
// Clamp final para evitar clipping (opcional se usarmos f32, mas bom para fidelidade)
|
||||
// Final clamp to avoid clipping (optional if using f32, but good for fidelity)
|
||||
for sample in buffer.iter_mut() {
|
||||
*sample = sample.clamp(-1.0, 1.0);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ impl HostDebugger {
|
||||
if let BootTarget::Cartridge { path, debug: true, debug_port } = boot_target {
|
||||
self.waiting_for_start = true;
|
||||
|
||||
// Pré-carrega informações do cartucho para o handshake
|
||||
// Pre-loads cartridge information for the handshake
|
||||
if let Ok(cartridge) = CartridgeLoader::load(path) {
|
||||
firmware.os.initialize_vm(&mut firmware.vm, &cartridge);
|
||||
}
|
||||
@@ -75,7 +75,7 @@ impl HostDebugger {
|
||||
|
||||
self.stream = Some(stream);
|
||||
|
||||
// Enviar Handshake
|
||||
// Send Handshake
|
||||
let handshake = DebugResponse::Handshake {
|
||||
protocol_version: DEVTOOLS_PROTOCOL_VERSION,
|
||||
runtime_version: "0.1".to_string(),
|
||||
@@ -104,10 +104,10 @@ impl HostDebugger {
|
||||
}
|
||||
Ok(n) => {
|
||||
let data = &buf[..n];
|
||||
// Processar múltiplos comandos se houver \n
|
||||
// Process multiple commands if there's \n
|
||||
let msg = String::from_utf8_lossy(data);
|
||||
|
||||
self.stream = Some(stream); // Coloca de volta antes de processar comandos
|
||||
self.stream = Some(stream); // Put it back before processing commands
|
||||
|
||||
for line in msg.lines() {
|
||||
let trimmed = line.trim();
|
||||
@@ -154,7 +154,7 @@ impl HostDebugger {
|
||||
}
|
||||
DebugCommand::Step => {
|
||||
firmware.os.paused = true;
|
||||
// Executa uma instrução imediatamente
|
||||
// Executes an instruction immediately
|
||||
let _ = firmware.os.debug_step_instruction(&mut firmware.vm, hardware);
|
||||
}
|
||||
DebugCommand::StepFrame => {
|
||||
@@ -192,7 +192,7 @@ impl HostDebugger {
|
||||
for event in new_events {
|
||||
self.last_log_seq = event.seq;
|
||||
|
||||
// Verifica se é um breakpoint hit via tag
|
||||
// Check if it's a breakpoint hit via tag
|
||||
if event.tag == 0xDEB1 {
|
||||
self.send_event(DebugEvent::BreakpointHit {
|
||||
pc: firmware.vm.pc,
|
||||
@@ -200,7 +200,7 @@ impl HostDebugger {
|
||||
});
|
||||
}
|
||||
|
||||
// Certificação via Tags 0xCA01-0xCA03
|
||||
// Certification via Tags 0xCA01-0xCA03
|
||||
if event.tag >= 0xCA01 && event.tag <= 0xCA03 {
|
||||
let rule = match event.tag {
|
||||
0xCA01 => "cycles_budget",
|
||||
@@ -211,7 +211,7 @@ impl HostDebugger {
|
||||
|
||||
self.send_event(DebugEvent::Cert {
|
||||
rule,
|
||||
used: 0, // Simplificado, informações detalhadas estão na msg do log
|
||||
used: 0, // Simplified, detailed information is in the log message
|
||||
limit: 0,
|
||||
frame_index: firmware.os.logical_frame_index,
|
||||
});
|
||||
|
||||
@@ -21,7 +21,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut debug_mode = false;
|
||||
let mut debug_port = 7777;
|
||||
|
||||
let mut i = 1; // Pula o nome do executável
|
||||
let mut i = 1; // Skip the executable name
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--run" => {
|
||||
|
||||
@@ -95,7 +95,7 @@ impl HostRunner {
|
||||
fn display_dbg_overlay(&mut self) {
|
||||
let tel = &self.firmware.os.telemetry_last;
|
||||
let color_text = prometeu_core::model::Color::WHITE;
|
||||
let color_bg = prometeu_core::model::Color::INDIGO; // Azul escuro para destacar
|
||||
let color_bg = prometeu_core::model::Color::INDIGO; // Dark blue to stand out
|
||||
let color_warn = prometeu_core::model::Color::RED;
|
||||
|
||||
self.hardware.gfx.fill_rect(5, 5, 140, 65, color_bg);
|
||||
@@ -129,7 +129,7 @@ impl ApplicationHandler for HostRunner {
|
||||
|
||||
let window = event_loop.create_window(attrs).expect("failed to create window");
|
||||
|
||||
// 🔥 Leak: Window vira &'static Window (bootstrap)
|
||||
// 🔥 Leak: Window becomes &'static Window (bootstrap)
|
||||
let window: &'static Window = Box::leak(Box::new(window));
|
||||
self.window = Some(window);
|
||||
|
||||
@@ -165,18 +165,18 @@ impl ApplicationHandler for HostRunner {
|
||||
}
|
||||
|
||||
WindowEvent::RedrawRequested => {
|
||||
// Pegue o Pixels diretamente do campo (não via helper que pega &mut self inteiro)
|
||||
// Get Pixels directly from the field (not via helper that gets the entire &mut self)
|
||||
let pixels = self.pixels.as_mut().expect("pixels not initialized");
|
||||
|
||||
{
|
||||
// Borrow mutável do frame (dura só dentro deste bloco)
|
||||
// Mutable borrow of the frame (lasts only within this block)
|
||||
let frame = pixels.frame_mut();
|
||||
|
||||
// Borrow imutável do prometeu-core (campo diferente, ok)
|
||||
// Immutable borrow of prometeu-core (different field, ok)
|
||||
let src = self.hardware.gfx.front_buffer();
|
||||
|
||||
draw_rgb565_to_rgba8(src, frame);
|
||||
} // <- frame borrow termina aqui
|
||||
} // <- frame borrow ends here
|
||||
|
||||
if pixels.render().is_err() {
|
||||
event_loop.exit();
|
||||
@@ -206,7 +206,7 @@ impl ApplicationHandler for HostRunner {
|
||||
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
self.debugger.check_commands(&mut self.firmware, &mut self.hardware);
|
||||
|
||||
// Atualiza estado do Filesystem no OS (específico do prometeu-runtime-desktop)
|
||||
// Updates Filesystem state in OS (specific to prometeu-runtime-desktop)
|
||||
if let Some(root) = &self.fs_root {
|
||||
use prometeu_core::fs::FsState;
|
||||
if matches!(self.firmware.os.fs_state, FsState::Unmounted | FsState::Error(_)) {
|
||||
@@ -220,7 +220,7 @@ impl ApplicationHandler for HostRunner {
|
||||
let now = Instant::now();
|
||||
let mut frame_delta = now.duration_since(self.last_frame_time);
|
||||
|
||||
// Limitador para evitar a "espiral da morte" se o SO travar (máximo de 100ms por volta)
|
||||
// Limiter to avoid the "death spiral" if the OS freezes (max 100ms per loop)
|
||||
if frame_delta > Duration::from_millis(100) {
|
||||
frame_delta = Duration::from_millis(100);
|
||||
}
|
||||
@@ -228,7 +228,7 @@ impl ApplicationHandler for HostRunner {
|
||||
self.last_frame_time = now;
|
||||
self.accumulator += frame_delta;
|
||||
|
||||
// 🔥 O coração do determinismo: consome o tempo em fatias exatas de 60Hz
|
||||
// 🔥 The heart of determinism: consumes time in exact 60Hz slices
|
||||
while self.accumulator >= self.frame_target_dt {
|
||||
if !self.debugger.waiting_for_start {
|
||||
self.firmware.step_frame(&self.input.signals, &mut self.hardware);
|
||||
@@ -242,10 +242,10 @@ impl ApplicationHandler for HostRunner {
|
||||
|
||||
self.audio.update_stats(&mut self.stats);
|
||||
|
||||
// Atualiza estatísticas a cada 1 segundo real
|
||||
// Updates statistics every 1 real second
|
||||
self.stats.update(now, self.window, &self.hardware, &self.firmware);
|
||||
|
||||
// Processa logs do sistema
|
||||
// Process system logs
|
||||
let last_seq = self.log_sink.last_seq().unwrap_or(u64::MAX);
|
||||
let new_events = if last_seq == u64::MAX {
|
||||
self.firmware.os.log_service.get_recent(4096)
|
||||
@@ -254,11 +254,11 @@ impl ApplicationHandler for HostRunner {
|
||||
};
|
||||
self.log_sink.process_events(new_events);
|
||||
|
||||
// Overlay de Telemetria
|
||||
// Telemetry Overlay
|
||||
if self.overlay_enabled {
|
||||
self.hardware.gfx.present(); // Traz o front para o back para desenhar por cima
|
||||
self.hardware.gfx.present(); // Bring front to back to draw over
|
||||
self.display_dbg_overlay();
|
||||
self.hardware.gfx.present(); // Devolve para o front com o overlay aplicado
|
||||
self.hardware.gfx.present(); // Return to front with overlay applied
|
||||
}
|
||||
|
||||
self.request_redraw();
|
||||
@@ -286,37 +286,37 @@ mod tests {
|
||||
assert!(runner.debugger.waiting_for_start);
|
||||
assert!(runner.debugger.listener.is_some());
|
||||
|
||||
// Verifica se conseguimos conectar
|
||||
// Check if we can connect
|
||||
{
|
||||
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar");
|
||||
// Pequeno sleep para garantir que o SO processe
|
||||
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect");
|
||||
// Short sleep to ensure the OS processes
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
|
||||
// Simula o loop para aceitar a conexão
|
||||
// Simulates the loop to accept the connection
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
assert!(runner.debugger.stream.is_some(), "Stream deve ter sido mantido aberto");
|
||||
assert!(runner.debugger.stream.is_some(), "Stream should have been kept open");
|
||||
|
||||
// Verifica Handshake
|
||||
// Handshake Check
|
||||
let mut buf = [0u8; 2048];
|
||||
let n = stream.read(&mut buf).expect("Deve ler handshake");
|
||||
let resp: serde_json::Value = serde_json::from_slice(&buf[..n]).expect("Handshake deve ser JSON válido");
|
||||
let n = stream.read(&mut buf).expect("Should read handshake");
|
||||
let resp: serde_json::Value = serde_json::from_slice(&buf[..n]).expect("Handshake should be valid JSON");
|
||||
assert_eq!(resp["type"], "handshake");
|
||||
assert_eq!(resp["protocol_version"], DEVTOOLS_PROTOCOL_VERSION);
|
||||
|
||||
// Envia start via JSON
|
||||
stream.write_all(b"{\"type\":\"start\"}\n").expect("Conexão deve estar aberta para escrita");
|
||||
// Send start via JSON
|
||||
stream.write_all(b"{\"type\":\"start\"}\n").expect("Connection should be open for writing");
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
|
||||
// Processa o comando recebido
|
||||
// Process the received command
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
assert!(!runner.debugger.waiting_for_start, "Execução deve ter iniciado após comando start");
|
||||
assert!(runner.debugger.listener.is_some(), "Listener deve permanecer aberto para reconexões");
|
||||
assert!(!runner.debugger.waiting_for_start, "Execution should have started after start command");
|
||||
assert!(runner.debugger.listener.is_some(), "Listener should remain open for reconnections");
|
||||
}
|
||||
|
||||
// Agora que o stream saiu do escopo do teste, o runner deve detectar o fechamento no próximo check
|
||||
// Now that the stream is out of the test scope, the runner should detect closure on next check
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
assert!(runner.debugger.stream.is_none(), "Stream deve ter sido fechado após o cliente desconectar");
|
||||
assert!(runner.debugger.stream.is_none(), "Stream should have been closed after client disconnected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -329,32 +329,32 @@ mod tests {
|
||||
debug_port: port,
|
||||
});
|
||||
|
||||
// 1. Conecta e inicia
|
||||
// 1. Connect and start
|
||||
{
|
||||
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar 1");
|
||||
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 1");
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
assert!(runner.debugger.stream.is_some());
|
||||
|
||||
stream.write_all(b"{\"type\":\"start\"}\n").expect("Deve escrever start");
|
||||
stream.write_all(b"{\"type\":\"start\"}\n").expect("Should write start");
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
assert!(!runner.debugger.waiting_for_start);
|
||||
// Atualmente o listener é fechado aqui.
|
||||
// Currently the listener is closed here.
|
||||
}
|
||||
|
||||
// 2. Desconecta (limpa o stream no runner)
|
||||
// 2. Disconnect (clears stream in runner)
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
assert!(runner.debugger.stream.is_none());
|
||||
|
||||
// 3. Tenta reconectar - DEVE FALHAR atualmente, mas queremos que FUNCIONE
|
||||
// 3. Try to reconnect - SHOULD FAIL currently, but we want it to WORK
|
||||
let stream2 = TcpStream::connect(format!("127.0.0.1:{}", port));
|
||||
assert!(stream2.is_ok(), "Deve aceitar nova conexão mesmo após o start");
|
||||
assert!(stream2.is_ok(), "Should accept new connection even after start");
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
assert!(runner.debugger.stream.is_some(), "Stream deve ter sido aceito na reconexão");
|
||||
assert!(runner.debugger.stream.is_some(), "Stream should have been accepted on reconnection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -367,24 +367,24 @@ mod tests {
|
||||
debug_port: port,
|
||||
});
|
||||
|
||||
// 1. Primeira conexão
|
||||
let mut _stream1 = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar 1");
|
||||
// 1. First connection
|
||||
let mut _stream1 = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 1");
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
assert!(runner.debugger.stream.is_some());
|
||||
|
||||
// 2. Segunda conexão
|
||||
let mut stream2 = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar 2 (SO aceita)");
|
||||
// 2. Second connection
|
||||
let mut stream2 = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 2 (OS accepts)");
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware); // Deve aceitar e fechar stream2
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware); // Should accept and close stream2
|
||||
|
||||
// Verifica se stream2 foi fechado pelo servidor
|
||||
// Check if stream2 was closed by the server
|
||||
let mut buf = [0u8; 10];
|
||||
stream2.set_read_timeout(Some(std::time::Duration::from_millis(100))).unwrap();
|
||||
let res = stream2.read(&mut buf);
|
||||
assert!(matches!(res, Ok(0)) || res.is_err(), "Segunda conexão deve ser fechada pelo servidor");
|
||||
assert!(matches!(res, Ok(0)) || res.is_err(), "Second connection should be closed by server");
|
||||
|
||||
assert!(runner.debugger.stream.is_some(), "Primeira conexão deve continuar ativa");
|
||||
assert!(runner.debugger.stream.is_some(), "First connection should continue active");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -397,7 +397,7 @@ mod tests {
|
||||
debug_port: port,
|
||||
});
|
||||
|
||||
let stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar");
|
||||
let stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect");
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
|
||||
@@ -405,19 +405,19 @@ mod tests {
|
||||
let mut reader = std::io::BufReader::new(stream);
|
||||
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).expect("Deve ler handshake");
|
||||
reader.read_line(&mut line).expect("Should read handshake");
|
||||
assert!(line.contains("handshake"));
|
||||
|
||||
// Envia getState
|
||||
reader.get_mut().write_all(b"{\"type\":\"getState\"}\n").expect("Deve escrever getState");
|
||||
// Send getState
|
||||
reader.get_mut().write_all(b"{\"type\":\"getState\"}\n").expect("Should write getState");
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
|
||||
// Verifica se recebeu resposta (pode haver eventos/logs antes)
|
||||
// Check if response received (may have events/logs before)
|
||||
loop {
|
||||
line.clear();
|
||||
reader.read_line(&mut line).expect("Deve ler linha");
|
||||
reader.read_line(&mut line).expect("Should read line");
|
||||
if line.is_empty() { break; }
|
||||
|
||||
if let Ok(resp) = serde_json::from_str::<serde_json::Value>(&line) {
|
||||
@@ -426,7 +426,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("Não recebeu resposta getState");
|
||||
panic!("Did not receive getState response");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -439,24 +439,24 @@ mod tests {
|
||||
debug_port: port,
|
||||
});
|
||||
|
||||
// 1. Conecta e pausa
|
||||
// 1. Connect and pause
|
||||
{
|
||||
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar");
|
||||
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect");
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
|
||||
stream.write_all(b"{\"type\":\"pause\"}\n").expect("Deve escrever pause");
|
||||
stream.write_all(b"{\"type\":\"pause\"}\n").expect("Should write pause");
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
assert!(runner.firmware.os.paused, "VM deve estar pausada");
|
||||
assert!(runner.firmware.os.paused, "VM should be paused");
|
||||
}
|
||||
|
||||
// 2. Desconecta (stream sai de escopo)
|
||||
// 2. Disconnect (stream goes out of scope)
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
|
||||
|
||||
// 3. Verifica se despausou
|
||||
assert!(!runner.firmware.os.paused, "VM deve ter despausado após desconexão");
|
||||
assert!(!runner.debugger.waiting_for_start, "VM deve ter saído do estado waiting_for_start");
|
||||
// 3. Check if unpaused
|
||||
assert!(!runner.firmware.os.paused, "VM should have unpaused after disconnect");
|
||||
assert!(!runner.debugger.waiting_for_start, "VM should have left waiting_for_start state");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ impl HostStats {
|
||||
if let Some(window) = window {
|
||||
let kb = hardware.gfx.memory_usage_bytes() as f64 / 1024.0;
|
||||
|
||||
// comparação fixa sempre contra 60Hz, manter mesmo quando fazer teste de stress na CPU
|
||||
// Fixed comparison always against 60Hz, keep even when doing CPU stress tests
|
||||
let frame_budget_us = 16666.0;
|
||||
let cpu_load_core = (firmware.os.last_frame_cpu_time_us as f64 / frame_budget_us) * 100.0;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// Copia RGB565 (u16) -> RGBA8888 (u8[4]) para o frame do pixels.
|
||||
/// Formato do pixels: RGBA8.
|
||||
/// Copies RGB565 (u16) -> RGBA8888 (u8[4]) to the pixels frame.
|
||||
/// Pixels format: RGBA8.
|
||||
pub fn draw_rgb565_to_rgba8(src: &[u16], dst_rgba: &mut [u8]) {
|
||||
for (i, &px) in src.iter().enumerate() {
|
||||
let (r8, g8, b8) = rgb565_to_rgb888(px);
|
||||
@@ -11,7 +11,7 @@ pub fn draw_rgb565_to_rgba8(src: &[u16], dst_rgba: &mut [u8]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Expande RGB565 para RGB888 (replicação de bits altos).
|
||||
/// Expands RGB565 to RGB888 (high bit replication).
|
||||
#[inline(always)]
|
||||
pub fn rgb565_to_rgb888(px: u16) -> (u8, u8, u8) {
|
||||
let r5 = ((px >> 11) & 0x1F) as u8;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# PROMETEU CLI (Dispatcher)
|
||||
|
||||
O binário `prometeu` atua como o front-end unificado para o ecossistema. Ele não implementa a lógica de execução ou compilação, mas sabe onde encontrar os binários que as implementam.
|
||||
The `prometeu` binary acts as the unified front-end for the ecosystem. It does not implement the execution or compilation logic but knows where to find the binaries that do.
|
||||
|
||||
## Comandos
|
||||
## Commands
|
||||
|
||||
- `prometeu run <cart>`: Executa um cartucho usando o runtime disponível.
|
||||
- `prometeu debug <cart> [--port <p>]`: Inicia a execução em modo de depuração.
|
||||
- `prometeu build <projectDir>`: (Planejado) Chama o compilador `prometeuc`.
|
||||
- `prometeu pack <cartDir>`: (Planejado) Chama o empacotador `prometeup`.
|
||||
- `prometeu run <cart>`: Runs a cartridge using the available runtime.
|
||||
- `prometeu debug <cart> [--port <p>]`: Starts execution in debug mode.
|
||||
- `prometeu build <projectDir>`: (Planned) Calls the `prometeuc` compiler.
|
||||
- `prometeu pack <cartDir>`: (Planned) Calls the `prometeup` packager.
|
||||
|
||||
## Funcionamento
|
||||
## How it works
|
||||
|
||||
O dispatcher localiza os binários irmãos (`prometeu-runtime`, `prometeuc`, etc.) no mesmo diretório onde ele próprio está instalado. Ele herda `stdin`, `stdout` e `stderr`, e propaga o código de saída do processo chamado.
|
||||
The dispatcher locates sibling binaries (`prometeu-runtime`, `prometeuc`, etc.) in the same directory where it is installed. It inherits `stdin`, `stdout`, and `stderr`, and propagates the exit code of the called process.
|
||||
|
||||
+21
-21
@@ -5,7 +5,7 @@ use std::process::Command;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "prometeu")]
|
||||
#[command(about = "Dispatcher para o ecossistema Prometeu", long_about = None)]
|
||||
#[command(about = "Dispatcher for the Prometeu ecosystem", long_about = None)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Option<Commands>,
|
||||
@@ -13,30 +13,30 @@ struct Cli {
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Commands {
|
||||
/// Executa um cartucho
|
||||
/// Executes a cartridge
|
||||
Run {
|
||||
/// Caminho para o cartucho
|
||||
/// Path to the cartridge
|
||||
cart: String,
|
||||
},
|
||||
/// Debuga um cartucho
|
||||
/// Debugs a cartridge
|
||||
Debug {
|
||||
/// Caminho para o cartucho
|
||||
/// Path to the cartridge
|
||||
cart: String,
|
||||
/// Porta para o debugger (padrão: 7777)
|
||||
/// Port for the debugger (default: 7777)
|
||||
#[arg(long, default_value_t = 7777)]
|
||||
port: u16,
|
||||
},
|
||||
/// Compila um projeto
|
||||
/// Builds a project
|
||||
Build {
|
||||
/// Diretório do projeto
|
||||
/// Project directory
|
||||
project_dir: String,
|
||||
},
|
||||
/// Empacota um cartucho
|
||||
/// Packages a cartridge
|
||||
Pack {
|
||||
/// Diretório do cartucho
|
||||
/// Cartridge directory
|
||||
cart_dir: String,
|
||||
},
|
||||
/// Verifica integridade de um projeto ou cartucho
|
||||
/// Verifies the integrity of a project or cartridge
|
||||
Verify {
|
||||
#[command(subcommand)]
|
||||
target: VerifyCommands,
|
||||
@@ -45,14 +45,14 @@ enum Commands {
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum VerifyCommands {
|
||||
/// Verifica um projeto
|
||||
/// Verifies a project
|
||||
C {
|
||||
/// Diretório do projeto
|
||||
/// Project directory
|
||||
project_dir: String,
|
||||
},
|
||||
/// Verifica um cartucho ou arquivo PMC
|
||||
/// Verifies a cartridge or PMC file
|
||||
P {
|
||||
/// Caminho para o cartucho ou PMC
|
||||
/// Path to the cartridge or PMC
|
||||
cart_or_pmc: String,
|
||||
},
|
||||
}
|
||||
@@ -63,7 +63,7 @@ fn main() {
|
||||
let exe_dir = match env::current_exe() {
|
||||
Ok(exe_path) => exe_path.parent().unwrap_or_else(|| Path::new(".")).to_path_buf(),
|
||||
Err(e) => {
|
||||
eprintln!("Erro ao obter o caminho do executável: {}", e);
|
||||
eprintln!("Error obtaining executable path: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
@@ -109,8 +109,8 @@ fn dispatch(exe_dir: &Path, bin_name: &str, args: &[&str]) {
|
||||
let bin_path = get_binary_path(exe_dir, bin_name);
|
||||
|
||||
if !bin_path.exists() {
|
||||
// Tenta encontrar o runtime com o nome exato (prometeu-runtime-desktop)
|
||||
// caso prometeu-runtime seja apenas um alias ou link que ainda não existe
|
||||
// Tries to find the runtime with the exact name (prometeu-runtime-desktop)
|
||||
// in case prometeu-runtime is just an alias or link that doesn't exist yet
|
||||
let alt_bin_name = if bin_name == "prometeu-runtime" {
|
||||
Some("prometeu-runtime-desktop")
|
||||
} else {
|
||||
@@ -130,7 +130,7 @@ fn dispatch(exe_dir: &Path, bin_name: &str, args: &[&str]) {
|
||||
|
||||
if !final_bin_path.exists() {
|
||||
eprintln!(
|
||||
"prometeu: comando '{}' ainda não está disponível nesta distribuição",
|
||||
"prometeu: command '{}' is not yet available in this distribution",
|
||||
match bin_name {
|
||||
"prometeu-runtime" => "run/debug",
|
||||
"prometeuc" => "build/verify c",
|
||||
@@ -159,7 +159,7 @@ fn execute_bin(bin_path: &Path, args: &[&str]) {
|
||||
std::process::exit(status.code().unwrap_or(0));
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Erro ao executar {}: {}", bin_path.display(), e);
|
||||
eprintln!("Error executing {}: {}", bin_path.display(), e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -167,7 +167,7 @@ fn execute_bin(bin_path: &Path, args: &[&str]) {
|
||||
|
||||
fn not_implemented(cmd: &str, _bin_name: &str) {
|
||||
eprintln!(
|
||||
"prometeu: comando '{}' ainda não está disponível nesta distribuição",
|
||||
"prometeu: command '{}' is not yet available in this distribution",
|
||||
cmd
|
||||
);
|
||||
std::process::exit(1);
|
||||
|
||||
Reference in New Issue
Block a user