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));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user