change names of modules

This commit is contained in:
Nilton Constantino
2026-01-16 13:44:47 +00:00
parent 3ebb96acc1
commit ca2e1f8658
41 changed files with 18 additions and 18 deletions
@@ -0,0 +1,78 @@
use crate::firmware::firmware_state::FirmwareState;
use crate::hardware::{HardwareBridge, InputSignals};
use crate::model::{AppMode, Cartridge, Color};
use crate::prometeu_hub::PrometeuHub;
use crate::prometeu_os::PrometeuOS;
pub struct Firmware {
pub os: PrometeuOS,
pub hub: PrometeuHub,
pub state: FirmwareState,
}
impl Firmware {
pub fn new() -> Self {
Self {
os: PrometeuOS::new(),
hub: PrometeuHub::new(),
state: FirmwareState::Reset,
}
}
pub fn step_frame(&mut self, signals: &InputSignals, hw: &mut dyn HardwareBridge) {
match &mut self.state {
FirmwareState::Reset => {
self.os.reset();
self.state = FirmwareState::SplashScreen;
}
FirmwareState::SplashScreen => {
// Splash logic opcional
self.state = FirmwareState::LaunchHubHome;
}
FirmwareState::LaunchHubHome => {
self.hub.init();
self.state = FirmwareState::HubHome;
}
FirmwareState::HubHome => {
hw.gfx_mut().clear(Color::INDIGO);
self.hub.gui_update(&mut self.os);
hw.gfx_mut().present();
}
FirmwareState::PosRunGame(_cart) => {
if let Some(error) = self.os.step_frame(signals, hw) {
self.state = FirmwareState::PosCrashScreen(error);
}
}
FirmwareState::PosRunSystem(_cart) => {
// System Apps rodam "dentro" do Hub/Window System
if let Some(error) = self.os.step_frame(signals, hw) {
self.state = FirmwareState::PosCrashScreen(error);
}
// TODO: Compor com a UI do Hub
}
FirmwareState::PosCrashScreen(_error) => {
// Atualiza periféricos para input na tela de crash
hw.pad_mut().begin_frame(signals);
// Tela de erro: fundo vermelho, texto branco
hw.gfx_mut().clear(Color::RED);
// Por enquanto apenas logamos ou mostramos algo simples
// No futuro, usar draw_text
hw.gfx_mut().present();
// Se apertar START, volta pro Hub
if hw.pad().start.down {
self.state = FirmwareState::LaunchHubHome;
}
}
}
}
pub fn load_app(&mut self, cart: Cartridge, mode: AppMode) {
self.os.load_cartridge(&cart);
match mode {
AppMode::Game => self.state = FirmwareState::PosRunGame(cart),
AppMode::System => self.state = FirmwareState::PosRunSystem(cart),
}
}
}
@@ -0,0 +1,12 @@
use crate::model::Cartridge;
#[derive(Debug, Clone)]
pub enum FirmwareState {
Reset,
SplashScreen,
LaunchHubHome,
HubHome,
PosRunGame(Cartridge),
PosRunSystem(Cartridge),
PosCrashScreen(String),
}
+4
View File
@@ -0,0 +1,4 @@
mod firmware;
pub mod firmware_state;
pub use firmware::Firmware;
+127
View File
@@ -0,0 +1,127 @@
use crate::model::Sample;
use std::sync::Arc;
pub const MAX_CHANNELS: usize = 16;
pub const OUTPUT_SAMPLE_RATE: u32 = 48000;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LoopMode {
Off,
On,
}
pub struct Channel {
pub sample: Option<Arc<Sample>>,
pub pos: f64,
pub pitch: f64,
pub volume: u8, // 0..255
pub pan: u8, // 0..255
pub loop_mode: LoopMode,
pub priority: u8,
}
impl Default for Channel {
fn default() -> Self {
Self {
sample: None,
pos: 0.0,
pitch: 1.0,
volume: 255,
pan: 127,
loop_mode: LoopMode::Off,
priority: 0,
}
}
}
pub enum AudioCommand {
Play {
sample: Arc<Sample>,
voice_id: usize,
volume: u8,
pan: u8,
pitch: f64,
priority: u8,
loop_mode: LoopMode,
},
Stop {
voice_id: usize,
},
SetVolume {
voice_id: usize,
volume: u8,
},
SetPan {
voice_id: usize,
pan: u8,
},
SetPitch {
voice_id: usize,
pitch: f64,
},
}
pub struct Audio {
pub voices: [Channel; MAX_CHANNELS],
pub commands: Vec<AudioCommand>,
}
impl Audio {
pub fn new() -> Self {
Self {
voices: Default::default(),
commands: Vec::new(),
}
}
pub fn play(&mut self, sample: Arc<Sample>, voice_id: usize, volume: u8, pan: u8, pitch: f64, priority: u8, loop_mode: LoopMode) {
if voice_id < MAX_CHANNELS {
self.commands.push(AudioCommand::Play {
sample,
voice_id,
volume,
pan,
pitch,
priority,
loop_mode,
});
}
}
pub fn stop(&mut self, voice_id: usize) {
if voice_id < MAX_CHANNELS {
self.commands.push(AudioCommand::Stop { voice_id });
}
}
pub fn set_volume(&mut self, voice_id: usize, volume: u8) {
if voice_id < MAX_CHANNELS {
self.commands.push(AudioCommand::SetVolume { voice_id, volume });
}
}
pub fn set_pan(&mut self, voice_id: usize, pan: u8) {
if voice_id < MAX_CHANNELS {
self.commands.push(AudioCommand::SetPan { voice_id, pan });
}
}
pub fn set_pitch(&mut self, voice_id: usize, pitch: f64) {
if voice_id < MAX_CHANNELS {
self.commands.push(AudioCommand::SetPitch { voice_id, pitch });
}
}
pub fn is_playing(&self, voice_id: usize) -> bool {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].sample.is_some()
} else {
false
}
}
/// Limpa a fila de comandos. O Host deve consumir isso a cada frame.
pub fn clear_commands(&mut self) {
self.commands.clear();
}
}
+433
View File
@@ -0,0 +1,433 @@
use crate::model::{Color, HudTileLayer, ScrollableTileLayer, Sprite, TileBank, TileMap, TileSize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BlendMode {
/// dst = src
#[default]
None,
/// dst = (src + dst) / 2
Half,
/// dst = dst + (src / 2)
HalfPlus,
/// dst = dst - (src / 2)
HalfMinus,
/// dst = dst + src
Full,
}
pub struct Gfx {
w: usize,
h: usize,
front: Vec<u16>,
back: Vec<u16>,
pub layers: [ScrollableTileLayer; 4],
pub hud: HudTileLayer,
pub banks: [Option<TileBank>; 16],
pub sprites: [Sprite; 512],
pub scene_fade_level: u8, // 0..31
pub scene_fade_color: Color,
pub hud_fade_level: u8, // 0..31
pub hud_fade_color: Color,
// Cache de prioridades para evitar alocações por frame
priority_buckets: [Vec<usize>; 5],
}
impl Gfx {
pub fn new(w: usize, h: usize) -> Self {
const EMPTY_BANK: Option<TileBank> = None;
const EMPTY_SPRITE: Sprite = Sprite {
tile: crate::model::Tile { id: 0, flip_x: false, flip_y: false, palette_id: 0 },
x: 0,
y: 0,
bank_id: 0,
active: false,
flip_x: false,
flip_y: false,
priority: 4,
};
let len = w * h;
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),
],
hud: HudTileLayer::new(64, 32),
banks: [EMPTY_BANK; 16],
sprites: [EMPTY_SPRITE; 512],
scene_fade_level: 31,
scene_fade_color: Color::BLACK,
hud_fade_level: 31,
hud_fade_color: Color::BLACK,
priority_buckets: [
Vec::with_capacity(128),
Vec::with_capacity(128),
Vec::with_capacity(128),
Vec::with_capacity(128),
Vec::with_capacity(128),
],
}
}
pub fn size(&self) -> (usize, usize) {
(self.w, self.h)
}
/// O buffer que o host deve exibir (RGB565).
pub fn front_buffer(&self) -> &[u16] {
&self.front
}
pub fn clear(&mut self, color: Color) {
self.back.fill(color.0);
}
/// Retângulo com modo de blend.
pub fn fill_rect_blend(
&mut self,
x: i32,
y: i32,
w: i32,
h: i32,
color: Color,
mode: BlendMode,
) {
let fw = self.w as i32;
let fh = self.h as i32;
let x0 = x.clamp(0, fw);
let y0 = y.clamp(0, fh);
let x1 = (x + w).clamp(0, fw);
let y1 = (y + h).clamp(0, fh);
let src = color.0;
for yy in y0..y1 {
let row = (yy as usize) * self.w;
for xx in x0..x1 {
let idx = row + (xx as usize);
let dst = self.back[idx];
self.back[idx] = blend_rgb565(dst, src, mode);
}
}
}
/// Conveniência: retângulo normal (sem 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).
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).
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
for bucket in self.priority_buckets.iter_mut() {
bucket.clear();
}
for (idx, sprite) in self.sprites.iter().enumerate() {
if sprite.active && sprite.priority < 5 {
self.priority_buckets[sprite.priority as usize].push(idx);
}
}
// 1. Sprites de prioridade 0 (Atrás da Layer 0 - o fundo do fundo)
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)
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
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)
Self::apply_fade_to_buffer(&mut self.back, self.scene_fade_level, self.scene_fade_color);
// 5. HUD (Sempre por cima)
self.render_hud();
// 6. Aplica HUD Fade (Opcional, apenas para o HUD)
Self::apply_fade_to_buffer(&mut self.back, self.hud_fade_level, self.hud_fade_color);
}
pub fn render_layer(&mut self, layer_idx: usize) {
if layer_idx >= self.layers.len() { return; }
let bank_id = self.layers[layer_idx].bank_id as usize;
let scroll_x = self.layers[layer_idx].scroll_x;
let scroll_y = self.layers[layer_idx].scroll_y;
let bank = match self.banks.get(bank_id) {
Some(Some(b)) => b,
_ => return,
};
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).
pub fn render_hud(&mut self) {
let bank_id = self.hud.bank_id as usize;
let bank = match self.banks.get(bank_id) {
Some(Some(b)) => b,
_ => return,
};
Self::draw_tile_map(&mut self.back, self.w, self.h, &self.hud.map, bank, 0, 0);
}
fn draw_tile_map(
back: &mut [u16],
screen_w: usize,
screen_h: usize,
map: &TileMap,
bank: &TileBank,
scroll_x: i32,
scroll_y: i32
) {
let tile_size = bank.tile_size as usize;
// 1. Calcular quantos tiles cabem na tela (com margem de 1 para o 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)
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)
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
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
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;
Self::draw_tile_pixels(back, screen_w, screen_h, screen_tile_x, screen_tile_y, tile, bank);
}
}
}
// Função auxiliar para desenhar um bloco de 8x8, 16x16 ou 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;
for local_y in 0..size {
let world_y = y + local_y as i32;
if world_y < 0 || world_y >= screen_h as i32 { continue; }
for local_x in 0..size {
let world_x = x + local_x as i32;
if world_x < 0 || world_x >= screen_w as i32 { continue; }
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
let px_index = bank.get_pixel_index(tile.id, fetch_x, fetch_y);
// 2. Regra: Índice 0 é transparente
if px_index == 0 { continue; }
// 3. Resolve a cor usando a paleta do tile
let color = bank.resolve_color(tile.palette_id, px_index);
back[world_y as usize * screen_w + world_x as usize] = color.raw();
}
}
}
fn draw_bucket_on_buffer(
back: &mut [u16],
screen_w: usize,
screen_h: usize,
bucket: &[usize],
sprites: &[Sprite],
banks: &[Option<TileBank>],
) {
for &idx in bucket {
let s = &sprites[idx];
let bank_id = s.bank_id as usize;
if let Some(Some(bank)) = banks.get(bank_id) {
Self::draw_sprite_pixel_by_pixel(back, screen_w, screen_h, s, bank);
}
}
}
fn draw_sprite_pixel_by_pixel(
back: &mut [u16],
screen_w: usize,
screen_h: usize,
sprite: &Sprite,
bank: &TileBank
) {
// ... (mesmo cálculo de bounds/clipping que já tínhamos) ...
let size = bank.tile_size as usize;
let start_x = sprite.x.max(0);
let start_y = sprite.y.max(0);
let end_x = (sprite.x + size as i32).min(screen_w as i32);
let end_y = (sprite.y + size as i32).min(screen_h as i32);
for world_y in start_y..end_y {
for world_x in start_x..end_x {
let local_x = (world_x - sprite.x) as usize;
let local_y = (world_y - sprite.y) as usize;
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
let px_index = bank.get_pixel_index(sprite.tile.id, fetch_x, fetch_y);
// 2. Transparência
if px_index == 0 { continue; }
// 3. Resolve cor via paleta (do tile dentro do 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();
}
}
}
/// Aplica o efeito de fade em todo o back buffer.
/// level: 0 (cor total) até 31 (visível)
fn apply_fade_to_buffer(back: &mut [u16], level: u8, fade_color: Color) {
if level >= 31 { return; } // Totalmente visível, pula processamento
let weight = level as u16;
let inv_weight = 31 - weight;
let (fr, fg, fb) = Color::unpack_to_native(fade_color.0);
for px in back.iter_mut() {
let (sr, sg, sb) = Color::unpack_to_native(*px);
// Fórmula: (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;
*px = Color::pack_from_native(r, g, b);
}
}
/// 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.
pub fn memory_usage_bytes(&self) -> usize {
let mut total = 0;
// 1. Framebuffers (Front + Back)
// Cada um é Vec<u16>, ocupando 2 bytes por 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>)
total += size_of::<ScrollableTileLayer>();
total += layer.map.tiles.len() * size_of::<crate::model::Tile>();
}
// 3. HUD Layer
total += size_of::<HudTileLayer>();
total += self.hud.map.tiles.len() * size_of::<crate::model::Tile>();
// 4. Tile Banks (Assets e Paletas)
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
total += 256 * 16 * size_of::<Color>();
}
}
// 5. Sprites (OAM)
// Array fixo de 512 Sprites.
total += self.sprites.len() * size_of::<Sprite>();
total
}
}
/// Faz blend em RGB565 por canal com saturação.
/// `dst` e `src` são pixels RGB565 (u16).
fn blend_rgb565(dst: u16, src: u16, mode: BlendMode) -> u16 {
match mode {
BlendMode::None => src,
BlendMode::Half => {
let (dr, dg, db) = Color::unpack_to_native(dst);
let (sr, sg, sb) = Color::unpack_to_native(src);
let r = ((dr as u16 + sr as u16) >> 1) as u8;
let g = ((dg as u16 + sg as u16) >> 1) as u8;
let b = ((db as u16 + sb as u16) >> 1) as u8;
Color::pack_from_native(r, g, b)
}
BlendMode::HalfPlus => {
let (dr, dg, db) = Color::unpack_to_native(dst);
let (sr, sg, sb) = Color::unpack_to_native(src);
let r = (dr as u16 + ((sr as u16) >> 1)).min(31) as u8;
let g = (dg as u16 + ((sg as u16) >> 1)).min(63) as u8;
let b = (db as u16 + ((sb as u16) >> 1)).min(31) as u8;
Color::pack_from_native(r, g, b)
}
BlendMode::HalfMinus => {
let (dr, dg, db) = Color::unpack_to_native(dst);
let (sr, sg, sb) = Color::unpack_to_native(src);
let r = (dr as i16 - ((sr as i16) >> 1)).max(0) as u8;
let g = (dg as i16 - ((sg as i16) >> 1)).max(0) as u8;
let b = (db as i16 - ((sb as i16) >> 1)).max(0) as u8;
Color::pack_from_native(r, g, b)
}
BlendMode::Full => {
let (dr, dg, db) = Color::unpack_to_native(dst);
let (sr, sg, sb) = Color::unpack_to_native(src);
let r = (dr as u16 + sr as u16).min(31) as u8;
let g = (dg as u16 + sg as u16).min(63) as u8;
let b = (db as u16 + sb as u16).min(31) as u8;
Color::pack_from_native(r, g, b)
}
}
}
@@ -0,0 +1,36 @@
use crate::hardware::{Audio, Gfx, HardwareBridge, Pad, Touch};
pub struct Hardware {
pub gfx: Gfx,
pub audio: Audio,
pub pad: Pad,
pub touch: Touch,
}
impl HardwareBridge for Hardware {
fn gfx(&self) -> &Gfx { &self.gfx }
fn gfx_mut(&mut self) -> &mut Gfx { &mut self.gfx }
fn audio(&self) -> &Audio { &self.audio }
fn audio_mut(&mut self) -> &mut Audio { &mut self.audio }
fn pad(&self) -> &Pad { &self.pad }
fn pad_mut(&mut self) -> &mut Pad { &mut self.pad }
fn touch(&self) -> &Touch { &self.touch }
fn touch_mut(&mut self) -> &mut Touch { &mut self.touch }
}
impl Hardware {
pub const W: usize = 320;
pub const H: usize = 180;
pub fn new() -> Self {
Self {
gfx: Gfx::new(Self::W, Self::H),
audio: Audio::new(),
pad: Pad::default(),
touch: Touch::default(),
}
}
}
@@ -0,0 +1,26 @@
#[derive(Default, Clone, Copy, Debug)]
pub struct InputSignals {
// PAD
pub up_signal: bool,
pub down_signal: bool,
pub left_signal: bool,
pub right_signal: bool,
pub a_signal: bool,
pub b_signal: bool,
pub x_signal: bool,
pub y_signal: bool,
pub l_signal: bool,
pub r_signal: bool,
pub start_signal: bool,
pub select_signal: bool,
// TOUCH
pub f_signal: bool,
pub x_pos: i32,
pub y_pos: i32,
}
impl InputSignals {
}
+27
View File
@@ -0,0 +1,27 @@
mod gfx;
mod pad;
mod touch;
mod input_signal;
mod audio;
pub mod hardware;
pub use gfx::Gfx;
pub use gfx::BlendMode;
pub use input_signal::InputSignals;
pub use pad::Pad;
pub use touch::Touch;
pub use audio::{Audio, AudioCommand, Channel, LoopMode, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
pub trait HardwareBridge {
fn gfx(&self) -> &Gfx;
fn gfx_mut(&mut self) -> &mut Gfx;
fn audio(&self) -> &Audio;
fn audio_mut(&mut self) -> &mut Audio;
fn pad(&self) -> &Pad;
fn pad_mut(&mut self) -> &mut Pad;
fn touch(&self) -> &Touch;
fn touch_mut(&mut self) -> &mut Touch;
}
+41
View File
@@ -0,0 +1,41 @@
use crate::model::Button;
use crate::hardware::input_signal::InputSignals;
#[derive(Default, Clone, Copy, Debug)]
pub struct Pad {
pub up: Button,
pub down: Button,
pub left: Button,
pub right: Button,
pub a: Button, // ps: square
pub b: Button, // ps: circle
pub x: Button, // ps: triangle
pub y: Button, // ps: cross
pub l: Button, // ps: R
pub r: Button, // ps: L
pub start: Button,
pub select: Button,
}
impl Pad {
pub fn begin_frame(&mut self, signals: &InputSignals) {
self.up.begin_frame(signals.up_signal);
self.down.begin_frame(signals.down_signal);
self.left.begin_frame(signals.left_signal);
self.right.begin_frame(signals.right_signal);
self.a.begin_frame(signals.a_signal);
self.b.begin_frame(signals.b_signal);
self.x.begin_frame(signals.x_signal);
self.y.begin_frame(signals.y_signal);
self.l.begin_frame(signals.l_signal);
self.r.begin_frame(signals.r_signal);
self.start.begin_frame(signals.start_signal);
self.select.begin_frame(signals.select_signal);
}
}
@@ -0,0 +1,18 @@
use crate::model::Button;
use crate::hardware::input_signal::InputSignals;
#[derive(Default, Clone, Copy, Debug)]
pub struct Touch {
pub f: Button,
pub x: i32,
pub y: i32,
}
impl Touch {
/// Flags transitórias devem durar apenas 1 frame.
pub fn begin_frame(&mut self, signals: &InputSignals) {
self.f.begin_frame(signals.f_signal);
self.x = signals.x_pos.clone();
self.y = signals.y_pos.clone();
}
}
+8
View File
@@ -0,0 +1,8 @@
pub mod hardware;
pub mod vm;
mod model;
pub mod firmware;
mod prometeu_os;
mod prometeu_hub;
pub use hardware::hardware::Hardware;
+23
View File
@@ -0,0 +1,23 @@
#[derive(Default, Clone, Copy, Debug)]
pub struct Button {
pub pressed: bool,
pub released: bool,
pub down: bool,
pub hold_frames: u32,
}
impl Button {
pub fn begin_frame(&mut self, is_down_now: bool) {
let was_down = self.down;
self.down = is_down_now.clone();
self.pressed = !was_down && self.down;
self.released = was_down && !self.down;
if self.down {
self.hold_frames = self.hold_frames.saturating_add(1);
} else {
self.hold_frames = 0;
}
}
}
@@ -0,0 +1,27 @@
use crate::vm::Program;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppMode {
Game,
System,
}
#[derive(Debug, Clone)]
pub struct AppHeader {
pub app_id: String,
pub title: String,
pub mode: AppMode,
pub entrypoint: u32,
}
#[derive(Clone, Debug)]
pub struct Cartridge {
pub header: AppHeader,
pub program: Program,
}
impl Cartridge {
pub fn new(header: AppHeader, program: Program) -> Self {
Self { header, program }
}
}
+63
View File
@@ -0,0 +1,63 @@
/// Cor simples em RGB565 (0bRRRRRGGGGGGBBBBB).
/// - 5 bits Red
/// - 6 bits Green
/// - 5 bits Blue
///
/// Não há canal alpha.
/// Transparência é tratada via Color Key ou Blend Mode.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Color(pub u16);
impl Color {
pub const BLACK: Self = Self::rgb(0, 0, 0); // 0x0000
pub const WHITE: Self = Self::rgb(255, 255, 255); // 0xFFFF
pub const RED: Self = Self::rgb(255, 0, 0); // 0xF800
pub const GREEN: Self = Self::rgb(0, 255, 0); // 0x07E0
pub const BLUE: Self = Self::rgb(0, 0, 255); // 0x001F
pub const YELLOW: Self = Self::rgb(255, 255, 0); // 0xFFE0
pub const ORANGE: Self = Self::rgb(255, 128, 0);
pub const INDIGO: Self = Self::rgb(75, 0, 130);
pub const GRAY: Self = Self::rgb(128, 128, 128);
pub const CYAN: Self = Self::rgb(0, 255, 255); // 0x07FF
pub const MAGENTA: Self = Self::rgb(255, 0, 255); // 0xF81F
pub const COLOR_KEY: Self = Self::MAGENTA;
pub const TRANSPARENT: Self = Self::MAGENTA;
/// Extrai canais já na faixa nativa do RGB565:
/// R: 0..31, G: 0..63, B: 0..31
#[inline(always)]
pub const fn unpack_to_native(px: u16) -> (u8, u8, u8) {
let r = ((px >> 11) & 0x1F) as u8;
let g = ((px >> 5) & 0x3F) as u8;
let b = (px & 0x1F) as u8;
(r, g, b)
}
/// Incorpora canais já na faixa nativa do RGB565 em um 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).
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;
let b5 = (b as u16 >> 3) & 0x1F;
Self((r5 << 11) | (g6 << 5) | b5)
}
pub const fn gray_scale(c: u8) -> Self {
Self::rgb(c, c, c)
}
pub const fn from_raw(raw: u16) -> Self {
Self(raw)
}
pub const fn raw(self) -> u16 {
self.0
}
}
+17
View File
@@ -0,0 +1,17 @@
mod color;
mod button;
mod tile;
mod tile_layer;
mod tile_bank;
mod sprite;
mod sample;
mod cartridge;
pub use button::Button;
pub use color::Color;
pub use tile::Tile;
pub use tile_bank::{TileBank, TileSize};
pub use tile_layer::{HudTileLayer, ScrollableTileLayer, TileMap};
pub use sprite::Sprite;
pub use sample::Sample;
pub use cartridge::{Cartridge, AppMode};
+27
View File
@@ -0,0 +1,27 @@
pub struct Sample {
pub sample_rate: u32,
pub data: Vec<i16>,
pub loop_start: Option<u32>,
pub loop_end: Option<u32>,
}
impl Sample {
pub fn new(sample_rate: u32, data: Vec<i16>) -> Self {
Self {
sample_rate,
data,
loop_start: None,
loop_end: None,
}
}
pub fn with_loop(mut self, start: u32, end: u32) -> Self {
self.loop_start = Some(start);
self.loop_end = Some(end);
self
}
pub fn frames_len(&self) -> usize {
self.data.len()
}
}
+13
View File
@@ -0,0 +1,13 @@
use crate::model::Tile;
#[derive(Clone, Copy, Debug, Default)]
pub struct Sprite {
pub tile: Tile,
pub x: i32,
pub y: i32,
pub bank_id: u8,
pub active: bool,
pub flip_x: bool,
pub flip_y: bool,
pub priority: u8,
}
+7
View File
@@ -0,0 +1,7 @@
#[derive(Clone, Copy, Debug, Default)]
pub struct Tile {
pub id: u16,
pub flip_x: bool,
pub flip_y: bool,
pub palette_id: u8,
}
@@ -0,0 +1,61 @@
use crate::model::Color;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TileSize {
Size8 = 8,
Size16 = 16,
Size32 = 32,
}
pub struct TileBank {
pub tile_size: TileSize,
pub width: usize, // em pixels
pub height: usize, // em pixels
// pub pixels: Vec<Color>,
/// Agora guardamos índices de 0 a 15 (4 bits por pixel simulados em 8 bits)
pub pixel_indices: Vec<u8>,
/// 256 paletas, cada uma com 16 cores (RGB565 como u16)
pub palettes: [[Color; 16]; 256],
}
impl TileBank {
pub fn new(tile_size: TileSize, width: usize, height: usize) -> Self {
Self {
tile_size,
width,
height,
pixel_indices: vec![0; width * height], // Índice 0 = Transparente
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)
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;
let tile_x = (tile_id as usize % tiles_per_row) * size;
let tile_y = (tile_id as usize / tiles_per_row) * size;
let pixel_x = tile_x + local_x;
let pixel_y = tile_y + local_y;
if pixel_x < self.width && pixel_y < self.height {
self.pixel_indices[pixel_y * self.width + pixel_x]
} else {
0 // Fora do banco = Transparente
}
}
/// Resolve um índice de pixel para uma Color real usando uma paleta.
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Color {
// Regra: Índice 0 é sempre transparente (usamos MAGENTA/COLOR_KEY como vácuo)
if pixel_index == 0 {
return Color::COLOR_KEY;
}
self.palettes[palette_id as usize][pixel_index as usize]
}
}
@@ -0,0 +1,109 @@
use crate::model::Tile;
use crate::model::tile_bank::TileSize;
use crate::model::TileSize::Size8;
pub struct TileMap {
pub width: usize,
pub height: usize,
pub tiles: Vec<Tile>,
}
impl TileMap {
fn create(width: usize, height: usize) -> Self {
Self {
width,
height,
tiles: vec![Tile::default(); width * height],
}
}
pub fn set_tile(&mut self, x: usize, y: usize, tile: Tile) {
if x < self.width && y < self.height {
self.tiles[y * self.width + x] = tile;
}
}
}
pub struct TileLayer {
pub bank_id: u8,
pub tile_size: TileSize,
pub map: TileMap,
}
impl TileLayer {
fn create(width: usize, height: usize, tile_size: TileSize) -> Self {
Self {
bank_id: 0,
tile_size: tile_size,
map: TileMap::create(width, height),
}
}
}
impl std::ops::Deref for TileLayer {
type Target = TileMap;
fn deref(&self) -> &Self::Target {
&self.map
}
}
impl std::ops::DerefMut for TileLayer {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.map
}
}
pub struct ScrollableTileLayer {
pub layer: TileLayer,
pub scroll_x: i32,
pub scroll_y: i32,
}
impl ScrollableTileLayer {
pub fn new(width: usize, height: usize, tile_size: TileSize) -> Self {
Self {
layer: TileLayer::create(width, height, tile_size),
scroll_x: 0,
scroll_y: 0,
}
}
}
impl std::ops::Deref for ScrollableTileLayer {
type Target = TileLayer;
fn deref(&self) -> &Self::Target {
&self.layer
}
}
impl std::ops::DerefMut for ScrollableTileLayer {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.layer
}
}
pub struct HudTileLayer {
pub layer: TileLayer,
}
impl HudTileLayer {
pub fn new(width: usize, height: usize) -> Self {
Self {
layer: TileLayer::create(width, height, Size8),
}
}
}
impl std::ops::Deref for HudTileLayer {
type Target = TileLayer;
fn deref(&self) -> &Self::Target {
&self.layer
}
}
impl std::ops::DerefMut for HudTileLayer {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.layer
}
}
@@ -0,0 +1,3 @@
mod prometeu_hub;
pub use prometeu_hub::PrometeuHub;
@@ -0,0 +1,37 @@
use crate::model::Color;
use crate::prometeu_os::PrometeuOS;
// TODO: Mover para arquivo próprio se crescer.
/// Sistema de janelas do PROMETEU.
pub struct WindowSystem {
pub theme_color: Color,
}
impl WindowSystem {
pub fn new() -> Self {
Self {
theme_color: Color::INDIGO,
}
}
}
/// PrometeuHub: Launcher e ambiente de UI do sistema.
pub struct PrometeuHub {
pub window_system: WindowSystem,
}
impl PrometeuHub {
pub fn new() -> Self {
Self {
window_system: WindowSystem::new(),
}
}
pub fn init(&mut self) {
// Inicializa o Window System e lista apps
}
pub fn gui_update(&mut self, _os: &mut PrometeuOS) {
// Atualiza a UI do Window System
}
}
@@ -0,0 +1,4 @@
mod prometeu_os;
pub use prometeu_os::PrometeuOS;
pub use crate::vm::native_interface::NativeInterface;
@@ -0,0 +1,229 @@
use crate::model::{Cartridge, Color, Sample};
use crate::hardware::{HardwareBridge, InputSignals};
use crate::vm::{Value, VirtualMachine};
use std::sync::Arc;
use crate::prometeu_os::NativeInterface;
/// PrometeuOS (POS): O firmware/base do sistema.
/// Autoridade máxima do boot, periféricos, execução da PVM e tratamento de falhas.
pub struct PrometeuOS {
pub vm: VirtualMachine,
pub tick_index: u64,
pub logical_frame_index: u64,
pub logical_frame_open: bool,
pub last_frame_cpu_time_us: u64,
// Assets de exemplo (mantidos para compatibilidade com syscalls de áudio v0)
pub sample_square: Option<Arc<Sample>>,
pub sample_kick: Option<Arc<Sample>>,
pub sample_snare: Option<Arc<Sample>>,
}
impl PrometeuOS {
pub const CYCLES_PER_FRAME: u64 = 100_000;
pub fn new() -> Self {
let mut os = Self {
vm: VirtualMachine::default(),
tick_index: 0,
logical_frame_index: 0,
logical_frame_open: false,
last_frame_cpu_time_us: 0,
sample_square: None,
sample_kick: None,
sample_snare: None,
};
// Inicializa samples básicos (mesma lógica do LogicalHardware)
os.sample_square = Some(Arc::new(Self::create_square_sample(440.0, 0.1)));
os
}
pub fn reset(&mut self) {
self.vm = VirtualMachine::default();
self.tick_index = 0;
self.logical_frame_index = 0;
self.logical_frame_open = false;
self.last_frame_cpu_time_us = 0;
}
/// Carrega um cartucho na PVM e reseta o estado de execução.
pub fn load_cartridge(&mut self, cart: &Cartridge) {
// Na spec: "resetar PC/stack/heap ao iniciar app"
self.vm.program = cart.program.clone();
self.vm.pc = 0;
self.vm.operand_stack.clear();
self.vm.call_stack.clear();
self.vm.globals.clear();
self.vm.heap.clear();
self.vm.halted = false;
}
/// Executa um tick do host (60Hz).
pub fn step_frame(&mut self, signals: &InputSignals, hw: &mut dyn HardwareBridge) -> Option<String> {
let start = std::time::Instant::now();
self.tick_index += 1;
if !self.logical_frame_open {
self.logical_frame_open = true;
self.begin_logical_frame(signals, hw);
}
// Executa budget
let mut vm = std::mem::take(&mut self.vm);
let run_result = vm.run_budget(Self::CYCLES_PER_FRAME, self, hw);
self.vm = vm;
match run_result {
Ok(run) => {
if run.reason == crate::vm::LogicalFrameEndingReason::FrameSync {
hw.gfx_mut().render_all();
self.end_logical_frame(hw);
self.logical_frame_index += 1;
self.logical_frame_open = false;
}
}
Err(e) => {
return Some(format!("PVM Fault: {:?}", e));
}
}
self.last_frame_cpu_time_us = start.elapsed().as_micros() as u64;
None
}
fn begin_logical_frame(&mut self, signals: &InputSignals, hw: &mut dyn HardwareBridge) {
hw.audio_mut().clear_commands();
hw.touch_mut().begin_frame(signals);
hw.pad_mut().begin_frame(signals);
}
fn end_logical_frame(&mut self, hw: &mut dyn HardwareBridge) {
hw.gfx_mut().present();
}
// Helper para syscalls
pub fn get_color(&self, index: usize, hw: &mut dyn HardwareBridge) -> Color {
if let Some(bank) = hw.gfx().banks[0].as_ref() {
bank.palettes[0][index % 16]
} else {
match index % 16 {
0 => Color::BLACK,
1 => Color::WHITE,
2 => Color::RED,
3 => Color::GREEN,
4 => Color::BLUE,
5 => Color::YELLOW,
6 => Color::CYAN,
7 => Color::INDIGO,
8 => Color::GRAY,
_ => Color::BLACK,
}
}
}
// Helper para syscalls
pub fn is_button_down(&self, id: u32, hw: &mut dyn HardwareBridge) -> bool {
match id {
0 => hw.pad().up.down,
1 => hw.pad().down.down,
2 => hw.pad().left.down,
3 => hw.pad().right.down,
4 => hw.pad().a.down,
5 => hw.pad().b.down,
6 => hw.pad().x.down,
7 => hw.pad().y.down,
8 => hw.pad().l.down,
9 => hw.pad().r.down,
10 => hw.pad().start.down,
11 => hw.pad().select.down,
_ => false,
}
}
fn create_square_sample(freq: f64, duration: f64) -> Sample {
let sample_rate = crate::hardware::OUTPUT_SAMPLE_RATE;
let num_samples = (duration * sample_rate as f64) as usize;
let mut data = Vec::with_capacity(num_samples);
let period = sample_rate as f64 / freq;
for i in 0..num_samples {
let val = if (i as f64 % period) < (period / 2.0) {
10000
} else {
-10000
};
data.push(val);
}
Sample::new(sample_rate, data)
}
}
impl NativeInterface for PrometeuOS {
fn syscall(&mut self, id: u32, vm: &mut VirtualMachine, hw: &mut dyn HardwareBridge) -> Result<u64, String> {
match id {
// system.has_cart() -> bool
0x0001 => {
// vm.push(Value::Boolean(self.current_cartridge.is_some()));
Ok(10)
}
// system.run_cart()
0x0002 => {
// if let Some(cart) = self.current_cartridge.as_ref().cloned() {
// self.load_cartridge(&cart);
// } else {
// return Err("No cartridge inserted".into());
// }
Ok(100)
}
// gfx.clear(color_index)
0x1001 => {
let color_idx = vm.pop_integer()? as usize;
let color = self.get_color(color_idx, hw);
hw.gfx_mut().clear(color);
Ok(100)
}
// gfx.draw_rect(x, y, w, h, color_index)
0x1002 => {
let color_idx = vm.pop_integer()? as usize;
let h = vm.pop_integer()? as i32;
let w = vm.pop_integer()? as i32;
let y = vm.pop_integer()? as i32;
let x = vm.pop_integer()? as i32;
let color = self.get_color(color_idx, hw);
hw.gfx_mut().fill_rect(x, y, w, h, color);
Ok(200)
}
// input.get_pad(button_id) -> bool
0x2001 => {
let button_id = vm.pop_integer()? as u32;
let is_down = self.is_button_down(button_id, hw);
vm.push(Value::Boolean(is_down));
Ok(50)
}
// audio.play_sample(sample_id, voice_id, volume, pan, pitch)
0x3001 => {
let pitch = vm.pop_number()?;
let pan = vm.pop_integer()? as u8;
let volume = vm.pop_integer()? as u8;
let voice_id = vm.pop_integer()? as usize;
let sample_id = vm.pop_integer()? as u32;
let sample = match sample_id {
0 => self.sample_square.clone(),
1 => self.sample_kick.clone(),
2 => self.sample_snare.clone(),
_ => None,
};
if let Some(s) = sample {
hw.audio_mut().play(s, voice_id, volume, pan, pitch, 0, crate::hardware::LoopMode::Off);
}
Ok(300)
}
_ => Err(format!("Unknown syscall: 0x{:08X}", id)),
}
}
}
@@ -0,0 +1,5 @@
pub struct CallFrame {
pub return_address: usize,
pub stack_base: usize,
pub locals_count: usize,
}
+12
View File
@@ -0,0 +1,12 @@
mod virtual_machine;
mod value;
mod opcode;
mod call_frame;
mod program;
pub mod native_interface;
pub use opcode::OpCode;
pub use program::Program;
pub use value::Value;
pub use virtual_machine::{BudgetReport, LogicalFrameEndingReason, VirtualMachine};
@@ -0,0 +1,6 @@
use crate::hardware::HardwareBridge;
use crate::vm::VirtualMachine;
pub trait NativeInterface {
fn syscall(&mut self, id: u32, vm: &mut VirtualMachine, hw: &mut dyn HardwareBridge) -> Result<u64, String>;
}
+157
View File
@@ -0,0 +1,157 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum OpCode {
// 6.1 Controle de Execução
Nop = 0x00,
Halt = 0x01,
Jmp = 0x02,
JmpIfFalse = 0x03,
// 6.2 Pilha
PushConst = 0x10,
Pop = 0x11,
Dup = 0x12,
Swap = 0x13,
// 6.3 Aritmética
Add = 0x20,
Sub = 0x21,
Mul = 0x22,
Div = 0x23,
// 6.4 Comparação e Lógica
Eq = 0x30,
Neq = 0x31,
Lt = 0x32,
Gt = 0x33,
And = 0x34,
Or = 0x35,
Not = 0x36,
// 6.5 Variáveis
GetGlobal = 0x40,
SetGlobal = 0x41,
GetLocal = 0x42,
SetLocal = 0x43,
// 6.6 Funções
Call = 0x50,
Ret = 0x51,
PushScope = 0x52,
PopScope = 0x53,
// 6.7 Heap
Alloc = 0x60,
LoadRef = 0x61,
StoreRef = 0x62,
// 6.8 Periféricos e Sistema
Syscall = 0x70,
FrameSync = 0x80,
}
impl TryFrom<u16> for OpCode {
type Error = String;
fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
0x00 => Ok(OpCode::Nop),
0x01 => Ok(OpCode::Halt),
0x02 => Ok(OpCode::Jmp),
0x03 => Ok(OpCode::JmpIfFalse),
0x10 => Ok(OpCode::PushConst),
0x11 => Ok(OpCode::Pop),
0x12 => Ok(OpCode::Dup),
0x13 => Ok(OpCode::Swap),
0x20 => Ok(OpCode::Add),
0x21 => Ok(OpCode::Sub),
0x22 => Ok(OpCode::Mul),
0x23 => Ok(OpCode::Div),
0x30 => Ok(OpCode::Eq),
0x31 => Ok(OpCode::Neq),
0x32 => Ok(OpCode::Lt),
0x33 => Ok(OpCode::Gt),
0x34 => Ok(OpCode::And),
0x35 => Ok(OpCode::Or),
0x36 => Ok(OpCode::Not),
0x40 => Ok(OpCode::GetGlobal),
0x41 => Ok(OpCode::SetGlobal),
0x42 => Ok(OpCode::GetLocal),
0x43 => Ok(OpCode::SetLocal),
0x50 => Ok(OpCode::Call),
0x51 => Ok(OpCode::Ret),
0x52 => Ok(OpCode::PushScope),
0x53 => Ok(OpCode::PopScope),
0x60 => Ok(OpCode::Alloc),
0x61 => Ok(OpCode::LoadRef),
0x62 => Ok(OpCode::StoreRef),
0x70 => Ok(OpCode::Syscall),
0x80 => Ok(OpCode::FrameSync),
_ => Err(format!("Invalid OpCode: 0x{:04X}", value)),
}
}
}
impl OpCode {
pub fn cycles(&self) -> u64 {
match self {
OpCode::Nop => 1,
OpCode::Halt => 1,
OpCode::Jmp => 2,
OpCode::JmpIfFalse => 3,
OpCode::PushConst => 2,
OpCode::Pop => 1,
OpCode::Dup => 1,
OpCode::Swap => 1,
OpCode::Add => 2,
OpCode::Sub => 2,
OpCode::Mul => 4,
OpCode::Div => 6,
OpCode::Eq => 2,
OpCode::Neq => 2,
OpCode::Lt => 2,
OpCode::Gt => 2,
OpCode::And => 2,
OpCode::Or => 2,
OpCode::Not => 1,
OpCode::GetGlobal => 3,
OpCode::SetGlobal => 3,
OpCode::GetLocal => 2,
OpCode::SetLocal => 2,
OpCode::Call => 5,
OpCode::Ret => 4,
OpCode::PushScope => 3,
OpCode::PopScope => 3,
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::FrameSync => 1,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_opcode_decoding() {
assert_eq!(OpCode::try_from(0x00).unwrap(), OpCode::Nop);
assert_eq!(OpCode::try_from(0x10).unwrap(), OpCode::PushConst);
assert_eq!(OpCode::try_from(0x20).unwrap(), OpCode::Add);
assert_eq!(OpCode::try_from(0x70).unwrap(), OpCode::Syscall);
assert_eq!(OpCode::try_from(0x80).unwrap(), OpCode::FrameSync);
assert!(OpCode::try_from(0xFFFF).is_err());
}
#[test]
fn test_opcode_cycles() {
assert_eq!(OpCode::Nop.cycles(), 1);
assert_eq!(OpCode::Add.cycles(), 2);
assert_eq!(OpCode::Mul.cycles(), 4);
assert_eq!(OpCode::Div.cycles(), 6);
assert_eq!(OpCode::Alloc.cycles(), 10);
}
}
+17
View File
@@ -0,0 +1,17 @@
use std::sync::Arc;
use crate::vm::Value;
#[derive(Debug, Clone, Default)]
pub struct Program {
pub rom: Arc<[u8]>,
pub constant_pool: Arc<[Value]>,
}
impl Program {
pub fn new(rom: Vec<u8>, constant_pool: Vec<Value>) -> Self {
Self {
rom: Arc::from(rom),
constant_pool: Arc::from(constant_pool),
}
}
}
+77
View File
@@ -0,0 +1,77 @@
#[derive(Debug, Clone)]
pub enum Value {
Integer(i64),
Float(f64),
Boolean(bool),
String(String),
Ref(usize), // Referência ao heap
Null,
}
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Value::Integer(a), Value::Integer(b)) => a == b,
(Value::Float(a), Value::Float(b)) => a == b,
(Value::Integer(a), Value::Float(b)) => *a as f64 == *b,
(Value::Float(a), Value::Integer(b)) => *a == *b as f64,
(Value::Boolean(a), Value::Boolean(b)) => a == b,
(Value::String(a), Value::String(b)) => a == b,
(Value::Ref(a), Value::Ref(b)) => a == b,
(Value::Null, Value::Null) => true,
_ => false,
}
}
}
impl Value {
pub fn as_float(&self) -> Option<f64> {
match self {
Value::Integer(i) => Some(*i as f64),
Value::Float(f) => Some(*f),
_ => None,
}
}
pub fn as_integer(&self) -> Option<i64> {
match self {
Value::Integer(i) => Some(*i),
Value::Float(f) => Some(*f as i64),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_value_equality() {
assert_eq!(Value::Integer(10), Value::Integer(10));
assert_eq!(Value::Float(10.5), Value::Float(10.5));
assert_eq!(Value::Integer(10), Value::Float(10.0));
assert_eq!(Value::Float(10.0), Value::Integer(10));
assert_ne!(Value::Integer(10), Value::Integer(11));
assert_ne!(Value::Integer(10), Value::Float(10.1));
assert_eq!(Value::Boolean(true), Value::Boolean(true));
assert_ne!(Value::Boolean(true), Value::Boolean(false));
assert_eq!(Value::String("oi".into()), Value::String("oi".into()));
assert_eq!(Value::Null, Value::Null);
}
#[test]
fn test_value_conversions() {
let v_int = Value::Integer(42);
assert_eq!(v_int.as_float(), Some(42.0));
assert_eq!(v_int.as_integer(), Some(42));
let v_float = Value::Float(42.7);
assert_eq!(v_float.as_float(), Some(42.7));
assert_eq!(v_float.as_integer(), Some(42));
let v_bool = Value::Boolean(true);
assert_eq!(v_bool.as_float(), None);
assert_eq!(v_bool.as_integer(), None);
}
}
@@ -0,0 +1,400 @@
use crate::hardware::HardwareBridge;
use crate::prometeu_os::NativeInterface;
use crate::vm::call_frame::CallFrame;
use crate::vm::opcode::OpCode;
use crate::vm::value::Value;
use crate::vm::Program;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogicalFrameEndingReason {
FrameSync,
BudgetExhausted,
Halted,
EndOfRom,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BudgetReport {
pub cycles_used: u64,
pub reason: LogicalFrameEndingReason,
}
pub struct VirtualMachine {
pub pc: usize,
pub operand_stack: Vec<Value>,
pub call_stack: Vec<CallFrame>,
pub globals: Vec<Value>,
pub program: Program,
pub heap: Vec<Value>, // Simplificado para demo, futuramente RAM/Heap real
pub cycles: u64,
pub halted: bool,
}
impl VirtualMachine {
pub fn new(rom: Vec<u8>, constant_pool: Vec<Value>) -> Self {
Self {
pc: 0,
operand_stack: Vec::new(),
call_stack: Vec::new(),
globals: Vec::new(),
program: Program::new(rom, constant_pool),
heap: Vec::new(),
cycles: 0,
halted: false,
}
}
}
impl Default for VirtualMachine {
fn default() -> Self {
Self::new(vec![], vec![])
}
}
impl VirtualMachine {
pub fn run_budget(
&mut self,
budget: u64,
native: &mut dyn NativeInterface,
hw: &mut dyn HardwareBridge,
) -> Result<BudgetReport, String> {
let start_cycles = self.cycles;
let mut ending_reason: Option<LogicalFrameEndingReason> = None;
while (self.cycles - start_cycles) < budget
&& !self.halted
&& self.pc < self.program.rom.len()
{
let pc_before = self.pc;
let cycles_before = self.cycles;
// Fast-path: FRAME_SYNC encerra o frame lógico
let opcode_val = self.peek_u16()?;
let opcode = OpCode::try_from(opcode_val)?;
if opcode == OpCode::FrameSync {
self.pc += 2;
self.cycles += OpCode::FrameSync.cycles();
ending_reason = Some(LogicalFrameEndingReason::FrameSync);
break;
}
self.step(native, hw)?;
// garante progresso real
if self.pc == pc_before && self.cycles == cycles_before && !self.halted {
return Err(format!("VM stuck at PC 0x{:08X}", self.pc));
}
}
if ending_reason.is_none() {
if self.halted {
ending_reason = Some(LogicalFrameEndingReason::Halted);
} else if self.pc >= self.program.rom.len() {
ending_reason = Some(LogicalFrameEndingReason::EndOfRom);
} else {
ending_reason = Some(LogicalFrameEndingReason::BudgetExhausted);
}
}
Ok(BudgetReport {
cycles_used: self.cycles - start_cycles,
reason: ending_reason.unwrap(),
})
}
fn peek_u16(&self) -> Result<u16, String> {
if self.pc + 2 > self.program.rom.len() {
return Err("Unexpected end of ROM".into());
}
let bytes = [
self.program.rom[self.pc],
self.program.rom[self.pc + 1],
];
Ok(u16::from_le_bytes(bytes))
}
pub fn step(&mut self, native: &mut dyn NativeInterface, hw: &mut dyn HardwareBridge) -> Result<(), String> {
if self.halted || self.pc >= self.program.rom.len() {
return Ok(());
}
let opcode_val = self.read_u16()?;
let opcode = OpCode::try_from(opcode_val)?;
match opcode {
OpCode::Nop => {}
OpCode::Halt => {
self.halted = true;
}
OpCode::Jmp => {
let addr = self.read_u32()? as usize;
self.pc = addr;
}
OpCode::JmpIfFalse => {
let addr = self.read_u32()? as usize;
let val = self.pop()?;
if let Value::Boolean(false) = val {
self.pc = addr;
}
}
OpCode::PushConst => {
let idx = self.read_u32()? as usize;
let val = self.program.constant_pool.get(idx).cloned().ok_or("Invalid constant index")?;
self.push(val);
}
OpCode::Pop => {
self.pop()?;
}
OpCode::Dup => {
let val = self.peek()?.clone();
self.push(val);
}
OpCode::Swap => {
let a = self.pop()?;
let b = self.pop()?;
self.push(a);
self.push(b);
}
OpCode::Add => self.binary_op(|a, b| match (a, b) {
(Value::Integer(a), Value::Integer(b)) => Ok(Value::Integer(a.wrapping_add(b))),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a + b)),
(Value::Integer(a), Value::Float(b)) => Ok(Value::Float(a as f64 + b)),
(Value::Float(a), Value::Integer(b)) => Ok(Value::Float(a + b as f64)),
_ => Err("Invalid types for ADD".into()),
})?,
OpCode::Sub => self.binary_op(|a, b| match (a, b) {
(Value::Integer(a), Value::Integer(b)) => Ok(Value::Integer(a.wrapping_sub(b))),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a - b)),
(Value::Integer(a), Value::Float(b)) => Ok(Value::Float(a as f64 - b)),
(Value::Float(a), Value::Integer(b)) => Ok(Value::Float(a - b as f64)),
_ => Err("Invalid types for SUB".into()),
})?,
OpCode::Mul => self.binary_op(|a, b| match (a, b) {
(Value::Integer(a), Value::Integer(b)) => Ok(Value::Integer(a.wrapping_mul(b))),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a * b)),
(Value::Integer(a), Value::Float(b)) => Ok(Value::Float(a as f64 * b)),
(Value::Float(a), Value::Integer(b)) => Ok(Value::Float(a * b as f64)),
_ => Err("Invalid types for MUL".into()),
})?,
OpCode::Div => self.binary_op(|a, b| match (a, b) {
(Value::Integer(a), Value::Integer(b)) => {
if b == 0 { return Err("Division by zero".into()); }
Ok(Value::Integer(a / b))
}
(Value::Float(a), Value::Float(b)) => {
if b == 0.0 { return Err("Division by zero".into()); }
Ok(Value::Float(a / b))
}
(Value::Integer(a), Value::Float(b)) => {
if b == 0.0 { return Err("Division by zero".into()); }
Ok(Value::Float(a as f64 / b))
}
(Value::Float(a), Value::Integer(b)) => {
if b == 0 { return Err("Division by zero".into()); }
Ok(Value::Float(a / b as f64))
}
_ => Err("Invalid types for DIV".into()),
})?,
OpCode::Eq => self.binary_op(|a, b| Ok(Value::Boolean(a == b)))?,
OpCode::Neq => self.binary_op(|a, b| Ok(Value::Boolean(a != b)))?,
OpCode::Lt => self.binary_op(|a, b| {
match (a, b) {
(Value::Integer(a), Value::Integer(b)) => Ok(Value::Boolean(a < b)),
(Value::Float(a), Value::Float(b)) => Ok(Value::Boolean(a < b)),
(Value::Integer(a), Value::Float(b)) => Ok(Value::Boolean((a as f64) < b)),
(Value::Float(a), Value::Integer(b)) => Ok(Value::Boolean(a < (b as f64))),
_ => Err("Invalid types for LT".into()),
}
})?,
OpCode::Gt => self.binary_op(|a, b| {
match (a, b) {
(Value::Integer(a), Value::Integer(b)) => Ok(Value::Boolean(a > b)),
(Value::Float(a), Value::Float(b)) => Ok(Value::Boolean(a > b)),
(Value::Integer(a), Value::Float(b)) => Ok(Value::Boolean((a as f64) > b)),
(Value::Float(a), Value::Integer(b)) => Ok(Value::Boolean(a > (b as f64))),
_ => Err("Invalid types for GT".into()),
}
})?,
OpCode::And => self.binary_op(|a, b| match (a, b) {
(Value::Boolean(a), Value::Boolean(b)) => Ok(Value::Boolean(a && b)),
_ => Err("Invalid types for AND".into()),
})?,
OpCode::Or => self.binary_op(|a, b| match (a, b) {
(Value::Boolean(a), Value::Boolean(b)) => Ok(Value::Boolean(a || b)),
_ => Err("Invalid types for OR".into()),
})?,
OpCode::Not => {
let val = self.pop()?;
if let Value::Boolean(b) = val {
self.push(Value::Boolean(!b));
} else {
return Err("Invalid type for NOT".into());
}
}
OpCode::GetGlobal => {
let idx = self.read_u32()? as usize;
let val = self.globals.get(idx).cloned().ok_or("Invalid global index")?;
self.push(val);
}
OpCode::SetGlobal => {
let idx = self.read_u32()? as usize;
let val = self.pop()?;
if idx >= self.globals.len() {
self.globals.resize(idx + 1, Value::Null);
}
self.globals[idx] = val;
}
OpCode::GetLocal => {
let idx = self.read_u32()? as usize;
let frame = self.call_stack.last().ok_or("No active call frame")?;
let val = self.operand_stack.get(frame.stack_base + idx).cloned().ok_or("Invalid local index")?;
self.push(val);
}
OpCode::SetLocal => {
let idx = self.read_u32()? as usize;
let val = self.pop()?;
let frame = self.call_stack.last().ok_or("No active call frame")?;
let stack_idx = frame.stack_base + idx;
if stack_idx >= self.operand_stack.len() {
return Err("Local index out of bounds".into());
}
self.operand_stack[stack_idx] = val;
}
OpCode::Call => {
let addr = self.read_u32()? as usize;
let args_count = self.read_u32()? as usize;
let stack_base = self.operand_stack.len() - args_count;
self.call_stack.push(CallFrame {
return_address: self.pc,
stack_base,
locals_count: args_count,
});
self.pc = addr;
}
OpCode::Ret => {
let frame = self.call_stack.pop().ok_or("Call stack underflow")?;
let return_val = self.pop()?;
self.operand_stack.truncate(frame.stack_base);
self.push(return_val);
self.pc = frame.return_address;
}
OpCode::PushScope => {
let locals_count = self.read_u32()? as usize;
let stack_base = self.operand_stack.len();
for _ in 0..locals_count {
self.push(Value::Null);
}
self.call_stack.push(CallFrame {
return_address: 0,
stack_base,
locals_count,
});
}
OpCode::PopScope => {
let frame = self.call_stack.pop().ok_or("Call stack underflow")?;
self.operand_stack.truncate(frame.stack_base);
}
OpCode::Alloc => {
let size = self.read_u32()? as usize;
let ref_idx = self.heap.len();
for _ in 0..size {
self.heap.push(Value::Null);
}
self.push(Value::Ref(ref_idx));
}
OpCode::LoadRef => {
let offset = self.read_u32()? as usize;
let ref_val = self.pop()?;
if let Value::Ref(base) = ref_val {
let val = self.heap.get(base + offset).cloned().ok_or("Invalid heap access")?;
self.push(val);
} else {
return Err("Expected reference for LOAD_REF".into());
}
}
OpCode::StoreRef => {
let offset = self.read_u32()? as usize;
let val = self.pop()?;
let ref_val = self.pop()?;
if let Value::Ref(base) = ref_val {
if base + offset >= self.heap.len() {
return Err("Invalid heap access".into());
}
self.heap[base + offset] = val;
} else {
return Err("Expected reference for STORE_REF".into());
}
}
OpCode::Syscall => {
let id = self.read_u32()?;
let native_cycles = native.syscall(id, self, hw).map_err(|e| format!("syscall 0x{:08X} failed: {}", id, e))?;
self.cycles += native_cycles;
}
OpCode::FrameSync => {
return Ok(());
}
}
self.cycles += opcode.cycles();
Ok(())
}
fn read_u32(&mut self) -> Result<u32, String> {
if self.pc + 4 > self.program.rom.len() {
return Err("Unexpected end of ROM".into());
}
let bytes = [
self.program.rom[self.pc],
self.program.rom[self.pc + 1],
self.program.rom[self.pc + 2],
self.program.rom[self.pc + 3],
];
self.pc += 4;
Ok(u32::from_le_bytes(bytes))
}
fn read_u16(&mut self) -> Result<u16, String> {
if self.pc + 2 > self.program.rom.len() {
return Err("Unexpected end of ROM".into());
}
let bytes = [
self.program.rom[self.pc],
self.program.rom[self.pc + 1],
];
self.pc += 2;
Ok(u16::from_le_bytes(bytes))
}
pub fn push(&mut self, val: Value) {
self.operand_stack.push(val);
}
pub fn pop(&mut self) -> Result<Value, String> {
self.operand_stack.pop().ok_or("Stack underflow".into())
}
pub fn pop_number(&mut self) -> Result<f64, String> {
let val = self.pop()?;
val.as_float().ok_or_else(|| "Expected number".into())
}
pub fn pop_integer(&mut self) -> Result<i64, String> {
let val = self.pop()?;
val.as_integer().ok_or_else(|| "Expected integer".into())
}
pub fn peek(&self) -> Result<&Value, String> {
self.operand_stack.last().ok_or("Stack underflow".into())
}
fn binary_op<F>(&mut self, f: F) -> Result<(), String>
where
F: FnOnce(Value, Value) -> Result<Value, String>,
{
let b = self.pop()?;
let a = self.pop()?;
let res = f(a, b)?;
self.push(res);
Ok(())
}
}