added domains into crates

This commit is contained in:
2026-03-24 13:40:34 +00:00
parent 1135514508
commit bddd588464
222 changed files with 751 additions and 790 deletions
@@ -0,0 +1,11 @@
[package]
name = "prometeu-drivers"
version = "0.1.0"
edition = "2024"
license.workspace = true
[dependencies]
serde_json = "1.0.149"
prometeu-vm = { path = "../prometeu-vm" }
prometeu-abi = { path = "../../compiler/prometeu-abi" }
prometeu-hal = { path = "../prometeu-hal" }
+14
View File
@@ -0,0 +1,14 @@
# PROMETEU Core
This crate contains the core library that defines the behavior of PROMETEU's hardware and software.
## Responsibilities
- **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.
## Architecture
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`).
@@ -0,0 +1,882 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::time::Instant;
use prometeu_hal::asset::{AssetEntry, BankStats, BankType, HandleId, LoadStatus, PreloadEntry, SlotRef, SlotStats};
use prometeu_hal::AssetBridge;
use prometeu_hal::color::Color;
use prometeu_hal::sample::Sample;
use prometeu_hal::sound_bank::SoundBank;
use prometeu_hal::tile_bank::{TileBank, TileSize};
use crate::memory_banks::{SoundBankPoolInstaller, TileBankPoolInstaller};
/// Resident metadata for a decoded/materialized asset inside a BankPolicy.
#[derive(Debug)]
pub struct ResidentEntry<T> {
/// The resident, materialized object.
pub value: Arc<T>,
/// Resident size in bytes (post-decode). Used for telemetry/budgets.
pub bytes: usize,
// /// Pin count (optional): if > 0, entry should not be evicted by policy.
// pub pins: u32,
/// Telemetry / profiling fields (optional but useful).
pub loads: u64,
pub last_used: Instant,
}
impl<T> ResidentEntry<T> {
pub fn new(value: Arc<T>, bytes: usize) -> Self {
Self {
value,
bytes,
// pins: 0,
loads: 1,
last_used: Instant::now(),
}
}
}
/// Encapsulates the residency and staging policy for a specific type of asset.
/// This is internal to the AssetManager and not visible to peripherals.
pub struct BankPolicy<T> {
/// Dedup table: asset_id -> resident entry (value + telemetry).
resident: Arc<RwLock<HashMap<u32, ResidentEntry<T>>>>,
/// Staging area: handle -> value ready to commit.
staging: Arc<RwLock<HashMap<HandleId, Arc<T>>>>,
}
impl<T> BankPolicy<T> {
pub fn new() -> Self {
Self {
resident: Arc::new(RwLock::new(HashMap::new())),
staging: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Try get a resident value by asset_id (dedupe path).
pub fn get_resident(&self, asset_id: u32) -> Option<Arc<T>> {
let mut map = self.resident.write().unwrap();
let entry = map.get_mut(&asset_id)?;
entry.last_used = Instant::now();
Some(Arc::clone(&entry.value))
}
/// Insert or reuse a resident entry. Returns the resident Arc<T>.
pub fn put_resident(&self, asset_id: u32, value: Arc<T>, bytes: usize) -> Arc<T> {
let mut map = self.resident.write().unwrap();
match map.get_mut(&asset_id) {
Some(existing) => {
existing.last_used = Instant::now();
existing.loads += 1;
Arc::clone(&existing.value)
}
None => {
let entry = ResidentEntry::new(Arc::clone(&value), bytes);
map.insert(asset_id, entry);
value
}
}
}
/// Place a value into staging for a given handle.
pub fn stage(&self, handle: HandleId, value: Arc<T>) {
self.staging.write().unwrap().insert(handle, value);
}
/// Take staged value (used by commit path).
pub fn take_staging(&self, handle: HandleId) -> Option<Arc<T>> {
self.staging.write().unwrap().remove(&handle)
}
pub fn clear(&self) {
self.resident.write().unwrap().clear();
self.staging.write().unwrap().clear();
}
}
pub struct AssetManager {
assets: Arc<RwLock<HashMap<u32, AssetEntry>>>,
name_to_id: Arc<RwLock<HashMap<String, u32>>>,
handles: Arc<RwLock<HashMap<HandleId, LoadHandleInfo>>>,
next_handle_id: Mutex<HandleId>,
assets_data: Arc<RwLock<Vec<u8>>>,
/// Narrow hardware interfaces
gfx_installer: Arc<dyn TileBankPoolInstaller>,
sound_installer: Arc<dyn SoundBankPoolInstaller>,
/// Track what is installed in each hardware slot (for stats/info).
gfx_slots: Arc<RwLock<[Option<u32>; 16]>>,
sound_slots: Arc<RwLock<[Option<u32>; 16]>>,
/// Residency policy for GFX tile banks.
gfx_policy: BankPolicy<TileBank>,
/// Residency policy for sound banks.
sound_policy: BankPolicy<SoundBank>,
// Commits that are ready to be applied at the next frame boundary.
pending_commits: Mutex<Vec<HandleId>>,
}
struct LoadHandleInfo {
_asset_id: u32,
slot: SlotRef,
status: LoadStatus,
}
impl AssetBridge for AssetManager {
fn initialize_for_cartridge(&self, assets: Vec<AssetEntry>, preload: Vec<PreloadEntry>, assets_data: Vec<u8>) { self.initialize_for_cartridge(assets, preload, assets_data) }
fn load(&self, asset_name: &str, slot: SlotRef) -> Result<HandleId, String> { self.load(asset_name, slot) }
fn status(&self, handle: HandleId) -> LoadStatus { self.status(handle) }
fn commit(&self, handle: HandleId) { self.commit(handle) }
fn cancel(&self, handle: HandleId) { self.cancel(handle) }
fn apply_commits(&self) { self.apply_commits() }
fn bank_info(&self, kind: BankType) -> BankStats { self.bank_info(kind) }
fn slot_info(&self, slot: SlotRef) -> SlotStats { self.slot_info(slot) }
fn find_slot_by_name(&self, asset_name: &str, kind: BankType) -> Option<u8> { self.find_slot_by_name(asset_name, kind) }
fn shutdown(&self) { self.shutdown() }
}
impl AssetManager {
pub fn new(
assets: Vec<AssetEntry>,
assets_data: Vec<u8>,
gfx_installer: Arc<dyn TileBankPoolInstaller>,
sound_installer: Arc<dyn SoundBankPoolInstaller>,
) -> Self {
let mut asset_map = HashMap::new();
let mut name_to_id = HashMap::new();
for entry in assets {
name_to_id.insert(entry.asset_name.clone(), entry.asset_id);
asset_map.insert(entry.asset_id, entry);
}
Self {
assets: Arc::new(RwLock::new(asset_map)),
name_to_id: Arc::new(RwLock::new(name_to_id)),
gfx_installer,
sound_installer,
gfx_slots: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
sound_slots: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
gfx_policy: BankPolicy::new(),
sound_policy: BankPolicy::new(),
handles: Arc::new(RwLock::new(HashMap::new())),
next_handle_id: Mutex::new(1),
assets_data: Arc::new(RwLock::new(assets_data)),
pending_commits: Mutex::new(Vec::new()),
}
}
pub fn initialize_for_cartridge(&self, assets: Vec<AssetEntry>, preload: Vec<PreloadEntry>, assets_data: Vec<u8>) {
self.shutdown();
{
let mut asset_map = self.assets.write().unwrap();
let mut name_to_id = self.name_to_id.write().unwrap();
asset_map.clear();
name_to_id.clear();
for entry in assets.iter() {
name_to_id.insert(entry.asset_name.clone(), entry.asset_id);
asset_map.insert(entry.asset_id, entry.clone());
}
}
*self.assets_data.write().unwrap() = assets_data;
// Perform Preload for assets in the preload list
for item in preload {
let entry_opt = {
let assets = self.assets.read().unwrap();
let name_to_id = self.name_to_id.read().unwrap();
name_to_id.get(&item.asset_name)
.and_then(|id| assets.get(id))
.cloned()
};
if let Some(entry) = entry_opt {
let slot_index = item.slot;
match entry.bank_type {
BankType::TILES => {
if let Ok(bank) = Self::perform_load_tile_bank(&entry, self.assets_data.clone()) {
let bank_arc = Arc::new(bank);
self.gfx_policy.put_resident(entry.asset_id, Arc::clone(&bank_arc), entry.decoded_size as usize);
self.gfx_installer.install_tile_bank(slot_index, bank_arc);
let mut slots = self.gfx_slots.write().unwrap();
if slot_index < slots.len() {
slots[slot_index] = Some(entry.asset_id);
}
println!("[AssetManager] Preloaded tile asset '{}' (id: {}) into slot {}", entry.asset_name, entry.asset_id, slot_index);
} else {
eprintln!("[AssetManager] Failed to preload tile asset '{}'", entry.asset_name);
}
}
BankType::SOUNDS => {
if let Ok(bank) = Self::perform_load_sound_bank(&entry, self.assets_data.clone()) {
let bank_arc = Arc::new(bank);
self.sound_policy.put_resident(entry.asset_id, Arc::clone(&bank_arc), entry.decoded_size as usize);
self.sound_installer.install_sound_bank(slot_index, bank_arc);
let mut slots = self.sound_slots.write().unwrap();
if slot_index < slots.len() {
slots[slot_index] = Some(entry.asset_id);
}
println!("[AssetManager] Preloaded sound asset '{}' (id: {}) into slot {}", entry.asset_name, entry.asset_id, slot_index);
} else {
eprintln!("[AssetManager] Failed to preload sound asset '{}'", entry.asset_name);
}
}
}
} else {
eprintln!("[AssetManager] Preload failed: asset '{}' not found in table", item.asset_name);
}
}
}
pub fn load(&self, asset_name: &str, slot: SlotRef) -> Result<HandleId, String> {
let entry = {
let assets = self.assets.read().unwrap();
let name_to_id = self.name_to_id.read().unwrap();
let id = name_to_id.get(asset_name).ok_or_else(|| format!("Asset not found: {}", asset_name))?;
assets.get(id).ok_or_else(|| format!("Asset ID {} not found in table", id))?.clone()
};
let asset_id = entry.asset_id;
if slot.asset_type != entry.bank_type {
return Err("INCOMPATIBLE_SLOT_KIND".to_string());
}
let mut next_id = self.next_handle_id.lock().unwrap();
let handle_id = *next_id;
*next_id += 1;
// Check if already resident (Dedup)
let already_resident = match entry.bank_type {
BankType::TILES => {
if let Some(bank) = self.gfx_policy.get_resident(asset_id) {
self.gfx_policy.stage(handle_id, bank);
true
} else { false }
}
BankType::SOUNDS => {
if let Some(bank) = self.sound_policy.get_resident(asset_id) {
self.sound_policy.stage(handle_id, bank);
true
} else { false }
}
};
if already_resident {
self.handles.write().unwrap().insert(handle_id, LoadHandleInfo {
_asset_id: asset_id,
slot,
status: LoadStatus::READY,
});
return Ok(handle_id);
}
// Not resident, start loading
self.handles.write().unwrap().insert(handle_id, LoadHandleInfo {
_asset_id: asset_id,
slot,
status: LoadStatus::PENDING,
});
let handles = self.handles.clone();
let assets_data = self.assets_data.clone();
let entry_clone = entry.clone();
// Capture policies for the worker thread
let gfx_policy_resident = Arc::clone(&self.gfx_policy.resident);
let gfx_policy_staging = Arc::clone(&self.gfx_policy.staging);
let sound_policy_resident = Arc::clone(&self.sound_policy.resident);
let sound_policy_staging = Arc::clone(&self.sound_policy.staging);
thread::spawn(move || {
// Update status to LOADING
{
let mut handles_map = handles.write().unwrap();
if let Some(h) = handles_map.get_mut(&handle_id) {
if h.status == LoadStatus::PENDING {
h.status = LoadStatus::LOADING;
} else {
return;
}
} else {
return;
}
}
match entry_clone.bank_type {
BankType::TILES => {
let result = Self::perform_load_tile_bank(&entry_clone, assets_data);
if let Ok(tilebank) = result {
let bank_arc = Arc::new(tilebank);
let resident_arc = {
let mut map = gfx_policy_resident.write().unwrap();
if let Some(existing) = map.get_mut(&asset_id) {
existing.last_used = Instant::now();
existing.loads += 1;
Arc::clone(&existing.value)
} else {
let entry = ResidentEntry::new(Arc::clone(&bank_arc), entry_clone.decoded_size as usize);
map.insert(asset_id, entry);
bank_arc
}
};
gfx_policy_staging.write().unwrap().insert(handle_id, resident_arc);
let mut handles_map = handles.write().unwrap();
if let Some(h) = handles_map.get_mut(&handle_id) {
if h.status == LoadStatus::LOADING { h.status = LoadStatus::READY; }
}
} else {
let mut handles_map = handles.write().unwrap();
if let Some(h) = handles_map.get_mut(&handle_id) { h.status = LoadStatus::ERROR; }
}
}
BankType::SOUNDS => {
let result = Self::perform_load_sound_bank(&entry_clone, assets_data);
if let Ok(soundbank) = result {
let bank_arc = Arc::new(soundbank);
let resident_arc = {
let mut map = sound_policy_resident.write().unwrap();
if let Some(existing) = map.get_mut(&asset_id) {
existing.last_used = Instant::now();
existing.loads += 1;
Arc::clone(&existing.value)
} else {
let entry = ResidentEntry::new(Arc::clone(&bank_arc), entry_clone.decoded_size as usize);
map.insert(asset_id, entry);
bank_arc
}
};
sound_policy_staging.write().unwrap().insert(handle_id, resident_arc);
let mut handles_map = handles.write().unwrap();
if let Some(h) = handles_map.get_mut(&handle_id) {
if h.status == LoadStatus::LOADING { h.status = LoadStatus::READY; }
}
} else {
let mut handles_map = handles.write().unwrap();
if let Some(h) = handles_map.get_mut(&handle_id) { h.status = LoadStatus::ERROR; }
}
}
}
});
Ok(handle_id)
}
fn perform_load_tile_bank(entry: &AssetEntry, assets_data: Arc<RwLock<Vec<u8>>>) -> Result<TileBank, String> {
if entry.codec != "RAW" {
return Err(format!("Unsupported codec: {}", entry.codec));
}
let assets_data = assets_data.read().unwrap();
let start = entry.offset as usize;
let end = start + entry.size as usize;
if end > assets_data.len() {
return Err("Asset offset/size out of bounds".to_string());
}
let buffer = &assets_data[start..end];
// Decode TILEBANK metadata
let tile_size_val = entry.metadata.get("tile_size").and_then(|v| v.as_u64()).ok_or("Missing tile_size")?;
let width = entry.metadata.get("width").and_then(|v| v.as_u64()).ok_or("Missing width")? as usize;
let height = entry.metadata.get("height").and_then(|v| v.as_u64()).ok_or("Missing height")? as usize;
let tile_size = match tile_size_val {
8 => TileSize::Size8,
16 => TileSize::Size16,
32 => TileSize::Size32,
_ => return Err(format!("Invalid tile_size: {}", tile_size_val)),
};
let pixel_data_size = width * height;
if buffer.len() < pixel_data_size + 2048 {
return Err("Buffer too small for TILEBANK".to_string());
}
let pixel_indices = buffer[0..pixel_data_size].to_vec();
let palette_data = &buffer[pixel_data_size..pixel_data_size + 2048];
let mut palettes = [[Color::BLACK; 16]; 64];
for p in 0..64 {
for c in 0..16 {
let offset = (p * 16 + c) * 2;
let color_raw = u16::from_le_bytes([palette_data[offset], palette_data[offset + 1]]);
palettes[p][c] = Color(color_raw);
}
}
Ok(TileBank {
tile_size,
width,
height,
pixel_indices,
palettes,
})
}
fn perform_load_sound_bank(entry: &AssetEntry, assets_data: Arc<RwLock<Vec<u8>>>) -> Result<SoundBank, String> {
if entry.codec != "RAW" {
return Err(format!("Unsupported codec: {}", entry.codec));
}
let assets_data = assets_data.read().unwrap();
let start = entry.offset as usize;
let end = start + entry.size as usize;
if end > assets_data.len() {
return Err("Asset offset/size out of bounds".to_string());
}
let buffer = &assets_data[start..end];
let sample_rate = entry.metadata.get("sample_rate").and_then(|v| v.as_u64()).unwrap_or(44100) as u32;
let mut data = Vec::with_capacity(buffer.len() / 2);
for i in (0..buffer.len()).step_by(2) {
if i + 1 < buffer.len() {
data.push(i16::from_le_bytes([buffer[i], buffer[i+1]]));
}
}
let sample = Arc::new(Sample::new(sample_rate, data));
Ok(SoundBank::new(vec![sample]))
}
pub fn status(&self, handle: HandleId) -> LoadStatus {
self.handles.read().unwrap().get(&handle).map(|h| h.status).unwrap_or(LoadStatus::ERROR)
}
pub fn commit(&self, handle: HandleId) {
let mut handles_map = self.handles.write().unwrap();
if let Some(h) = handles_map.get_mut(&handle) {
if h.status == LoadStatus::READY {
self.pending_commits.lock().unwrap().push(handle);
}
}
}
pub fn cancel(&self, handle: HandleId) {
let mut handles_map = self.handles.write().unwrap();
if let Some(h) = handles_map.get_mut(&handle) {
match h.status {
LoadStatus::PENDING | LoadStatus::LOADING | LoadStatus::READY => {
h.status = LoadStatus::CANCELED;
}
_ => {}
}
}
self.gfx_policy.take_staging(handle);
self.sound_policy.take_staging(handle);
}
pub fn apply_commits(&self) {
let mut pending = self.pending_commits.lock().unwrap();
let mut handles = self.handles.write().unwrap();
for handle_id in pending.drain(..) {
if let Some(h) = handles.get_mut(&handle_id) {
if h.status == LoadStatus::READY {
match h.slot.asset_type {
BankType::TILES => {
if let Some(bank) = self.gfx_policy.take_staging(handle_id) {
self.gfx_installer.install_tile_bank(h.slot.index, bank);
let mut slots = self.gfx_slots.write().unwrap();
if h.slot.index < slots.len() {
slots[h.slot.index] = Some(h._asset_id);
}
h.status = LoadStatus::COMMITTED;
}
}
BankType::SOUNDS => {
if let Some(bank) = self.sound_policy.take_staging(handle_id) {
self.sound_installer.install_sound_bank(h.slot.index, bank);
let mut slots = self.sound_slots.write().unwrap();
if h.slot.index < slots.len() {
slots[h.slot.index] = Some(h._asset_id);
}
h.status = LoadStatus::COMMITTED;
}
}
}
}
}
}
}
pub fn bank_info(&self, kind: BankType) -> BankStats {
match kind {
BankType::TILES => {
let mut used_bytes = 0;
{
let resident = self.gfx_policy.resident.read().unwrap();
for entry in resident.values() {
used_bytes += entry.bytes;
}
}
let mut inflight_bytes = 0;
{
let staging = self.gfx_policy.staging.read().unwrap();
let assets = self.assets.read().unwrap();
let handles = self.handles.read().unwrap();
for (handle_id, _) in staging.iter() {
if let Some(h) = handles.get(handle_id) {
if let Some(entry) = assets.get(&h._asset_id) {
inflight_bytes += entry.decoded_size as usize;
}
}
}
}
let mut slots_occupied = 0;
{
let slots = self.gfx_slots.read().unwrap();
for s in slots.iter() {
if s.is_some() { slots_occupied += 1; }
}
}
BankStats {
total_bytes: 16 * 1024 * 1024,
used_bytes,
free_bytes: (16usize * 1024 * 1024).saturating_sub(used_bytes),
inflight_bytes,
slot_count: 16,
slots_occupied,
}
}
BankType::SOUNDS => {
let mut used_bytes = 0;
{
let resident = self.sound_policy.resident.read().unwrap();
for entry in resident.values() {
used_bytes += entry.bytes;
}
}
let mut inflight_bytes = 0;
{
let staging = self.sound_policy.staging.read().unwrap();
let assets = self.assets.read().unwrap();
let handles = self.handles.read().unwrap();
for (handle_id, _) in staging.iter() {
if let Some(h) = handles.get(handle_id) {
if let Some(entry) = assets.get(&h._asset_id) {
inflight_bytes += entry.decoded_size as usize;
}
}
}
}
let mut slots_occupied = 0;
{
let slots = self.sound_slots.read().unwrap();
for s in slots.iter() {
if s.is_some() { slots_occupied += 1; }
}
}
BankStats {
total_bytes: 32 * 1024 * 1024,
used_bytes,
free_bytes: (32usize * 1024 * 1024).saturating_sub(used_bytes),
inflight_bytes,
slot_count: 16,
slots_occupied,
}
}
}
}
pub fn slot_info(&self, slot: SlotRef) -> SlotStats {
match slot.asset_type {
BankType::TILES => {
let slots = self.gfx_slots.read().unwrap();
let asset_id = slots.get(slot.index).and_then(|s| s.clone());
let (bytes, asset_name) = if let Some(id) = &asset_id {
let bytes = self.gfx_policy.resident.read().unwrap()
.get(id)
.map(|entry| entry.bytes)
.unwrap_or(0);
let name = self.assets.read().unwrap().get(id).map(|e| e.asset_name.clone());
(bytes, name)
} else {
(0, None)
};
SlotStats {
asset_id,
asset_name,
generation: 0,
resident_bytes: bytes,
}
}
BankType::SOUNDS => {
let slots = self.sound_slots.read().unwrap();
let asset_id = slots.get(slot.index).and_then(|s| s.clone());
let (bytes, asset_name) = if let Some(id) = &asset_id {
let bytes = self.sound_policy.resident.read().unwrap()
.get(id)
.map(|entry| entry.bytes)
.unwrap_or(0);
let name = self.assets.read().unwrap().get(id).map(|e| e.asset_name.clone());
(bytes, name)
} else {
(0, None)
};
SlotStats {
asset_id,
asset_name,
generation: 0,
resident_bytes: bytes,
}
}
}
}
pub fn find_slot_by_name(&self, asset_name: &str, kind: BankType) -> Option<u8> {
let asset_id = {
let name_to_id = self.name_to_id.read().unwrap();
*name_to_id.get(asset_name)?
};
match kind {
BankType::TILES => {
let slots = self.gfx_slots.read().unwrap();
slots.iter().position(|&s| s == Some(asset_id)).map(|p| p as u8)
}
BankType::SOUNDS => {
let slots = self.sound_slots.read().unwrap();
slots.iter().position(|&s| s == Some(asset_id)).map(|p| p as u8)
}
}
}
pub fn shutdown(&self) {
self.gfx_policy.clear();
self.sound_policy.clear();
self.handles.write().unwrap().clear();
self.pending_commits.lock().unwrap().clear();
self.gfx_slots.write().unwrap().fill(None);
self.sound_slots.write().unwrap().fill(None);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::memory_banks::{MemoryBanks, SoundBankPoolAccess, TileBankPoolAccess};
#[test]
fn test_asset_loading_flow() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let mut data = vec![1u8; 256];
data.extend_from_slice(&[0u8; 2048]);
let asset_entry = AssetEntry {
asset_id: 0,
asset_name: "test_tiles".to_string(),
bank_type: BankType::TILES,
offset: 0,
size: data.len() as u64,
decoded_size: data.len() as u64,
codec: "RAW".to_string(),
metadata: serde_json::json!({
"tile_size": 16,
"width": 16,
"height": 16
}),
};
let am = AssetManager::new(vec![asset_entry], data, gfx_installer, sound_installer);
let slot = SlotRef::gfx(0);
let handle = am.load("test_tiles", slot).expect("Should start loading");
let mut status = am.status(handle);
let start = Instant::now();
while status != LoadStatus::READY && start.elapsed().as_secs() < 5 {
thread::sleep(std::time::Duration::from_millis(10));
status = am.status(handle);
}
assert_eq!(status, LoadStatus::READY);
{
let staging = am.gfx_policy.staging.read().unwrap();
assert!(staging.contains_key(&handle));
}
am.commit(handle);
am.apply_commits();
assert_eq!(am.status(handle), LoadStatus::COMMITTED);
assert!(banks.tile_bank_slot(0).is_some());
}
#[test]
fn test_asset_dedup() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let mut data = vec![1u8; 256];
data.extend_from_slice(&[0u8; 2048]);
let asset_entry = AssetEntry {
asset_id: 0,
asset_name: "test_tiles".to_string(),
bank_type: BankType::TILES,
offset: 0,
size: data.len() as u64,
decoded_size: data.len() as u64,
codec: "RAW".to_string(),
metadata: serde_json::json!({
"tile_size": 16,
"width": 16,
"height": 16
}),
};
let am = AssetManager::new(vec![asset_entry], data, gfx_installer, sound_installer);
let handle1 = am.load("test_tiles", SlotRef::gfx(0)).unwrap();
let start = Instant::now();
while am.status(handle1) != LoadStatus::READY && start.elapsed().as_secs() < 5 {
thread::sleep(std::time::Duration::from_millis(10));
}
let handle2 = am.load("test_tiles", SlotRef::gfx(1)).unwrap();
assert_eq!(am.status(handle2), LoadStatus::READY);
let staging = am.gfx_policy.staging.read().unwrap();
let bank1 = staging.get(&handle1).unwrap();
let bank2 = staging.get(&handle2).unwrap();
assert!(Arc::ptr_eq(bank1, bank2));
}
#[test]
fn test_sound_asset_loading() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
// 100 samples of 16-bit PCM (zeros)
let data = vec![0u8; 200];
let asset_entry = AssetEntry {
asset_id: 1,
asset_name: "test_sound".to_string(),
bank_type: BankType::SOUNDS,
offset: 0,
size: data.len() as u64,
decoded_size: data.len() as u64,
codec: "RAW".to_string(),
metadata: serde_json::json!({
"sample_rate": 44100
}),
};
let am = AssetManager::new(vec![asset_entry], data, gfx_installer, sound_installer);
let slot = SlotRef::audio(0);
let handle = am.load("test_sound", slot).expect("Should start loading");
let start = Instant::now();
while am.status(handle) != LoadStatus::READY && start.elapsed().as_secs() < 5 {
thread::sleep(std::time::Duration::from_millis(10));
}
assert_eq!(am.status(handle), LoadStatus::READY);
am.commit(handle);
am.apply_commits();
assert_eq!(am.status(handle), LoadStatus::COMMITTED);
assert!(banks.sound_bank_slot(0).is_some());
}
#[test]
fn test_preload_on_init() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let data = vec![0u8; 200];
let asset_entry = AssetEntry {
asset_id: 2,
asset_name: "preload_sound".to_string(),
bank_type: BankType::SOUNDS,
offset: 0,
size: data.len() as u64,
decoded_size: data.len() as u64,
codec: "RAW".to_string(),
metadata: serde_json::json!({
"sample_rate": 44100
}),
};
let preload = vec![
PreloadEntry { asset_name: "preload_sound".to_string(), slot: 5 }
];
let am = AssetManager::new(vec![], vec![], gfx_installer, sound_installer);
// Before init, slot 5 is empty
assert!(banks.sound_bank_slot(5).is_none());
am.initialize_for_cartridge(vec![asset_entry], preload, data);
// After init, slot 5 should be occupied because of preload
assert!(banks.sound_bank_slot(5).is_some());
assert_eq!(am.slot_info(SlotRef::audio(5)).asset_id, Some(2));
}
#[test]
fn test_find_slot_by_name() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let mut data = vec![0u8; 256]; // pixels
data.extend_from_slice(&[0u8; 2048]); // palette
let asset_entry = AssetEntry {
asset_id: 10,
asset_name: "my_tiles".to_string(),
bank_type: BankType::TILES,
offset: 0,
size: data.len() as u64,
decoded_size: data.len() as u64,
codec: "RAW".to_string(),
metadata: serde_json::json!({ "tile_size": 16, "width": 16, "height": 16 }),
};
let preload = vec![
PreloadEntry { asset_name: "my_tiles".to_string(), slot: 3 }
];
let am = AssetManager::new(vec![], vec![], gfx_installer, sound_installer);
am.initialize_for_cartridge(vec![asset_entry], preload, data);
assert_eq!(am.find_slot_by_name("my_tiles", BankType::TILES), Some(3));
assert_eq!(am.find_slot_by_name("unknown", BankType::TILES), None);
assert_eq!(am.find_slot_by_name("my_tiles", BankType::SOUNDS), None);
}
}
@@ -0,0 +1,231 @@
use std::sync::Arc;
use prometeu_hal::AudioBridge;
/// Maximum number of simultaneous audio voices supported by the hardware.
pub const MAX_CHANNELS: usize = 16;
/// Standard sample rate for the final audio output.
pub const OUTPUT_SAMPLE_RATE: u32 = 48000;
/// Looping mode for samples (re-exported from the hardware contract).
pub use prometeu_hal::LoopMode;
use prometeu_hal::sample::Sample;
use crate::memory_banks::SoundBankPoolAccess;
/// State of a single playback voice (channel).
///
/// The Core maintains this state to provide information to the App (e.g., is_playing),
/// but the actual real-time mixing is performed by the Host using commands.
pub struct Channel {
/// The actual sample data being played.
pub sample: Option<Arc<Sample>>,
/// Whether this channel is currently active.
pub active: bool,
/// Current playback position within the sample (fractional for pitch shifting).
pub pos: f64,
/// Playback speed multiplier (1.0 = original speed).
pub pitch: f64,
/// Voice volume (0-255).
pub volume: u8,
/// Stereo panning (0=Full Left, 127=Center, 255=Full Right).
pub pan: u8,
/// Loop configuration for this voice.
pub loop_mode: LoopMode,
/// Playback priority (used for voice stealing policies).
pub priority: u8,
}
impl Default for Channel {
fn default() -> Self {
Self {
sample: None,
active: false,
pos: 0.0,
pitch: 1.0,
volume: 255,
pan: 127,
loop_mode: LoopMode::Off,
priority: 0,
}
}
}
/// Commands sent from the Core to the Host audio backend.
///
/// Because the Core logic runs at 60Hz and Audio is generated at 48kHz,
/// we use an asynchronous command queue to synchronize them.
pub enum AudioCommand {
/// Start playing a sample on a specific voice.
Play {
sample: Arc<Sample>,
voice_id: usize,
volume: u8,
pan: u8,
pitch: f64,
priority: u8,
loop_mode: LoopMode,
},
/// Immediately stop playback on a voice.
Stop {
voice_id: usize,
},
/// Update volume of an ongoing playback.
SetVolume {
voice_id: usize,
volume: u8,
},
/// Update panning of an ongoing playback.
SetPan {
voice_id: usize,
pan: u8,
},
/// Update pitch of an ongoing playback.
SetPitch {
voice_id: usize,
pitch: f64,
},
/// Pause all audio processing.
MasterPause,
/// Resume audio processing.
MasterResume,
}
/// PROMETEU Audio Subsystem.
///
/// Models a multi-channel PCM sampler (SPU).
/// The audio system in Prometeu is **command-based**. This means the Core
/// doesn't generate raw audio samples; instead, it sends high-level commands
/// (like `Play`, `Stop`, `SetVolume`) to a queue. The physical host backend
/// (e.g., CPAL on desktop) then consumes these commands and performs the
/// actual mixing at the native hardware sample rate.
///
/// ### Key Features:
/// - **16 Simultaneous Voices**: Independent volume, pan, and pitch.
/// - **Sample-based Synthesis**: Plays PCM data stored in SoundBanks.
/// - **Stereo Output**: 48kHz output target.
pub struct Audio {
/// Local state of the hardware voices. This state is used for logic
/// (e.g., checking if a sound is still playing) and is synchronized with the Host.
pub voices: [Channel; MAX_CHANNELS],
/// Queue of pending commands to be processed by the Host mixer.
/// This queue is typically flushed and sent to the Host once per frame.
pub commands: Vec<AudioCommand>,
/// Interface to access sound memory banks (ARAM).
pub sound_banks: Arc<dyn SoundBankPoolAccess>,
}
impl AudioBridge for Audio {
fn play(&mut self, bank_id: u8, sample_id: u16, voice_id: usize, volume: u8, pan: u8, pitch: f64, priority: u8, loop_mode: prometeu_hal::LoopMode) {
let lm = match loop_mode { prometeu_hal::LoopMode::Off => LoopMode::Off, prometeu_hal::LoopMode::On => LoopMode::On };
self.play(bank_id, sample_id, voice_id, volume, pan, pitch, priority, lm)
}
fn play_sample(&mut self, sample: Arc<Sample>, voice_id: usize, volume: u8, pan: u8, pitch: f64, priority: u8, loop_mode: prometeu_hal::LoopMode) {
let lm = match loop_mode { prometeu_hal::LoopMode::Off => LoopMode::Off, prometeu_hal::LoopMode::On => LoopMode::On };
self.play_sample(sample, voice_id, volume, pan, pitch, priority, lm)
}
fn stop(&mut self, voice_id: usize) { self.stop(voice_id) }
fn set_volume(&mut self, voice_id: usize, volume: u8) { self.set_volume(voice_id, volume) }
fn set_pan(&mut self, voice_id: usize, pan: u8) { self.set_pan(voice_id, pan) }
fn set_pitch(&mut self, voice_id: usize, pitch: f64) { self.set_pitch(voice_id, pitch) }
fn is_playing(&self, voice_id: usize) -> bool { self.is_playing(voice_id) }
fn clear_commands(&mut self) { self.clear_commands() }
}
impl Audio {
/// Initializes the audio system with empty voices and sound bank access.
pub fn new(sound_banks: Arc<dyn SoundBankPoolAccess>) -> Self {
Self {
voices: std::array::from_fn(|_| Channel::default()),
commands: Vec::new(),
sound_banks,
}
}
pub fn play(&mut self, bank_id: u8, sample_id: u16, voice_id: usize, volume: u8, pan: u8, pitch: f64, priority: u8, loop_mode: LoopMode) {
if voice_id >= MAX_CHANNELS {
return;
}
// Resolve the sample from the hardware pools
let sample = self.sound_banks.sound_bank_slot(bank_id as usize)
.and_then(|bank| bank.samples.get(sample_id as usize).map(Arc::clone));
if let Some(s) = sample {
println!("[Audio] Resolved sample from bank {} sample {}. Playing on voice {}.", bank_id, sample_id, voice_id);
self.play_sample(s, voice_id, volume, pan, pitch, priority, loop_mode);
} else {
eprintln!("[Audio] Failed to resolve sample from bank {} sample {}.", bank_id, sample_id);
}
}
pub fn play_sample(&mut self, sample: Arc<Sample>, voice_id: usize, volume: u8, pan: u8, pitch: f64, priority: u8, loop_mode: LoopMode) {
if voice_id >= MAX_CHANNELS {
return;
}
// Update local state
self.voices[voice_id] = Channel {
sample: Some(Arc::clone(&sample)),
active: true,
pos: 0.0,
pitch,
volume,
pan,
loop_mode,
priority,
};
// Push command to the host
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.voices[voice_id].active = false;
self.voices[voice_id].sample = None;
self.commands.push(AudioCommand::Stop { voice_id });
}
}
pub fn set_volume(&mut self, voice_id: usize, volume: u8) {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].volume = volume;
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.voices[voice_id].pan = pan;
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.voices[voice_id].pitch = pitch;
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].active
} else {
false
}
}
/// Clears the command queue. The Host should consume this every frame.
pub fn clear_commands(&mut self) {
self.commands.clear();
}
}
+771
View File
@@ -0,0 +1,771 @@
use crate::memory_banks::TileBankPoolAccess;
use std::sync::Arc;
use prometeu_hal::color::Color;
use prometeu_hal::GfxBridge;
use prometeu_hal::sprite::Sprite;
use prometeu_hal::tile::Tile;
use prometeu_hal::tile_bank::{TileBank, TileSize};
use prometeu_hal::tile_layer::{HudTileLayer, ScrollableTileLayer, TileMap};
/// Blending modes inspired by classic 16-bit hardware.
/// Defines how source pixels are combined with existing pixels in the framebuffer.
///
/// ### Usage Example:
/// // Draw a semi-transparent blue rectangle
/// gfx.fill_rect_blend(10, 10, 50, 50, Color::BLUE, BlendMode::Half);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BlendMode {
/// No blending: a source overwrites the destination.
#[default]
None,
/// Average: `dst = (src + dst) / 2`. Creates a semi-transparent effect.
Half,
/// Additive: `dst = clamp(dst + (src / 2))`. Good for glows/light.
HalfPlus,
/// Subtractive: `dst = clamp(dst - (src / 2))`. Good for shadows.
HalfMinus,
/// Full Additive: `dst = clamp(dst + src)`. Saturated light effect.
Full,
}
/// PROMETEU Graphics Subsystem (GFX).
///
/// Models a specialized graphics chip with a fixed resolution, double buffering,
/// and a multi-layered tile/sprite architecture.
///
/// The GFX system works by composing several "layers" into a single 16-bit
/// RGB565 framebuffer. It supports hardware-accelerated primitives (lines, rects)
/// and specialized console features like background scrolling and sprite sorting.
///
/// ### Layer Composition Order (back to front):
/// 1. **Priority 0 Sprites**: Objects behind everything else.
/// 2. **Tile Layer 0 + Priority 1 Sprites**: Background 0.
/// 3. **Tile Layer 1 + Priority 2 Sprites**: Background 1.
/// 4. **Tile Layer 2 + Priority 3 Sprites**: Background 2.
/// 5. **Tile Layer 3 + Priority 4 Sprites**: Foreground.
/// 6. **Scene Fade**: Global brightness/color filter.
/// 7. **HUD Layer**: Fixed UI elements (always on top).
/// 8. **HUD Fade**: Independent fade for the UI.
pub struct Gfx {
/// Width of the internal framebuffer in pixels.
w: usize,
/// Height of the internal framebuffer in pixels.
h: usize,
/// Front buffer: the "VRAM" currently being displayed by the Host window.
front: Vec<u16>,
/// Back buffer: the "Work RAM" where new frames are composed.
back: Vec<u16>,
/// 4 scrollable background layers. Each can have its own scroll (X, Y) and TileBank.
pub layers: [ScrollableTileLayer; 4],
/// 1 fixed layer for User Interface (HUD). It doesn't scroll.
pub hud: HudTileLayer,
/// Shared access to graphical memory banks (tiles and palettes).
pub tile_banks: Arc<dyn TileBankPoolAccess>,
/// Hardware sprite list (512 slots). Equivalent to OAM (Object Attribute Memory).
pub sprites: [Sprite; 512],
/// Scene brightness/fade level (0 = black/invisible, 31 = fully visible).
pub scene_fade_level: u8,
/// Target color for the scene fade effect (usually Black).
pub scene_fade_color: Color,
/// HUD brightness/fade level (independent from the scene).
pub hud_fade_level: u8,
/// Target color for the HUD fade effect.
pub hud_fade_color: Color,
/// Internal cache used to sort sprites into priority groups to optimize rendering.
priority_buckets: [Vec<usize>; 5],
}
impl GfxBridge for Gfx {
fn size(&self) -> (usize, usize) { self.size() }
fn front_buffer(&self) -> &[u16] { self.front_buffer() }
fn clear(&mut self, color: Color) { self.clear(color) }
fn fill_rect_blend(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color, mode: prometeu_hal::BlendMode) { let m = match mode { prometeu_hal::BlendMode::None => BlendMode::None, prometeu_hal::BlendMode::Half => BlendMode::Half, prometeu_hal::BlendMode::HalfPlus => BlendMode::HalfPlus, prometeu_hal::BlendMode::HalfMinus => BlendMode::HalfMinus, prometeu_hal::BlendMode::Full => BlendMode::Full }; self.fill_rect_blend(x, y, w, h, color, m) }
fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color) { self.fill_rect(x, y, w, h, color) }
fn draw_pixel(&mut self, x: i32, y: i32, color: Color) { self.draw_pixel(x, y, color) }
fn draw_line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, color: Color) { self.draw_line(x0, y0, x1, y1, color) }
fn draw_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color) { self.draw_circle(xc, yc, r, color) }
fn draw_circle_points(&mut self, xc: i32, yc: i32, x: i32, y: i32, color: Color) { self.draw_circle_points(xc, yc, x, y, color) }
fn fill_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color) { self.fill_circle(xc, yc, r, color) }
fn draw_circle_lines(&mut self, xc: i32, yc: i32, x: i32, y: i32, color: Color) { self.draw_circle_lines(xc, yc, x, y, color) }
fn draw_disc(&mut self, x: i32, y: i32, r: i32, border_color: Color, fill_color: Color) { self.draw_disc(x, y, r, border_color, fill_color) }
fn draw_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color) { self.draw_rect(x, y, w, h, color) }
fn draw_square(&mut self, x: i32, y: i32, w: i32, h: i32, border_color: Color, fill_color: Color) { self.draw_square(x, y, w, h, border_color, fill_color) }
fn draw_horizontal_line(&mut self, x0: i32, x1: i32, y: i32, color: Color) { self.draw_horizontal_line(x0, x1, y, color) }
fn draw_vertical_line(&mut self, x: i32, y0: i32, y1: i32, color: Color) { self.draw_vertical_line(x, y0, y1, color) }
fn present(&mut self) { self.present() }
fn render_all(&mut self) { self.render_all() }
fn render_layer(&mut self, layer_idx: usize) { self.render_layer(layer_idx) }
fn render_hud(&mut self) { self.render_hud() }
fn draw_text(&mut self, x: i32, y: i32, text: &str, color: Color) { self.draw_text(x, y, text, color) }
fn draw_char(&mut self, x: i32, y: i32, c: char, color: Color) { self.draw_char(x, y, c, color) }
fn layer(&self, index: usize) -> &ScrollableTileLayer { &self.layers[index] }
fn layer_mut(&mut self, index: usize) -> &mut ScrollableTileLayer { &mut self.layers[index] }
fn hud(&self) -> &HudTileLayer { &self.hud }
fn hud_mut(&mut self) -> &mut HudTileLayer { &mut self.hud }
fn sprite(&self, index: usize) -> &Sprite { &self.sprites[index] }
fn sprite_mut(&mut self, index: usize) -> &mut Sprite { &mut self.sprites[index] }
fn scene_fade_level(&self) -> u8 { self.scene_fade_level }
fn set_scene_fade_level(&mut self, level: u8) { self.scene_fade_level = level; }
fn scene_fade_color(&self) -> Color { self.scene_fade_color }
fn set_scene_fade_color(&mut self, color: Color) { self.scene_fade_color = color; }
fn hud_fade_level(&self) -> u8 { self.hud_fade_level }
fn set_hud_fade_level(&mut self, level: u8) { self.hud_fade_level = level; }
fn hud_fade_color(&self) -> Color { self.hud_fade_color }
fn set_hud_fade_color(&mut self, color: Color) { self.hud_fade_color = color; }
}
impl Gfx {
/// Initializes the graphics system with a specific resolution and shared memory banks.
pub fn new(w: usize, h: usize, tile_banks: Arc<dyn TileBankPoolAccess>) -> Self {
const EMPTY_SPRITE: Sprite = Sprite {
tile: 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;
let 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,
hud: HudTileLayer::new(64, 32),
tile_banks,
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)
}
/// The buffer that the host should display (RGB565).
pub fn front_buffer(&self) -> &[u16] {
&self.front
}
pub fn clear(&mut self, color: Color) {
self.back.fill(color.0);
}
/// Rectangle with blend mode.
pub fn fill_rect_blend(
&mut self,
x: i32,
y: i32,
w: i32,
h: i32,
color: Color,
mode: BlendMode,
) {
if color == Color::COLOR_KEY { return; }
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);
}
}
}
/// 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);
}
/// Draws a single pixel.
pub fn draw_pixel(&mut self, x: i32, y: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if x >= 0 && x < self.w as i32 && y >= 0 && y < self.h as i32 {
self.back[y as usize * self.w + x as usize] = color.0;
}
}
/// Draws a line between two points using Bresenham's algorithm.
pub fn draw_line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
let dx = (x1 - x0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -(y1 - y0).abs();
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx + dy;
let mut x = x0;
let mut y = y0;
loop {
self.draw_pixel(x, y, color);
if x == x1 && y == y1 { break; }
let e2 = 2 * err;
if e2 >= dy {
err += dy;
x += sx;
}
if e2 <= dx {
err += dx;
y += sy;
}
}
}
/// Draws a circle outline using Midpoint Circle Algorithm.
pub fn draw_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if r < 0 { return; }
let mut x = 0;
let mut y = r;
let mut d = 3 - 2 * r;
self.draw_circle_points(xc, yc, x, y, color);
while y >= x {
x += 1;
if d > 0 {
y -= 1;
d = d + 4 * (x - y) + 10;
} else {
d = d + 4 * x + 6;
}
self.draw_circle_points(xc, yc, x, y, color);
}
}
fn draw_circle_points(&mut self, xc: i32, yc: i32, x: i32, y: i32, color: Color) {
self.draw_pixel(xc + x, yc + y, color);
self.draw_pixel(xc - x, yc + y, color);
self.draw_pixel(xc + x, yc - y, color);
self.draw_pixel(xc - x, yc - y, color);
self.draw_pixel(xc + y, yc + x, color);
self.draw_pixel(xc - y, yc + x, color);
self.draw_pixel(xc + y, yc - x, color);
self.draw_pixel(xc - y, yc - x, color);
}
/// Draws a filled circle.
pub fn fill_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if r < 0 { return; }
let mut x = 0;
let mut y = r;
let mut d = 3 - 2 * r;
self.draw_circle_lines(xc, yc, x, y, color);
while y >= x {
x += 1;
if d > 0 {
y -= 1;
d = d + 4 * (x - y) + 10;
} else {
d = d + 4 * x + 6;
}
self.draw_circle_lines(xc, yc, x, y, color);
}
}
fn draw_circle_lines(&mut self, xc: i32, yc: i32, x: i32, y: i32, color: Color) {
self.draw_horizontal_line(xc - x, xc + x, yc + y, color);
self.draw_horizontal_line(xc - x, xc + x, yc - y, color);
self.draw_horizontal_line(xc - y, xc + y, yc + x, color);
self.draw_horizontal_line(xc - y, xc + y, yc - x, color);
}
/// Draws a disc (filled circle with border).
pub fn draw_disc(&mut self, x: i32, y: i32, r: i32, border_color: Color, fill_color: Color) {
self.fill_circle(x, y, r, fill_color);
self.draw_circle(x, y, r, border_color);
}
/// Draws a rectangle outline.
pub fn draw_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if w <= 0 || h <= 0 { return; }
self.draw_horizontal_line(x, x + w - 1, y, color);
self.draw_horizontal_line(x, x + w - 1, y + h - 1, color);
self.draw_vertical_line(x, y, y + h - 1, color);
self.draw_vertical_line(x + w - 1, y, y + h - 1, color);
}
/// Draws a square (filled rectangle with border).
pub fn draw_square(&mut self, x: i32, y: i32, w: i32, h: i32, border_color: Color, fill_color: Color) {
self.fill_rect(x, y, w, h, fill_color);
self.draw_rect(x, y, w, h, border_color);
}
fn draw_horizontal_line(&mut self, x0: i32, x1: i32, y: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if y < 0 || y >= self.h as i32 { return; }
let start = x0.max(0);
let end = x1.min(self.w as i32 - 1);
if start > end { return; }
for x in start..=end {
self.back[y as usize * self.w + x as usize] = color.0;
}
}
fn draw_vertical_line(&mut self, x: i32, y0: i32, y1: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if x < 0 || x >= self.w as i32 { return; }
let start = y0.max(0);
let end = y1.min(self.h as i32 - 1);
if start > end { return; }
for y in start..=end {
self.back[y as usize * self.w + x as usize] = color.0;
}
}
/// Double buffer swap (O(1), no pixel copying).
/// Typically called by the Host when it's time to display the finished frame.
pub fn present(&mut self) {
std::mem::swap(&mut self.front, &mut self.back);
}
/// The main rendering pipeline.
///
/// This method composes the final frame by rasterizing layers and sprites in the
/// correct priority order into the back buffer.
/// Follows the hardware model where layers and sprites are composed every frame.
pub fn render_all(&mut self) {
// 0. Preparation Phase: Filter and group sprites by their priority levels.
// This avoids iterating through all 512 sprites for every layer.
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. Priority 0 sprites: drawn at the very back, behind everything else.
Self::draw_bucket_on_buffer(&mut self.back, self.w, self.h, &self.priority_buckets[0], &self.sprites, &*self.tile_banks);
// 2. Main layers and prioritized sprites.
// Order: Layer 0 -> Sprites 1 -> Layer 1 -> Sprites 2 ...
for i in 0..self.layers.len() {
let bank_id = self.layers[i].bank_id as usize;
if let Some(bank) = self.tile_banks.tile_bank_slot(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);
}
// Draw sprites that belong to this depth level
Self::draw_bucket_on_buffer(&mut self.back, self.w, self.h, &self.priority_buckets[i + 1], &self.sprites, &*self.tile_banks);
}
// 4. Scene Fade: Applies a color blend to the entire world (excluding HUD).
Self::apply_fade_to_buffer(&mut self.back, self.scene_fade_level, self.scene_fade_color);
// 5. HUD: The fixed interface layer, always drawn on top of the world.
Self::render_hud_with_pool(&mut self.back, self.w, self.h, &self.hud, &*self.tile_banks);
// 6. HUD Fade: Independent fade effect for the UI.
Self::apply_fade_to_buffer(&mut self.back, self.hud_fade_level, self.hud_fade_color);
}
/// Renders a specific game layer.
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.tile_banks.tile_bank_slot(bank_id) {
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);
}
/// Renders the HUD (fixed position, no scroll).
pub fn render_hud(&mut self) {
Self::render_hud_with_pool(&mut self.back, self.w, self.h, &self.hud, &*self.tile_banks);
}
fn render_hud_with_pool(back: &mut [u16], w: usize, h: usize, hud: &HudTileLayer, tile_banks: &dyn TileBankPoolAccess) {
let bank_id = hud.bank_id as usize;
let bank = match tile_banks.tile_bank_slot(bank_id) {
Some(b) => b,
_ => return,
};
Self::draw_tile_map(back, w, h, &hud.map, &bank, 0, 0);
}
/// Rasterizes a TileMap into the provided pixel buffer using scrolling.
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. Determine the range of visible tiles based on the scroll position.
// We add a margin of 1 tile to ensure smooth pixel-perfect scrolling at the borders.
let visible_tiles_x = (screen_w / tile_size) + 1;
let visible_tiles_y = (screen_h / tile_size) + 1;
// 2. Calculate offsets within the tilemap.
let start_tile_x = scroll_x / tile_size as i32;
let start_tile_y = scroll_y / tile_size as i32;
// 3. Fine scroll: how many pixels the tiles are shifted within the first visible cell.
let fine_scroll_x = scroll_x % tile_size as i32;
let fine_scroll_y = scroll_y % tile_size as i32;
// 4. Iterate only through the tiles that are actually visible on screen.
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;
// Bounds check: don't draw if the camera is outside the map.
if map_x >= map.width || map_y >= map.height { continue; }
let tile = map.tiles[map_y * map.width + map_x];
// Optimized skip for empty (ID 0) tiles.
if tile.id == 0 { continue; }
// 5. Project the tile pixels to screen space.
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);
}
}
}
/// Internal helper to copy a single tile's pixels to the framebuffer.
/// Handles flipping and palette resolution.
fn draw_tile_pixels(back: &mut [u16], screen_w: usize, screen_h: usize, x: i32, y: i32, tile: 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; }
// Handle flip flags by reversing the fetch coordinates.
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. Get the pixel color index (0-15) from the bank.
let px_index = bank.get_pixel_index(tile.id, fetch_x, fetch_y);
// 2. Hardware rule: Color index 0 is always fully transparent.
if px_index == 0 { continue; }
// 3. Resolve the virtual index to a real RGB565 color using the tile's assigned palette.
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],
tile_banks: &dyn TileBankPoolAccess,
) {
for &idx in bucket {
let s = &sprites[idx];
let bank_id = s.bank_id as usize;
if let Some(bank) = tile_banks.tile_bank_slot(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
) {
// ... (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);
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. Get index
let px_index = bank.get_pixel_index(sprite.tile.id, fetch_x, fetch_y);
// 2. Transparency
if px_index == 0 { continue; }
// 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();
}
}
}
/// 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; } // Fully visible, skip processing
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);
// 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;
*px = Color::pack_from_native(r, g, b);
}
}
pub fn draw_text(&mut self, x: i32, y: i32, text: &str, color: Color) {
let mut cx = x;
for c in text.chars() {
self.draw_char(cx, y, c, color);
cx += 4;
}
}
fn draw_char(&mut self, x: i32, y: i32, c: char, color: Color) {
let glyph: [u8; 5] = match c.to_ascii_uppercase() {
'0' => [0x7, 0x5, 0x5, 0x5, 0x7],
'1' => [0x2, 0x6, 0x2, 0x2, 0x7],
'2' => [0x7, 0x1, 0x7, 0x4, 0x7],
'3' => [0x7, 0x1, 0x7, 0x1, 0x7],
'4' => [0x5, 0x5, 0x7, 0x1, 0x1],
'5' => [0x7, 0x4, 0x7, 0x1, 0x7],
'6' => [0x7, 0x4, 0x7, 0x5, 0x7],
'7' => [0x7, 0x1, 0x1, 0x1, 0x1],
'8' => [0x7, 0x5, 0x7, 0x5, 0x7],
'9' => [0x7, 0x5, 0x7, 0x1, 0x7],
'A' => [0x7, 0x5, 0x7, 0x5, 0x5],
'B' => [0x6, 0x5, 0x6, 0x5, 0x6],
'C' => [0x7, 0x4, 0x4, 0x4, 0x7],
'D' => [0x6, 0x5, 0x5, 0x5, 0x6],
'E' => [0x7, 0x4, 0x6, 0x4, 0x7],
'F' => [0x7, 0x4, 0x6, 0x4, 0x4],
'G' => [0x7, 0x4, 0x5, 0x5, 0x7],
'H' => [0x5, 0x5, 0x7, 0x5, 0x5],
'I' => [0x7, 0x2, 0x2, 0x2, 0x7],
'J' => [0x1, 0x1, 0x1, 0x5, 0x2],
'K' => [0x5, 0x5, 0x6, 0x5, 0x5],
'L' => [0x4, 0x4, 0x4, 0x4, 0x7],
'M' => [0x5, 0x7, 0x5, 0x5, 0x5],
'N' => [0x5, 0x5, 0x5, 0x5, 0x5],
'O' => [0x7, 0x5, 0x5, 0x5, 0x7],
'P' => [0x7, 0x5, 0x7, 0x4, 0x4],
'Q' => [0x7, 0x5, 0x5, 0x7, 0x1],
'R' => [0x7, 0x5, 0x6, 0x5, 0x5],
'S' => [0x7, 0x4, 0x7, 0x1, 0x7],
'T' => [0x7, 0x2, 0x2, 0x2, 0x2],
'U' => [0x5, 0x5, 0x5, 0x5, 0x7],
'V' => [0x5, 0x5, 0x5, 0x5, 0x2],
'W' => [0x5, 0x5, 0x5, 0x7, 0x5],
'X' => [0x5, 0x5, 0x2, 0x5, 0x5],
'Y' => [0x5, 0x5, 0x2, 0x2, 0x2],
'Z' => [0x7, 0x1, 0x2, 0x4, 0x7],
':' => [0x0, 0x2, 0x0, 0x2, 0x0],
'.' => [0x0, 0x0, 0x0, 0x0, 0x2],
',' => [0x0, 0x0, 0x0, 0x2, 0x4],
'!' => [0x2, 0x2, 0x2, 0x0, 0x2],
'?' => [0x7, 0x1, 0x2, 0x0, 0x2],
' ' => [0x0, 0x0, 0x0, 0x0, 0x0],
'|' => [0x2, 0x2, 0x2, 0x2, 0x2],
'/' => [0x1, 0x1, 0x2, 0x4, 0x4],
'(' => [0x2, 0x4, 0x4, 0x4, 0x2],
')' => [0x2, 0x1, 0x1, 0x1, 0x2],
'>' => [0x4, 0x2, 0x1, 0x2, 0x4],
'<' => [0x1, 0x2, 0x4, 0x2, 0x1],
_ => [0x7, 0x7, 0x7, 0x7, 0x7],
};
for (row_idx, row) in glyph.iter().enumerate() {
for col_idx in 0..3 {
if (row >> (2 - col_idx)) & 1 == 1 {
let px = x + col_idx as i32;
let py = y + row_idx as i32;
self.draw_pixel(px, py, color);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::memory_banks::MemoryBanks;
#[test]
fn test_draw_pixel() {
let banks = Arc::new(MemoryBanks::new());
let mut gfx = Gfx::new(10, 10, banks);
gfx.draw_pixel(5, 5, Color::WHITE);
assert_eq!(gfx.back[5 * 10 + 5], Color::WHITE.0);
// Out of bounds should not panic
gfx.draw_pixel(-1, -1, Color::WHITE);
gfx.draw_pixel(10, 10, Color::WHITE);
}
#[test]
fn test_draw_line() {
let banks = Arc::new(MemoryBanks::new());
let mut gfx = Gfx::new(10, 10, banks);
gfx.draw_line(0, 0, 9, 9, Color::WHITE);
assert_eq!(gfx.back[0], Color::WHITE.0);
assert_eq!(gfx.back[9 * 10 + 9], Color::WHITE.0);
}
#[test]
fn test_draw_rect() {
let banks = Arc::new(MemoryBanks::new());
let mut gfx = Gfx::new(10, 10, banks);
gfx.draw_rect(0, 0, 10, 10, Color::WHITE);
assert_eq!(gfx.back[0], Color::WHITE.0);
assert_eq!(gfx.back[9], Color::WHITE.0);
assert_eq!(gfx.back[90], Color::WHITE.0);
assert_eq!(gfx.back[99], Color::WHITE.0);
}
#[test]
fn test_fill_circle() {
let banks = Arc::new(MemoryBanks::new());
let mut gfx = Gfx::new(10, 10, banks);
gfx.fill_circle(5, 5, 2, Color::WHITE);
assert_eq!(gfx.back[5 * 10 + 5], Color::WHITE.0);
}
#[test]
fn test_draw_square() {
let banks = Arc::new(MemoryBanks::new());
let mut gfx = Gfx::new(10, 10, banks);
gfx.draw_square(2, 2, 6, 6, Color::WHITE, Color::BLACK);
// Border
assert_eq!(gfx.back[2 * 10 + 2], Color::WHITE.0);
// Fill
assert_eq!(gfx.back[3 * 10 + 3], Color::BLACK.0);
}
}
/// 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,
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,74 @@
use std::sync::Arc;
use prometeu_hal::{AssetBridge, AudioBridge, GfxBridge, HardwareBridge, PadBridge, TouchBridge};
use crate::asset::AssetManager;
use crate::audio::Audio;
use crate::gfx::Gfx;
use crate::memory_banks::{MemoryBanks, SoundBankPoolAccess, SoundBankPoolInstaller, TileBankPoolAccess, TileBankPoolInstaller};
use crate::pad::Pad;
use crate::touch::Touch;
/// Aggregate structure for all virtual hardware peripherals.
///
/// This struct represents the "Mainboard" of the PROMETEU console.
/// It acts as a container for all hardware subsystems. In the Prometeu
/// architecture, hardware is decoupled from the OS and VM, allowing
/// for easier testing and different host implementations (Desktop, Web, etc.).
///
/// ### Console Specifications:
/// - **Resolution**: 320x180 (16:9 Aspect Ratio).
/// - **Color Depth**: RGB565 (16-bit).
/// - **Audio**: Stereo, Command-based mixing.
/// - **Input**: 12-button Digital Gamepad + Absolute Touch/Mouse.
pub struct Hardware {
/// The Graphics Processing Unit (GPU). Handles drawing primitives, sprites, and tilemaps.
pub gfx: Gfx,
/// The Sound Processing Unit (SPU). Manages sample playback and volume control.
pub audio: Audio,
/// The standard digital gamepad. Provides state for D-Pad, face buttons, and triggers.
pub pad: Pad,
/// The absolute pointer input device (Mouse/Touchscreen).
pub touch: Touch,
/// The Asset Management system (DMA). Handles loading data into VRAM (TileBanks) and ARAM (SoundBanks).
pub assets: AssetManager,
}
impl HardwareBridge for Hardware {
fn gfx(&self) -> &dyn GfxBridge { &self.gfx }
fn gfx_mut(&mut self) -> &mut dyn GfxBridge { &mut self.gfx }
fn audio(&self) -> &dyn AudioBridge { &self.audio }
fn audio_mut(&mut self) -> &mut dyn AudioBridge { &mut self.audio }
fn pad(&self) -> &dyn PadBridge { &self.pad }
fn pad_mut(&mut self) -> &mut dyn PadBridge { &mut self.pad }
fn touch(&self) -> &dyn TouchBridge { &self.touch }
fn touch_mut(&mut self) -> &mut dyn TouchBridge { &mut self.touch }
fn assets(&self) -> &dyn AssetBridge { &self.assets }
fn assets_mut(&mut self) -> &mut dyn AssetBridge { &mut self.assets }
}
impl Hardware {
/// Internal hardware width in pixels.
pub const W: usize = 320;
/// Internal hardware height in pixels.
pub const H: usize = 180;
/// Creates a fresh hardware instance with default settings.
pub fn new() -> Self {
let memory_banks = Arc::new(MemoryBanks::new());
Self {
gfx: Gfx::new(Self::W, Self::H, Arc::clone(&memory_banks) as Arc<dyn TileBankPoolAccess>),
audio: Audio::new(Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolAccess>),
pad: Pad::default(),
touch: Touch::default(),
assets: AssetManager::new(
vec![],
vec![],
Arc::clone(&memory_banks) as Arc<dyn TileBankPoolInstaller>,
Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolInstaller>,
),
}
}
}
@@ -0,0 +1,13 @@
mod asset;
mod gfx;
mod pad;
mod touch;
mod audio;
mod memory_banks;
pub mod hardware;
pub use crate::asset::AssetManager;
pub use crate::audio::{Audio, AudioCommand, Channel, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
pub use crate::gfx::Gfx;
pub use crate::memory_banks::MemoryBanks;
pub use crate::pad::Pad;
@@ -0,0 +1,91 @@
use std::sync::{Arc, RwLock};
use prometeu_hal::sound_bank::SoundBank;
use prometeu_hal::tile_bank::TileBank;
/// Non-generic interface for peripherals to access graphical tile banks.
pub trait TileBankPoolAccess: Send + Sync {
/// Returns a reference to the resident TileBank in the specified slot, if any.
fn tile_bank_slot(&self, slot: usize) -> Option<Arc<TileBank>>;
/// Returns the total number of slots available in this bank.
fn tile_bank_slot_count(&self) -> usize;
}
/// Non-generic interface for the AssetManager to install graphical tile banks.
pub trait TileBankPoolInstaller: Send + Sync {
/// Atomically swaps the resident TileBank in the specified slot.
fn install_tile_bank(&self, slot: usize, bank: Arc<TileBank>);
}
/// Non-generic interface for peripherals to access sound banks.
pub trait SoundBankPoolAccess: Send + Sync {
/// Returns a reference to the resident SoundBank in the specified slot, if any.
fn sound_bank_slot(&self, slot: usize) -> Option<Arc<SoundBank>>;
/// Returns the total number of slots available in this bank.
fn sound_bank_slot_count(&self) -> usize;
}
/// Non-generic interface for the AssetManager to install sound banks.
pub trait SoundBankPoolInstaller: Send + Sync {
/// Atomically swaps the resident SoundBank in the specified slot.
fn install_sound_bank(&self, slot: usize, bank: Arc<SoundBank>);
}
/// Centralized container for all hardware memory banks.
///
/// MemoryBanks represent the actual hardware slot state.
/// Peripherals consume this state via narrow, non-generic traits.
/// AssetManager coordinates residency and installs assets into these slots.
pub struct MemoryBanks {
tile_bank_pool: Arc<RwLock<[Option<Arc<TileBank>>; 16]>>,
sound_bank_pool: Arc<RwLock<[Option<Arc<SoundBank>>; 16]>>,
}
impl MemoryBanks {
/// Creates a new set of memory banks with empty slots.
pub fn new() -> Self {
Self {
tile_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
sound_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
}
}
}
impl TileBankPoolAccess for MemoryBanks {
fn tile_bank_slot(&self, slot: usize) -> Option<Arc<TileBank>> {
let pool = self.tile_bank_pool.read().unwrap();
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
}
fn tile_bank_slot_count(&self) -> usize {
16
}
}
impl TileBankPoolInstaller for MemoryBanks {
fn install_tile_bank(&self, slot: usize, bank: Arc<TileBank>) {
let mut pool = self.tile_bank_pool.write().unwrap();
if slot < 16 {
pool[slot] = Some(bank);
}
}
}
impl SoundBankPoolAccess for MemoryBanks {
fn sound_bank_slot(&self, slot: usize) -> Option<Arc<SoundBank>> {
let pool = self.sound_bank_pool.read().unwrap();
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
}
fn sound_bank_slot_count(&self) -> usize {
16
}
}
impl SoundBankPoolInstaller for MemoryBanks {
fn install_sound_bank(&self, slot: usize, bank: Arc<SoundBank>) {
let mut pool = self.sound_bank_pool.write().unwrap();
if slot < 16 {
pool[slot] = Some(bank);
}
}
}
@@ -0,0 +1,70 @@
use prometeu_hal::{InputSignals, PadBridge};
use prometeu_hal::button::Button;
#[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 PadBridge for Pad {
fn begin_frame(&mut self, signals: &InputSignals) { self.begin_frame(signals) }
fn any(&self) -> bool { self.any() }
fn up(&self) -> &Button { &self.up }
fn down(&self) -> &Button { &self.down }
fn left(&self) -> &Button { &self.left }
fn right(&self) -> &Button { &self.right }
fn a(&self) -> &Button { &self.a }
fn b(&self) -> &Button { &self.b }
fn x(&self) -> &Button { &self.x }
fn y(&self) -> &Button { &self.y }
fn l(&self) -> &Button { &self.l }
fn r(&self) -> &Button { &self.r }
fn start(&self) -> &Button { &self.start }
fn select(&self) -> &Button { &self.select }
}
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);
}
pub fn any(&self) -> bool {
self.a.down
|| self.b.down
|| self.x.down
|| self.y.down
|| self.l.down
|| self.r.down
|| self.start.down
|| self.select.down
}
}
@@ -0,0 +1,25 @@
use prometeu_hal::{InputSignals, TouchBridge};
use prometeu_hal::button::Button;
#[derive(Default, Clone, Copy, Debug)]
pub struct Touch {
pub f: Button,
pub x: i32,
pub y: i32,
}
impl Touch {
/// 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();
self.y = signals.y_pos.clone();
}
}
impl TouchBridge for Touch {
fn begin_frame(&mut self, signals: &InputSignals) { self.begin_frame(signals) }
fn f(&self) -> &Button { &self.f }
fn x(&self) -> i32 { self.x }
fn y(&self) -> i32 { self.y }
}
@@ -0,0 +1,74 @@
// use std::fs;
// use std::path::Path;
// use prometeu_abi::{Value, VmFault};
// use prometeu_drivers::hardware::Hardware;
// use prometeu_hal::{HostContext, HostReturn, NativeInterface};
// use prometeu_vm::{LogicalFrameEndingReason, VirtualMachine};
//
// struct MockNative;
// impl NativeInterface for MockNative {
// fn syscall(&mut self, id: u32, _args: &[Value], ret: &mut HostReturn, _ctx: &mut HostContext) -> Result<(), VmFault> {
// if id == 0x2010 { // InputPadSnapshot
// for _ in 0..48 {
// ret.push_bool(false);
// }
// } else if id == 0x2011 { // InputTouchSnapshot
// for _ in 0..6 {
// ret.push_int(0);
// }
// } else {
// // Push one result for others that might expect it
// // Based on results_count() in syscalls.rs, most return 1 except GfxClear565 (0)
// if id != 0x1010 {
// ret.push_null();
// }
// }
// Ok(())
// }
// }
//
// #[test]
// fn test_canonical_cartridge_heartbeat() {
// let mut pbc_path = Path::new("../../test-cartridges/canonical/golden/program.pbc").to_path_buf();
// if !pbc_path.exists() {
// pbc_path = Path::new("test-cartridges/canonical/golden/program.pbc").to_path_buf();
// }
//
// let pbc_bytes = fs::read(pbc_path).expect("Failed to read canonical PBC. Did you run the generation test?");
//
// // Determine entrypoint from the compiled module exports
// let entry_symbol = "src/main/modules:frame";
//
// let mut vm = VirtualMachine::new(vec![], vec![]);
// vm.initialize(pbc_bytes, entry_symbol).expect("Failed to initialize VM with canonical cartridge");
// vm.prepare_call(entry_symbol);
//
// let mut native = MockNative;
// let mut hw = Hardware::new();
// let mut ctx = HostContext::new(Some(&mut hw));
//
// // Run for a reasonable budget
// let report = vm.run_budget(1000, &mut native, &mut ctx).expect("VM failed to run");
//
// // Acceptance criteria:
// // 1. No traps
// match report.reason {
// LogicalFrameEndingReason::Trap(trap) => panic!("VM trapped: {:?}", trap),
// LogicalFrameEndingReason::Panic(msg) => panic!("VM panicked: {}", msg),
// LogicalFrameEndingReason::Halted => {},
// LogicalFrameEndingReason::EndOfRom => {},
// LogicalFrameEndingReason::FrameSync => {},
// LogicalFrameEndingReason::BudgetExhausted => {},
// LogicalFrameEndingReason::Breakpoint => {},
// }
//
// // 2. Deterministic output state (if any)
// // Observação: a PVM agora sinaliza FRAME_SYNC imediatamente antes do RET do entry point.
// // Quando o motivo é FRAME_SYNC, não exigimos pilha vazia (a limpeza final ocorre após o RET).
// // Para os demais motivos (RET/Halted/EndOfRom), a pilha deve estar vazia para frame(): void.
// if !matches!(report.reason, LogicalFrameEndingReason::FrameSync) {
// assert_eq!(vm.operand_stack.len(), 0, "Stack should be empty after frame() execution");
// }
//
// println!("Heartbeat test passed!");
// }
@@ -0,0 +1,15 @@
[package]
name = "prometeu-firmware"
version = "0.1.0"
edition = "2024"
license.workspace = true
[dependencies]
prometeu-drivers = { path = "../prometeu-drivers" }
prometeu-vm = { path = "../prometeu-vm" }
prometeu-system = { path = "../prometeu-system" }
prometeu-bytecode = { path = "../../compiler/prometeu-bytecode" }
prometeu-abi = { path = "../../compiler/prometeu-abi" }
prometeu-hal = { path = "../prometeu-hal" }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
@@ -0,0 +1,11 @@
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BootTarget {
Hub,
Cartridge { path: String, debug: bool, debug_port: u16 },
}
impl Default for BootTarget {
fn default() -> Self {
Self::Hub
}
}
@@ -0,0 +1,157 @@
use prometeu_hal::telemetry::CertificationConfig;
use prometeu_hal::{HardwareBridge, InputSignals};
use prometeu_hal::cartridge::Cartridge;
use prometeu_system::{PrometeuHub, VirtualMachineRuntime};
use prometeu_vm::VirtualMachine;
use crate::firmware::boot_target::BootTarget;
use crate::firmware::firmware_state::{FirmwareState, LoadCartridgeStep, ResetStep};
use crate::firmware::prometeu_context::PrometeuContext;
/// PROMETEU Firmware.
///
/// The central orchestrator of the console. The firmware acts as the
/// "Control Unit", managing the high-level state machine of the system.
///
/// It is responsible for transitioning between different modes of operation,
/// such as showing the splash screen, running the Hub (launcher), or
/// executing a game/app.
///
/// ### Execution Loop:
/// The firmware is designed to be ticked once per frame (60Hz). During each
/// tick, it:
/// 1. Updates peripherals with the latest input signals.
/// 2. Delegates the logic update to the current active state.
/// 3. Handles state transitions (e.g., from Loading to Playing).
pub struct Firmware {
/// The execution engine (PVM) for user applications.
pub vm: VirtualMachine,
/// The underlying OS services (Syscalls, Filesystem, Telemetry).
pub os: VirtualMachineRuntime,
/// The internal state of the system launcher (Hub).
pub hub: PrometeuHub,
/// The current operational state (e.g., Reset, SplashScreen, GameRunning).
pub state: FirmwareState,
/// The desired application to run after boot (Hub or specific Cartridge).
pub boot_target: BootTarget,
/// State-machine lifecycle tracker.
state_initialized: bool,
}
impl Firmware {
/// Initializes the firmware in the `Reset` state.
pub fn new(cap_config: Option<CertificationConfig>) -> Self {
Self {
vm: VirtualMachine::default(),
os: VirtualMachineRuntime::new(cap_config),
hub: PrometeuHub::new(),
state: FirmwareState::Reset(ResetStep),
boot_target: BootTarget::Hub,
state_initialized: false,
}
}
/// The main entry point for the Host to advance the system logic.
///
/// This method is called exactly once per Host frame (60Hz).
/// It updates peripheral signals and delegates the logic to the current state.
pub fn tick(&mut self, signals: &InputSignals, hw: &mut dyn HardwareBridge) {
// 0. Process asset commits at the beginning of the frame boundary.
hw.assets_mut().apply_commits();
// 1. Update the peripheral state using the latest signals from the Host.
// This ensures input is consistent throughout the entire update.
hw.pad_mut().begin_frame(signals);
hw.touch_mut().begin_frame(signals);
// 2. State machine lifecycle management.
if !self.state_initialized {
self.on_enter(signals, hw);
self.state_initialized = true;
}
// 3. Update the current state and check for transitions.
if let Some(next_state) = self.on_update(signals, hw) {
self.change_state(next_state, signals, hw);
}
}
/// Transitions the system to a new state, handling lifecycle hooks.
pub fn change_state(&mut self, new_state: FirmwareState, signals: &InputSignals, hw: &mut dyn HardwareBridge) {
self.on_exit(signals, hw);
self.state = new_state;
self.state_initialized = false;
// Enter the new state immediately to avoid "empty" frames during transitions.
self.on_enter(signals, hw);
self.state_initialized = true;
}
/// Dispatches the `on_enter` event to the current state implementation.
fn on_enter(&mut self, signals: &InputSignals, hw: &mut dyn HardwareBridge) {
let mut req = PrometeuContext {
vm: &mut self.vm,
os: &mut self.os,
hub: &mut self.hub,
boot_target: &self.boot_target,
signals,
hw,
};
match &mut self.state {
FirmwareState::Reset(s) => s.on_enter(&mut req),
FirmwareState::SplashScreen(s) => s.on_enter(&mut req),
FirmwareState::LaunchHub(s) => s.on_enter(&mut req),
FirmwareState::HubHome(s) => s.on_enter(&mut req),
FirmwareState::LoadCartridge(s) => s.on_enter(&mut req),
FirmwareState::GameRunning(s) => s.on_enter(&mut req),
FirmwareState::AppCrashes(s) => s.on_enter(&mut req),
}
}
/// Dispatches the `on_update` event to the current state implementation.
/// Returns an optional `FirmwareState` if a transition is requested.
fn on_update(&mut self, signals: &InputSignals, hw: &mut dyn HardwareBridge) -> Option<FirmwareState> {
let mut req = PrometeuContext {
vm: &mut self.vm,
os: &mut self.os,
hub: &mut self.hub,
boot_target: &self.boot_target,
signals,
hw,
};
match &mut self.state {
FirmwareState::Reset(s) => s.on_update(&mut req),
FirmwareState::SplashScreen(s) => s.on_update(&mut req),
FirmwareState::LaunchHub(s) => s.on_update(&mut req),
FirmwareState::HubHome(s) => s.on_update(&mut req),
FirmwareState::LoadCartridge(s) => s.on_update(&mut req),
FirmwareState::GameRunning(s) => s.on_update(&mut req),
FirmwareState::AppCrashes(s) => s.on_update(&mut req),
}
}
/// Dispatches the `on_exit` event to the current state implementation.
fn on_exit(&mut self, signals: &InputSignals, hw: &mut dyn HardwareBridge) {
let mut req = PrometeuContext {
vm: &mut self.vm,
os: &mut self.os,
hub: &mut self.hub,
boot_target: &self.boot_target,
signals,
hw,
};
match &mut self.state {
FirmwareState::Reset(s) => s.on_exit(&mut req),
FirmwareState::SplashScreen(s) => s.on_exit(&mut req),
FirmwareState::LaunchHub(s) => s.on_exit(&mut req),
FirmwareState::HubHome(s) => s.on_exit(&mut req),
FirmwareState::LoadCartridge(s) => s.on_exit(&mut req),
FirmwareState::GameRunning(s) => s.on_exit(&mut req),
FirmwareState::AppCrashes(s) => s.on_exit(&mut req),
}
}
pub fn load_cartridge(&mut self, cartridge: Cartridge) {
self.state = FirmwareState::LoadCartridge(LoadCartridgeStep { cartridge });
self.state_initialized = false;
}
}
@@ -0,0 +1,18 @@
pub use crate::firmware::firmware_step_crash_screen::AppCrashesStep;
pub use crate::firmware::firmware_step_game_running::GameRunningStep;
pub use crate::firmware::firmware_step_hub_home::HubHomeStep;
pub use crate::firmware::firmware_step_launch_hub::LaunchHubStep;
pub use crate::firmware::firmware_step_load_cartridge::LoadCartridgeStep;
pub use crate::firmware::firmware_step_reset::ResetStep;
pub use crate::firmware::firmware_step_splash_screen::SplashScreenStep;
#[derive(Debug, Clone)]
pub enum FirmwareState {
Reset(ResetStep),
SplashScreen(SplashScreenStep),
LaunchHub(LaunchHubStep),
HubHome(HubHomeStep),
LoadCartridge(LoadCartridgeStep),
GameRunning(GameRunningStep),
AppCrashes(AppCrashesStep),
}
@@ -0,0 +1,35 @@
use prometeu_hal::log::{LogLevel, LogSource};
use prometeu_hal::color::Color;
use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
use crate::firmware::prometeu_context::PrometeuContext;
#[derive(Debug, Clone)]
pub struct AppCrashesStep {
pub error: String,
}
impl AppCrashesStep {
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
ctx.os.log(LogLevel::Error, LogSource::Pos, 0, format!("App Crashed: {}", self.error));
}
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
// Update peripherals for input on the crash screen
ctx.hw.pad_mut().begin_frame(ctx.signals);
// Error screen: red background, white text
ctx.hw.gfx_mut().clear(Color::RED);
// For now we just log or show something simple
// In the future, use draw_text
ctx.hw.gfx_mut().present();
// If START is pressed, return to the Hub
if ctx.hw.pad().start().down {
return Some(FirmwareState::LaunchHub(LaunchHubStep));
}
None
}
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
}
@@ -0,0 +1,24 @@
use prometeu_hal::log::{LogLevel, LogSource};
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState};
use crate::firmware::prometeu_context::PrometeuContext;
#[derive(Debug, Clone)]
pub struct GameRunningStep;
impl GameRunningStep {
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Entering GameRunning".to_string());
}
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
let result = ctx.os.tick(ctx.vm, ctx.signals, ctx.hw);
if !ctx.os.logical_frame_active {
ctx.hw.gfx_mut().present();
}
result.map(|err| FirmwareState::AppCrashes(AppCrashesStep { error: err }))
}
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
}
@@ -0,0 +1,41 @@
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState};
use crate::firmware::prometeu_context::PrometeuContext;
use prometeu_hal::log::{LogLevel, LogSource};
#[derive(Debug, Clone)]
pub struct HubHomeStep;
impl HubHomeStep {
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
ctx.os.log(LogLevel::Info, LogSource::Hub, 0, "Entering HubHome".to_string());
}
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
let mut error = None;
// 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 runs here, drawing over the Hub background
error = ctx.os.tick(ctx.vm, ctx.signals, ctx.hw);
}
}
// Renders the System App window borders
ctx.hub.render(ctx.os, ctx.hw);
ctx.hw.gfx_mut().present();
if let Some(err) = error {
return Some(FirmwareState::AppCrashes(AppCrashesStep { error: err }));
}
None
}
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
}
@@ -0,0 +1,33 @@
use crate::firmware::boot_target::BootTarget;
use crate::firmware::firmware_state::{FirmwareState, HubHomeStep, LoadCartridgeStep};
use crate::firmware::prometeu_context::PrometeuContext;
use prometeu_hal::log::{LogLevel, LogSource};
use prometeu_hal::cartridge_loader::CartridgeLoader;
#[derive(Debug, Clone)]
pub struct LaunchHubStep;
impl LaunchHubStep {
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Launching Hub".to_string());
ctx.hub.init();
}
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
if let BootTarget::Cartridge { path, .. } = ctx.boot_target {
match CartridgeLoader::load(path) {
Ok(cartridge) => {
// 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) => {
ctx.os.log(LogLevel::Error, LogSource::Pos, 0, format!("Failed to auto-load cartridge: {:?}", e));
}
}
}
Some(FirmwareState::HubHome(HubHomeStep))
}
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
}
@@ -0,0 +1,45 @@
use crate::firmware::firmware_state::{FirmwareState, GameRunningStep, HubHomeStep};
use crate::firmware::prometeu_context::PrometeuContext;
use prometeu_hal::log::{LogLevel, LogSource};
use prometeu_hal::cartridge::{AppMode, Cartridge};
use prometeu_hal::color::Color;
use prometeu_hal::window::Rect;
#[derive(Debug, Clone)]
pub struct LoadCartridgeStep {
pub cartridge: Cartridge,
}
impl LoadCartridgeStep {
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, format!("Loading cartridge: {}", self.cartridge.title));
// Initialize Asset Manager
ctx.hw.assets_mut().initialize_for_cartridge(
self.cartridge.asset_table.clone(),
self.cartridge.preload.clone(),
self.cartridge.assets.clone()
);
ctx.os.initialize_vm(ctx.vm, &self.cartridge);
}
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
if self.cartridge.app_mode == AppMode::System {
let id = ctx.hub.window_manager.add_window(
self.cartridge.title.clone(),
Rect { x: 40, y: 20, w: 240, h: 140 },
Color::WHITE
);
ctx.hub.window_manager.set_focus(id);
// 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));
}
Some(FirmwareState::GameRunning(GameRunningStep))
}
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
}
@@ -0,0 +1,23 @@
use prometeu_hal::log::{LogLevel, LogSource};
use crate::firmware::boot_target::BootTarget;
use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep, SplashScreenStep};
use crate::firmware::prometeu_context::PrometeuContext;
#[derive(Debug, Clone)]
pub struct ResetStep;
impl ResetStep {
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Firmware Reset".to_string());
ctx.os.reset(ctx.vm);
}
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
match ctx.boot_target {
BootTarget::Hub => Some(FirmwareState::SplashScreen(SplashScreenStep { frame: 0 })),
BootTarget::Cartridge { .. } => Some(FirmwareState::LaunchHub(LaunchHubStep)),
}
}
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
}
@@ -0,0 +1,60 @@
use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
use crate::firmware::prometeu_context::PrometeuContext;
use prometeu_hal::log::{LogLevel, LogSource};
use prometeu_hal::color::Color;
#[derive(Debug, Clone)]
pub struct SplashScreenStep {
pub frame: u32,
}
impl SplashScreenStep {
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Showing SplashScreen".to_string());
// Play sound on enter
// ctx.hw.audio_mut().play(0, 0, 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 second at 60fps
const TOTAL_DURATION: u32 = 240; // 4 seconds total (updated from 2s based on total_duration logic)
// Update peripherals for input
ctx.hw.pad_mut().begin_frame(ctx.signals);
// Clear screen
ctx.hw.gfx_mut().clear(Color::BLACK);
// Draw expanding square
let (sw, sh) = ctx.hw.gfx().size();
let max_size = (sw.min(sh) as i32 / 2).max(1);
let current_size = if self.frame < ANIMATION_DURATION {
(max_size * (self.frame as i32 + 1)) / ANIMATION_DURATION as i32
} else {
max_size
};
let x = (sw as i32 - current_size) / 2;
let y = (sh as i32 - current_size) / 2;
ctx.hw.gfx_mut().fill_rect(x, y, current_size, current_size, Color::WHITE);
ctx.hw.gfx_mut().present();
// 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));
}
if self.frame >= TOTAL_DURATION {
return Some(FirmwareState::LaunchHub(LaunchHubStep));
}
self.frame += 1;
None
}
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
}
@@ -0,0 +1,17 @@
mod firmware;
pub mod firmware_state;
mod boot_target;
pub(crate) mod firmware_step_reset;
pub(crate) mod firmware_step_splash_screen;
pub(crate) mod firmware_step_launch_hub;
pub(crate) mod firmware_step_hub_home;
pub(crate) mod firmware_step_load_cartridge;
pub(crate) mod firmware_step_game_running;
pub(crate) mod firmware_step_crash_screen;
mod prometeu_context;
pub use boot_target::BootTarget;
pub use firmware::Firmware;
pub use firmware_state::FirmwareState;
pub use prometeu_context::PrometeuContext;
@@ -0,0 +1,13 @@
use prometeu_hal::{HardwareBridge, InputSignals};
use prometeu_system::{PrometeuHub, VirtualMachineRuntime};
use prometeu_vm::VirtualMachine;
use crate::firmware::boot_target::BootTarget;
pub struct PrometeuContext<'a> {
pub vm: &'a mut VirtualMachine,
pub os: &'a mut VirtualMachineRuntime,
pub hub: &'a mut PrometeuHub,
pub boot_target: &'a BootTarget,
pub signals: &'a InputSignals,
pub hw: &'a mut dyn HardwareBridge,
}
@@ -0,0 +1,3 @@
pub mod firmware;
pub use firmware::*;
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "prometeu-hal"
version = "0.1.0"
edition = "2024"
license.workspace = true
[dependencies]
prometeu-abi = { path = "../../compiler/prometeu-abi" }
prometeu-bytecode = { path = "../../compiler/prometeu-bytecode" }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
+80
View File
@@ -0,0 +1,80 @@
use serde::{Deserialize, Serialize};
pub type HandleId = u32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[allow(non_camel_case_types)]
pub enum BankType {
TILES,
SOUNDS,
// TILEMAPS,
// BLOBS,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AssetEntry {
pub asset_id: u32,
pub asset_name: String,
pub bank_type: BankType,
pub offset: u64,
pub size: u64,
pub decoded_size: u64,
pub codec: String, // e.g., "RAW"
pub metadata: serde_json::Value,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PreloadEntry {
pub asset_name: String,
pub slot: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LoadStatus {
PENDING,
LOADING,
READY,
COMMITTED,
CANCELED,
ERROR,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BankStats {
pub total_bytes: usize,
pub used_bytes: usize,
pub free_bytes: usize,
pub inflight_bytes: usize,
pub slot_count: usize,
pub slots_occupied: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SlotStats {
pub asset_id: Option<u32>,
pub asset_name: Option<String>,
pub generation: u32,
pub resident_bytes: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SlotRef {
pub asset_type: BankType,
pub index: usize,
}
impl SlotRef {
pub fn gfx(index: usize) -> Self {
Self {
asset_type: BankType::TILES,
index,
}
}
pub fn audio(index: usize) -> Self {
Self {
asset_type: BankType::SOUNDS,
index,
}
}
}
@@ -0,0 +1,19 @@
use crate::asset::{AssetEntry, BankStats, BankType, HandleId, LoadStatus, PreloadEntry, SlotRef, SlotStats};
pub trait AssetBridge {
fn initialize_for_cartridge(
&self,
assets: Vec<AssetEntry>,
preload: Vec<PreloadEntry>,
assets_data: Vec<u8>,
);
fn load(&self, asset_name: &str, slot: SlotRef) -> Result<HandleId, String>;
fn status(&self, handle: HandleId) -> LoadStatus;
fn commit(&self, handle: HandleId);
fn cancel(&self, handle: HandleId);
fn apply_commits(&self);
fn bank_info(&self, kind: BankType) -> BankStats;
fn slot_info(&self, slot: SlotRef) -> SlotStats;
fn find_slot_by_name(&self, asset_name: &str, kind: BankType) -> Option<u8>;
fn shutdown(&self);
}
@@ -0,0 +1,38 @@
use std::sync::Arc;
use crate::sample::Sample;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopMode {
Off,
On,
}
pub trait AudioBridge {
fn play(
&mut self,
bank_id: u8,
sample_id: u16,
voice_id: usize,
volume: u8,
pan: u8,
pitch: f64,
priority: u8,
loop_mode: LoopMode,
);
fn play_sample(
&mut self,
sample: Arc<Sample>,
voice_id: usize,
volume: u8,
pan: u8,
pitch: f64,
priority: u8,
loop_mode: LoopMode,
);
fn stop(&mut self, voice_id: usize);
fn set_volume(&mut self, voice_id: usize, volume: u8);
fn set_pan(&mut self, voice_id: usize, pan: u8);
fn set_pitch(&mut self, voice_id: usize, pitch: f64);
fn is_playing(&self, voice_id: usize) -> bool;
fn clear_commands(&mut self);
}
+41
View File
@@ -0,0 +1,41 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum ButtonId {
Up = 0,
Down = 1,
Left = 2,
Right = 3,
A = 4,
B = 5,
X = 6,
Y = 7,
L = 8,
R = 9,
Start = 10,
Select = 11,
}
#[repr(C)]
#[derive(Default, Clone, Copy, Debug)]
pub struct Button {
pub pressed: bool,
pub released: bool,
pub down: bool,
pub hold_frames: u16,
}
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,77 @@
use crate::asset::{AssetEntry, PreloadEntry};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum AppMode {
Game,
System,
}
#[derive(Debug, Clone)]
pub struct Cartridge {
pub app_id: u32,
pub title: String,
pub app_version: String,
pub app_mode: AppMode,
pub entrypoint: String,
pub program: Vec<u8>,
pub assets: Vec<u8>,
pub asset_table: Vec<AssetEntry>,
pub preload: Vec<PreloadEntry>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CartridgeDTO {
pub app_id: u32,
pub title: String,
pub app_version: String,
pub app_mode: AppMode,
pub entrypoint: String,
pub program: Vec<u8>,
pub assets: Vec<u8>,
#[serde(default)]
pub asset_table: Vec<AssetEntry>,
#[serde(default)]
pub preload: Vec<PreloadEntry>,
}
impl From<CartridgeDTO> for Cartridge {
fn from(dto: CartridgeDTO) -> Self {
Self {
app_id: dto.app_id,
title: dto.title,
app_version: dto.app_version,
app_mode: dto.app_mode,
entrypoint: dto.entrypoint,
program: dto.program,
assets: dto.assets,
asset_table: dto.asset_table,
preload: dto.preload,
}
}
}
#[derive(Debug)]
pub enum CartridgeError {
NotFound,
InvalidFormat,
InvalidManifest,
UnsupportedVersion,
MissingProgram,
IoError,
}
#[derive(Deserialize)]
pub struct CartridgeManifest {
pub magic: String,
pub cartridge_version: u32,
pub app_id: u32,
pub title: String,
pub app_version: String,
pub app_mode: AppMode,
pub entrypoint: String,
#[serde(default)]
pub asset_table: Vec<AssetEntry>,
#[serde(default)]
pub preload: Vec<PreloadEntry>,
}
@@ -0,0 +1,80 @@
use std::fs;
use std::path::Path;
use crate::cartridge::{Cartridge, CartridgeDTO, CartridgeError, CartridgeManifest};
pub struct CartridgeLoader;
impl CartridgeLoader {
pub fn load(path: impl AsRef<Path>) -> Result<Cartridge, CartridgeError> {
let path = path.as_ref();
if !path.exists() {
return Err(CartridgeError::NotFound);
}
if path.is_dir() {
DirectoryCartridgeLoader::load(path)
} else if path.extension().is_some_and(|ext| ext == "pmc") {
PackedCartridgeLoader::load(path)
} else {
Err(CartridgeError::InvalidFormat)
}
}
}
pub struct DirectoryCartridgeLoader;
impl DirectoryCartridgeLoader {
pub fn load(path: &Path) -> Result<Cartridge, CartridgeError> {
let manifest_path = path.join("manifest.json");
if !manifest_path.exists() {
return Err(CartridgeError::InvalidManifest);
}
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)?;
// Additional validation as per requirements
if manifest.magic != "PMTU" {
return Err(CartridgeError::InvalidManifest);
}
if manifest.cartridge_version != 1 {
return Err(CartridgeError::UnsupportedVersion);
}
let program_path = path.join("program.pbc");
if !program_path.exists() {
return Err(CartridgeError::MissingProgram);
}
let program = fs::read(program_path).map_err(|_| CartridgeError::IoError)?;
let assets_pa_path = path.join("assets.pa");
let assets = if assets_pa_path.exists() {
fs::read(assets_pa_path).map_err(|_| CartridgeError::IoError)?
} else {
Vec::new()
};
let dto = CartridgeDTO {
app_id: manifest.app_id,
title: manifest.title,
app_version: manifest.app_version,
app_mode: manifest.app_mode,
entrypoint: manifest.entrypoint,
program,
assets,
asset_table: manifest.asset_table,
preload: manifest.preload,
};
Ok(Cartridge::from(dto))
}
}
pub struct PackedCartridgeLoader;
impl PackedCartridgeLoader {
pub fn load(_path: &Path) -> Result<Cartridge, CartridgeError> {
Err(CartridgeError::InvalidFormat)
}
}
+76
View File
@@ -0,0 +1,76 @@
/// Represents a 16-bit color in the RGB565 format.
///
/// The RGB565 format is a common high-color representation for embedded systems:
/// - **Red**: 5 bits (0..31)
/// - **Green**: 6 bits (0..63)
/// - **Blue**: 5 bits (0..31)
///
/// Prometeu does not have a hardware alpha channel. Transparency is achieved
/// by using a specific color key (Magenta / 0xF81F) which the GFX engine
/// skips during rendering.
#[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;
/// 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) {
let r = ((px >> 11) & 0x1F) as u8;
let g = ((px >> 5) & 0x3F) as u8;
let b = (px & 0x1F) as u8;
(r, g, b)
}
/// 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)
}
/// 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;
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
}
pub const fn hex(self) -> i32 {
let (r5, g6, b5) = Self::unpack_to_native(self.0);
let r8 = ((r5 as u32) << 3) | ((r5 as u32) >> 2);
let g8 = ((g6 as u32) << 2) | ((g6 as u32) >> 4);
let b8 = ((b5 as u32) << 3) | ((b5 as u32) >> 2);
let hex = r8 << 16 | g8 << 8 | b8;
hex as i32
}
}
@@ -0,0 +1,145 @@
use serde::{Deserialize, Serialize};
use prometeu_abi::Value;
use crate::cartridge::AppMode;
pub const DEVTOOLS_PROTOCOL_VERSION: u32 = 1;
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum DebugCommand {
#[serde(rename = "ok")]
Ok,
#[serde(rename = "start")]
Start,
#[serde(rename = "pause")]
Pause,
#[serde(rename = "resume")]
Resume,
#[serde(rename = "step")]
Step,
#[serde(rename = "stepFrame")]
StepFrame,
#[serde(rename = "getState")]
GetState,
#[serde(rename = "setBreakpoint")]
SetBreakpoint { pc: usize },
#[serde(rename = "listBreakpoints")]
ListBreakpoints,
#[serde(rename = "clearBreakpoint")]
ClearBreakpoint { pc: usize },
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum DebugResponse {
#[serde(rename = "handshake")]
Handshake {
protocol_version: u32,
runtime_version: String,
cartridge: HandshakeCartridge,
},
#[serde(rename = "getState")]
GetState {
pc: usize,
stack_top: Vec<Value>,
frame_index: u64,
app_id: u32,
},
#[serde(rename = "breakpoints")]
Breakpoints {
pcs: Vec<usize>,
},
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HandshakeCartridge {
pub app_id: u32,
pub title: String,
pub app_version: String,
pub app_mode: AppMode,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "event")]
pub enum DebugEvent {
#[serde(rename = "breakpointHit")]
BreakpointHit {
pc: usize,
frame_index: u64,
},
#[serde(rename = "log")]
Log {
level: String,
source: String,
msg: String,
},
#[serde(rename = "telemetry")]
Telemetry {
frame_index: u64,
vm_steps: u32,
syscalls: u32,
cycles: u64,
cycles_budget: u64,
host_cpu_time_us: u64,
violations: u32,
gfx_used_bytes: usize,
gfx_inflight_bytes: usize,
gfx_slots_occupied: u32,
audio_used_bytes: usize,
audio_inflight_bytes: usize,
audio_slots_occupied: u32,
},
#[serde(rename = "cert")]
Cert {
rule: String,
used: u64,
limit: u64,
frame_index: u64,
},
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_telemetry_event_serialization() {
let event = DebugEvent::Telemetry {
frame_index: 10,
vm_steps: 100,
syscalls: 5,
cycles: 5000,
cycles_budget: 10000,
host_cpu_time_us: 1200,
violations: 0,
gfx_used_bytes: 1024,
gfx_inflight_bytes: 0,
gfx_slots_occupied: 1,
audio_used_bytes: 2048,
audio_inflight_bytes: 0,
audio_slots_occupied: 2,
};
let json = serde_json::to_string(&event).unwrap();
assert!(json.contains("\"event\":\"telemetry\""));
assert!(json.contains("\"cycles\":5000"));
assert!(json.contains("\"cycles_budget\":10000"));
}
#[test]
fn test_get_state_serialization() {
let resp = DebugResponse::GetState {
pc: 42,
stack_top: vec![Value::Int64(10), Value::String("test".into()), Value::Boolean(true)],
frame_index: 5,
app_id: 1,
};
let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains("\"type\":\"getState\""));
assert!(json.contains("\"pc\":42"));
assert!(json.contains("\"stack_top\":[10,\"test\",true]"));
assert!(json.contains("\"frame_index\":5"));
assert!(json.contains("\"app_id\":1"));
}
}
@@ -0,0 +1,53 @@
use crate::color::Color;
use crate::sprite::Sprite;
use crate::tile_layer::{HudTileLayer, ScrollableTileLayer};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlendMode {
None,
Half,
HalfPlus,
HalfMinus,
Full,
}
pub trait GfxBridge {
fn size(&self) -> (usize, usize);
fn front_buffer(&self) -> &[u16];
fn clear(&mut self, color: Color);
fn fill_rect_blend(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color, mode: BlendMode);
fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color);
fn draw_pixel(&mut self, x: i32, y: i32, color: Color);
fn draw_line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, color: Color);
fn draw_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color);
fn draw_circle_points(&mut self, xc: i32, yc: i32, x: i32, y: i32, color: Color);
fn fill_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color);
fn draw_circle_lines(&mut self, xc: i32, yc: i32, x: i32, y: i32, color: Color);
fn draw_disc(&mut self, x: i32, y: i32, r: i32, border_color: Color, fill_color: Color);
fn draw_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color);
fn draw_square(&mut self, x: i32, y: i32, w: i32, h: i32, border_color: Color, fill_color: Color);
fn draw_horizontal_line(&mut self, x0: i32, x1: i32, y: i32, color: Color);
fn draw_vertical_line(&mut self, x: i32, y0: i32, y1: i32, color: Color);
fn present(&mut self);
fn render_all(&mut self);
fn render_layer(&mut self, layer_idx: usize);
fn render_hud(&mut self);
fn draw_text(&mut self, x: i32, y: i32, text: &str, color: Color);
fn draw_char(&mut self, x: i32, y: i32, c: char, color: Color);
fn layer(&self, index: usize) -> &ScrollableTileLayer;
fn layer_mut(&mut self, index: usize) -> &mut ScrollableTileLayer;
fn hud(&self) -> &HudTileLayer;
fn hud_mut(&mut self) -> &mut HudTileLayer;
fn sprite(&self, index: usize) -> &Sprite;
fn sprite_mut(&mut self, index: usize) -> &mut Sprite;
fn scene_fade_level(&self) -> u8;
fn set_scene_fade_level(&mut self, level: u8);
fn scene_fade_color(&self) -> Color;
fn set_scene_fade_color(&mut self, color: Color);
fn hud_fade_level(&self) -> u8;
fn set_hud_fade_level(&mut self, level: u8);
fn hud_fade_color(&self) -> Color;
fn set_hud_fade_color(&mut self, color: Color);
}
@@ -0,0 +1,22 @@
use crate::asset_bridge::AssetBridge;
use crate::audio_bridge::AudioBridge;
use crate::gfx_bridge::GfxBridge;
use crate::pad_bridge::PadBridge;
use crate::touch_bridge::TouchBridge;
pub trait HardwareBridge {
fn gfx(&self) -> &dyn GfxBridge;
fn gfx_mut(&mut self) -> &mut dyn GfxBridge;
fn audio(&self) -> &dyn AudioBridge;
fn audio_mut(&mut self) -> &mut dyn AudioBridge;
fn pad(&self) -> &dyn PadBridge;
fn pad_mut(&mut self) -> &mut dyn PadBridge;
fn touch(&self) -> &dyn TouchBridge;
fn touch_mut(&mut self) -> &mut dyn TouchBridge;
fn assets(&self) -> &dyn AssetBridge;
fn assets_mut(&mut self) -> &mut dyn AssetBridge;
}
@@ -0,0 +1,24 @@
use prometeu_abi::VmFault;
use crate::hardware_bridge::HardwareBridge;
pub struct HostContext<'a> {
pub hw: Option<&'a mut dyn HardwareBridge>,
}
impl<'a> HostContext<'a> {
pub fn new(hw: Option<&'a mut dyn HardwareBridge>) -> Self {
Self { hw }
}
#[inline]
pub fn require_hw(&mut self) -> Result<&mut dyn HardwareBridge, VmFault> {
match &mut self.hw {
Some(hw) => Ok(*hw),
None => Err(VmFault::Unavailable),
}
}
}
pub trait HostContextProvider {
fn make_ctx(&'_ mut self) -> HostContext<'_>;
}
@@ -0,0 +1,34 @@
use prometeu_abi::Value;
use prometeu_abi::VmFault;
pub struct HostReturn<'a> {
stack: &'a mut Vec<Value>
}
impl<'a> HostReturn<'a> {
pub fn new(stack: &'a mut Vec<Value>) -> Self {
Self { stack }
}
pub fn push_bool(&mut self, v: bool) {
self.stack.push(Value::Boolean(v));
}
pub fn push_int(&mut self, v: i64) {
self.stack.push(Value::Int64(v));
}
pub fn push_bounded(&mut self, v: u32) -> Result<(), VmFault> {
if v > 0xFFFF {
return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_OOB, "Bounded value overflow".into()));
}
self.stack.push(Value::Bounded(v));
Ok(())
}
pub fn push_null(&mut self) {
self.stack.push(Value::Null);
}
pub fn push_gate(&mut self, g: usize) {
self.stack.push(Value::Gate(g));
}
pub fn push_string(&mut self, s: String) {
self.stack.push(Value::String(s));
}
}
@@ -0,0 +1,23 @@
#[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,
}
+39
View File
@@ -0,0 +1,39 @@
pub mod asset_bridge;
pub mod audio_bridge;
pub mod gfx_bridge;
pub mod hardware_bridge;
pub mod host_context;
pub mod host_return;
pub mod native_interface;
pub mod pad_bridge;
pub mod touch_bridge;
pub mod native_helpers;
pub mod input_signals;
pub mod cartridge;
pub mod cartridge_loader;
pub mod debugger_protocol;
pub mod asset;
pub mod color;
pub mod button;
pub mod tile;
pub mod tile_layer;
pub mod tile_bank;
pub mod sound_bank;
pub mod sprite;
pub mod sample;
pub mod window;
pub mod syscalls;
pub mod telemetry;
pub mod log;
pub use asset_bridge::AssetBridge;
pub use audio_bridge::{AudioBridge, LoopMode};
pub use gfx_bridge::{BlendMode, GfxBridge};
pub use hardware_bridge::HardwareBridge;
pub use host_context::{HostContext, HostContextProvider};
pub use host_return::HostReturn;
pub use input_signals::InputSignals;
pub use native_interface::{NativeInterface, SyscallId};
pub use pad_bridge::PadBridge;
pub use touch_bridge::TouchBridge;
pub use native_helpers::{expect_bool, expect_bounded, expect_int};
@@ -0,0 +1,12 @@
use crate::log::{LogLevel, LogSource};
#[derive(Debug, Clone)]
pub struct LogEvent {
pub seq: u64,
pub ts_ms: u64,
pub frame: u64,
pub level: LogLevel,
pub source: LogSource,
pub tag: u16,
pub msg: String,
}
@@ -0,0 +1,8 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
}
@@ -0,0 +1,93 @@
use std::collections::VecDeque;
use crate::log::{LogEvent, LogLevel, LogSource};
pub struct LogService {
events: VecDeque<LogEvent>,
capacity: usize,
next_seq: u64,
}
impl LogService {
pub fn new(capacity: usize) -> Self {
Self {
events: VecDeque::with_capacity(capacity),
capacity,
next_seq: 0,
}
}
pub fn log(&mut self, ts_ms: u64, frame: u64, level: LogLevel, source: LogSource, tag: u16, msg: String) {
if self.events.len() >= self.capacity {
self.events.pop_front();
}
self.events.push_back(LogEvent {
seq: self.next_seq,
ts_ms,
frame,
level,
source,
tag,
msg,
});
self.next_seq += 1;
}
pub fn get_recent(&self, n: usize) -> Vec<LogEvent> {
self.events.iter().rev().take(n).cloned().collect::<Vec<_>>().into_iter().rev().collect()
}
pub fn get_after(&self, seq: u64) -> Vec<LogEvent> {
self.events.iter().filter(|e| e.seq > seq).cloned().collect()
}
pub fn last_seq(&self) -> Option<u64> {
self.events.back().map(|e| e.seq)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ring_buffer_capacity() {
let mut service = LogService::new(3);
service.log(100, 1, LogLevel::Info, LogSource::Pos, 0, "Log 1".to_string());
service.log(110, 1, LogLevel::Info, LogSource::Pos, 0, "Log 2".to_string());
service.log(120, 1, LogLevel::Info, LogSource::Pos, 0, "Log 3".to_string());
assert_eq!(service.events.len(), 3);
assert_eq!(service.events[0].msg, "Log 1");
service.log(130, 1, LogLevel::Info, LogSource::Pos, 0, "Log 4".to_string());
assert_eq!(service.events.len(), 3);
assert_eq!(service.events[0].msg, "Log 2");
assert_eq!(service.events[2].msg, "Log 4");
}
#[test]
fn test_get_recent() {
let mut service = LogService::new(10);
for i in 0..5 {
service.log(i as u64, 1, LogLevel::Info, LogSource::Pos, 0, format!("Log {}", i));
}
let recent = service.get_recent(2);
assert_eq!(recent.len(), 2);
assert_eq!(recent[0].msg, "Log 3");
assert_eq!(recent[1].msg, "Log 4");
}
#[test]
fn test_get_after() {
let mut service = LogService::new(10);
for i in 0..5 {
service.log(i as u64, 1, LogLevel::Info, LogSource::Pos, 0, format!("Log {}", i));
}
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");
}
}
@@ -0,0 +1,8 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogSource {
Pos,
Hub,
Vm,
Fs,
App { app_id: u32 },
}
@@ -0,0 +1,9 @@
mod log_level;
mod log_source;
mod log_event;
mod log_service;
pub use log_event::LogEvent;
pub use log_level::LogLevel;
pub use log_service::LogService;
pub use log_source::LogSource;
@@ -0,0 +1,26 @@
use prometeu_abi::Value;
use prometeu_abi::VmFault;
pub fn expect_bounded(args: &[Value], idx: usize) -> Result<u32, VmFault> {
args.get(idx)
.and_then(|v| match v {
Value::Bounded(b) => Some(*b),
_ => None,
})
.ok_or_else(|| VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, format!("Expected bounded at index {}", idx)))
}
pub fn expect_int(args: &[Value], idx: usize) -> Result<i64, VmFault> {
args.get(idx)
.and_then(|v| v.as_integer())
.ok_or_else(|| VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, format!("Expected integer at index {}", idx)))
}
pub fn expect_bool(args: &[Value], idx: usize) -> Result<bool, VmFault> {
args.get(idx)
.and_then(|v| match v {
Value::Boolean(b) => Some(*b),
_ => None,
})
.ok_or_else(|| VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, format!("Expected boolean at index {}", idx)))
}
@@ -0,0 +1,14 @@
use prometeu_abi::{Value, VmFault};
use crate::host_context::HostContext;
use crate::host_return::HostReturn;
pub type SyscallId = u32;
pub trait NativeInterface {
/// Dispatches a syscall from the Virtual Machine to the native implementation.
///
/// ABI Rule: Arguments for the syscall are passed in `args`.
///
/// Returns are written via `ret`.
fn syscall(&mut self, id: SyscallId, args: &[Value], ret: &mut HostReturn, ctx: &mut HostContext) -> Result<(), VmFault>;
}
@@ -0,0 +1,20 @@
use crate::button::Button;
use crate::input_signals::InputSignals;
pub trait PadBridge {
fn begin_frame(&mut self, signals: &InputSignals);
fn any(&self) -> bool;
fn up(&self) -> &Button;
fn down(&self) -> &Button;
fn left(&self) -> &Button;
fn right(&self) -> &Button;
fn a(&self) -> &Button;
fn b(&self) -> &Button;
fn x(&self) -> &Button;
fn y(&self) -> &Button;
fn l(&self) -> &Button;
fn r(&self) -> &Button;
fn start(&self) -> &Button;
fn select(&self) -> &Button;
}
+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()
}
}
@@ -0,0 +1,16 @@
use std::sync::Arc;
use crate::sample::Sample;
/// A container for audio assets.
///
/// A SoundBank stores multiple audio samples that can be played by the
/// audio subsystem.
pub struct SoundBank {
pub samples: Vec<Arc<Sample>>,
}
impl SoundBank {
pub fn new(samples: Vec<Arc<Sample>>) -> Self {
Self { samples }
}
}
+13
View File
@@ -0,0 +1,13 @@
use crate::tile::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,
}
+381
View File
@@ -0,0 +1,381 @@
/// Enumeration of all System Calls (Syscalls) available in the Prometeu environment.
///
/// Syscalls are the primary mechanism for a program running in the Virtual Machine
/// to interact with the outside world (Hardware, OS, Filesystem).
///
/// Each Syscall has a unique 32-bit ID. The IDs are grouped by category:
/// - **0x0xxx**: System & OS Control
/// - **0x1xxx**: Graphics (GFX)
/// - **0x2xxx**: Input (Gamepad & Touch)
/// - **0x3xxx**: Audio (PCM & Mixing)
/// - **0x4xxx**: Filesystem (Sandboxed I/O)
/// - **0x5xxx**: Logging & Debugging
/// - **0x6xxx**: Asset Loading & Memory Banks
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum Syscall {
// --- System ---
/// Checks if a cartridge is currently inserted in the virtual slot.
SystemHasCart = 0x0001,
/// Requests the OS to launch a specific cartridge.
SystemRunCart = 0x0002,
// --- GFX (Graphics) ---
/// Fills the entire back buffer with a single color.
GfxClear = 0x1001,
/// Draws a solid rectangle.
GfxFillRect = 0x1002,
/// Draws a 1-pixel wide line.
GfxDrawLine = 0x1003,
/// Draws a circle outline.
GfxDrawCircle = 0x1004,
/// Draws a filled circle (disc).
GfxDrawDisc = 0x1005,
/// Draws a rectangle outline.
GfxDrawSquare = 0x1006,
/// Configures one of the 512 hardware sprites.
GfxSetSprite = 0x1007,
/// Draws a text string at the specified coordinates.
GfxDrawText = 0x1008,
/// Fills the entire back buffer with a single RGB565 color (flattened).
GfxClear565 = 0x1010,
// --- Input ---
/// Returns the current raw state of the digital gamepad (bitmask).
InputGetPad = 0x2001,
/// Returns buttons that were pressed exactly in this frame.
InputGetPadPressed = 0x2002,
/// Returns buttons that were released exactly in this frame.
InputGetPadReleased = 0x2003,
/// Returns how many frames a button has been held down.
InputGetPadHold = 0x2004,
/// Returns the full snapshot of the gamepad state (48 slots).
InputPadSnapshot = 0x2010,
/// Returns the full snapshot of the touch state (6 slots).
InputTouchSnapshot = 0x2011,
/// Returns the X coordinate of the touch/mouse pointer.
TouchGetX = 0x2101,
/// Returns the Y coordinate of the touch/mouse pointer.
TouchGetY = 0x2102,
/// Returns true if the pointer is currently touching the screen.
TouchIsDown = 0x2103,
/// Returns true if the touch started in this frame.
TouchIsPressed = 0x2104,
/// Returns true if the touch ended in this frame.
TouchIsReleased = 0x2105,
/// Returns how many frames the pointer has been held down.
TouchGetHold = 0x2106,
/// Returns the full Button struct (6 bytes) for the touch finger state.
TouchGetFinger = 0x2107,
// --- Input (Pad service-based) ---
/// Returns the full Button struct (6 bytes) for each gamepad button
PadGetUp = 0x2200,
PadGetDown = 0x2201,
PadGetLeft = 0x2202,
PadGetRight = 0x2203,
PadGetA = 0x2204,
PadGetB = 0x2205,
PadGetX = 0x2206,
PadGetY = 0x2207,
PadGetL = 0x2208,
PadGetR = 0x2209,
PadGetStart = 0x220A,
PadGetSelect = 0x220B,
// --- Audio ---
/// Starts playback of a sound sample by its Bank and ID.
AudioPlaySample = 0x3001,
/// Low-level audio play command.
AudioPlay = 0x3002,
// --- FS (Filesystem) ---
/// Opens a file for reading or writing. Returns a File Handle (u32).
FsOpen = 0x4001,
/// Reads data from an open file handle into the VM heap.
FsRead = 0x4002,
/// Writes data from the VM heap into an open file handle.
FsWrite = 0x4003,
/// Closes an open file handle.
FsClose = 0x4004,
/// Lists entries in a directory.
FsListDir = 0x4005,
/// Checks if a file or directory exists.
FsExists = 0x4006,
/// Deletes a file or empty directory.
FsDelete = 0x4007,
// --- Log ---
/// Writes a generic string to the system log.
LogWrite = 0x5001,
/// Writes a string to the system log with a specific numerical tag.
LogWriteTag = 0x5002,
// --- Asset (DMA) ---
/// Starts an asynchronous load of a file into a memory bank.
AssetLoad = 0x6001,
/// Returns the status of a pending asset load (0=Loading, 1=Ready, 2=Error).
AssetStatus = 0x6002,
/// Finalizes the asset loading, making it available for GFX/Audio.
AssetCommit = 0x6003,
/// Cancels a pending asset load.
AssetCancel = 0x6004,
// --- Bank (Memory) ---
/// Returns information about a specific Memory Bank.
BankInfo = 0x6101,
/// Returns information about a slot within a Memory Bank.
BankSlotInfo = 0x6102,
}
impl Syscall {
pub fn from_u32(id: u32) -> Option<Self> {
match id {
0x0001 => Some(Self::SystemHasCart),
0x0002 => Some(Self::SystemRunCart),
0x1001 => Some(Self::GfxClear),
0x1002 => Some(Self::GfxFillRect),
0x1003 => Some(Self::GfxDrawLine),
0x1004 => Some(Self::GfxDrawCircle),
0x1005 => Some(Self::GfxDrawDisc),
0x1006 => Some(Self::GfxDrawSquare),
0x1007 => Some(Self::GfxSetSprite),
0x1008 => Some(Self::GfxDrawText),
0x1010 => Some(Self::GfxClear565),
0x2001 => Some(Self::InputGetPad),
0x2002 => Some(Self::InputGetPadPressed),
0x2003 => Some(Self::InputGetPadReleased),
0x2004 => Some(Self::InputGetPadHold),
0x2010 => Some(Self::InputPadSnapshot),
0x2011 => Some(Self::InputTouchSnapshot),
0x2101 => Some(Self::TouchGetX),
0x2102 => Some(Self::TouchGetY),
0x2103 => Some(Self::TouchIsDown),
0x2104 => Some(Self::TouchIsPressed),
0x2105 => Some(Self::TouchIsReleased),
0x2106 => Some(Self::TouchGetHold),
0x2107 => Some(Self::TouchGetFinger),
0x2200 => Some(Self::PadGetUp),
0x2201 => Some(Self::PadGetDown),
0x2202 => Some(Self::PadGetLeft),
0x2203 => Some(Self::PadGetRight),
0x2204 => Some(Self::PadGetA),
0x2205 => Some(Self::PadGetB),
0x2206 => Some(Self::PadGetX),
0x2207 => Some(Self::PadGetY),
0x2208 => Some(Self::PadGetL),
0x2209 => Some(Self::PadGetR),
0x220A => Some(Self::PadGetStart),
0x220B => Some(Self::PadGetSelect),
0x3001 => Some(Self::AudioPlaySample),
0x3002 => Some(Self::AudioPlay),
0x4001 => Some(Self::FsOpen),
0x4002 => Some(Self::FsRead),
0x4003 => Some(Self::FsWrite),
0x4004 => Some(Self::FsClose),
0x4005 => Some(Self::FsListDir),
0x4006 => Some(Self::FsExists),
0x4007 => Some(Self::FsDelete),
0x5001 => Some(Self::LogWrite),
0x5002 => Some(Self::LogWriteTag),
0x6001 => Some(Self::AssetLoad),
0x6002 => Some(Self::AssetStatus),
0x6003 => Some(Self::AssetCommit),
0x6004 => Some(Self::AssetCancel),
0x6101 => Some(Self::BankInfo),
0x6102 => Some(Self::BankSlotInfo),
_ => None,
}
}
pub fn args_count(&self) -> usize {
match self {
Self::SystemHasCart => 0,
Self::SystemRunCart => 0,
Self::GfxClear => 1,
Self::GfxFillRect => 5,
Self::GfxDrawLine => 5,
Self::GfxDrawCircle => 4,
Self::GfxDrawDisc => 5,
Self::GfxDrawSquare => 6,
Self::GfxSetSprite => 10,
Self::GfxDrawText => 4,
Self::GfxClear565 => 1,
Self::InputGetPad => 1,
Self::InputGetPadPressed => 1,
Self::InputGetPadReleased => 1,
Self::InputGetPadHold => 1,
Self::InputPadSnapshot => 0,
Self::InputTouchSnapshot => 0,
Self::TouchGetX => 0,
Self::TouchGetY => 0,
Self::TouchIsDown => 0,
Self::TouchIsPressed => 0,
Self::TouchIsReleased => 0,
Self::TouchGetHold => 0,
Self::TouchGetFinger => 0,
Self::PadGetUp => 0,
Self::PadGetDown => 0,
Self::PadGetLeft => 0,
Self::PadGetRight => 0,
Self::PadGetA => 0,
Self::PadGetB => 0,
Self::PadGetX => 0,
Self::PadGetY => 0,
Self::PadGetL => 0,
Self::PadGetR => 0,
Self::PadGetStart => 0,
Self::PadGetSelect => 0,
Self::AudioPlaySample => 5,
Self::AudioPlay => 7,
Self::FsOpen => 1,
Self::FsRead => 1,
Self::FsWrite => 2,
Self::FsClose => 1,
Self::FsListDir => 1,
Self::FsExists => 1,
Self::FsDelete => 1,
Self::LogWrite => 2,
Self::LogWriteTag => 3,
Self::AssetLoad => 3,
Self::AssetStatus => 1,
Self::AssetCommit => 1,
Self::AssetCancel => 1,
Self::BankInfo => 1,
Self::BankSlotInfo => 2,
}
}
pub fn results_count(&self) -> usize {
match self {
// --- System ---
Self::SystemHasCart => 1,
Self::SystemRunCart => 0,
// --- GFX (void) ---
Self::GfxClear => 0,
Self::GfxFillRect => 0,
Self::GfxDrawLine => 0,
Self::GfxDrawCircle => 0,
Self::GfxDrawDisc => 0,
Self::GfxDrawSquare => 0,
Self::GfxSetSprite => 0,
Self::GfxDrawText => 0,
Self::GfxClear565 => 0,
// --- Input (scalar/snapshots) ---
Self::InputGetPad => 1,
Self::InputGetPadPressed => 1,
Self::InputGetPadReleased => 1,
Self::InputGetPadHold => 1,
Self::InputPadSnapshot => 48,
Self::InputTouchSnapshot => 6,
// --- Touch (scalars/struct) ---
Self::TouchGetX => 1,
Self::TouchGetY => 1,
Self::TouchIsDown => 1,
Self::TouchIsPressed => 1,
Self::TouchIsReleased => 1,
Self::TouchGetHold => 1,
Self::TouchGetFinger => 4, // Button struct (4 slots)
// --- Pad (per-button struct: 4 slots) ---
Self::PadGetUp
| Self::PadGetDown
| Self::PadGetLeft
| Self::PadGetRight
| Self::PadGetA
| Self::PadGetB
| Self::PadGetX
| Self::PadGetY
| Self::PadGetL
| Self::PadGetR
| Self::PadGetStart
| Self::PadGetSelect => 4,
// --- Audio (void) ---
Self::AudioPlaySample => 0,
Self::AudioPlay => 0,
// --- FS ---
Self::FsOpen => 1,
Self::FsRead => 1, // bytes read
Self::FsWrite => 1, // bytes written
Self::FsClose => 0,
Self::FsListDir => 1, // entries count/handle (TBD)
Self::FsExists => 1,
Self::FsDelete => 0,
// --- Log (void) ---
Self::LogWrite | Self::LogWriteTag => 0,
// --- Asset/Bank (conservador) ---
Self::AssetLoad => 1,
Self::AssetStatus => 1,
Self::AssetCommit => 0,
Self::AssetCancel => 0,
Self::BankInfo => 1,
Self::BankSlotInfo => 1,
}
}
pub fn name(&self) -> &'static str {
match self {
Self::SystemHasCart => "SystemHasCart",
Self::SystemRunCart => "SystemRunCart",
Self::GfxClear => "GfxClear",
Self::GfxFillRect => "GfxFillRect",
Self::GfxDrawLine => "GfxDrawLine",
Self::GfxDrawCircle => "GfxDrawCircle",
Self::GfxDrawDisc => "GfxDrawDisc",
Self::GfxDrawSquare => "GfxDrawSquare",
Self::GfxSetSprite => "GfxSetSprite",
Self::GfxDrawText => "GfxDrawText",
Self::GfxClear565 => "GfxClear565",
Self::InputGetPad => "InputGetPad",
Self::InputGetPadPressed => "InputGetPadPressed",
Self::InputGetPadReleased => "InputGetPadReleased",
Self::InputGetPadHold => "InputGetPadHold",
Self::InputPadSnapshot => "InputPadSnapshot",
Self::InputTouchSnapshot => "InputTouchSnapshot",
Self::TouchGetX => "TouchGetX",
Self::TouchGetY => "TouchGetY",
Self::TouchIsDown => "TouchIsDown",
Self::TouchIsPressed => "TouchIsPressed",
Self::TouchIsReleased => "TouchIsReleased",
Self::TouchGetHold => "TouchGetHold",
Self::TouchGetFinger => "TouchGetFinger",
Self::PadGetUp => "PadGetUp",
Self::PadGetDown => "PadGetDown",
Self::PadGetLeft => "PadGetLeft",
Self::PadGetRight => "PadGetRight",
Self::PadGetA => "PadGetA",
Self::PadGetB => "PadGetB",
Self::PadGetX => "PadGetX",
Self::PadGetY => "PadGetY",
Self::PadGetL => "PadGetL",
Self::PadGetR => "PadGetR",
Self::PadGetStart => "PadGetStart",
Self::PadGetSelect => "PadGetSelect",
Self::AudioPlaySample => "AudioPlaySample",
Self::AudioPlay => "AudioPlay",
Self::FsOpen => "FsOpen",
Self::FsRead => "FsRead",
Self::FsWrite => "FsWrite",
Self::FsClose => "FsClose",
Self::FsListDir => "FsListDir",
Self::FsExists => "FsExists",
Self::FsDelete => "FsDelete",
Self::LogWrite => "LogWrite",
Self::LogWriteTag => "LogWriteTag",
Self::AssetLoad => "AssetLoad",
Self::AssetStatus => "AssetStatus",
Self::AssetCommit => "AssetCommit",
Self::AssetCancel => "AssetCancel",
Self::BankInfo => "BankInfo",
Self::BankSlotInfo => "BankSlotInfo",
}
}
}
@@ -0,0 +1,123 @@
use crate::log::{LogLevel, LogService, LogSource};
#[derive(Debug, Clone, Copy, Default)]
pub struct TelemetryFrame {
pub frame_index: u64,
pub vm_steps: u32,
pub cycles_used: u64,
pub cycles_budget: u64,
pub syscalls: u32,
pub host_cpu_time_us: u64,
pub violations: u32,
// GFX Banks
pub gfx_used_bytes: usize,
pub gfx_inflight_bytes: usize,
pub gfx_slots_occupied: u32,
// Audio Banks
pub audio_used_bytes: usize,
pub audio_inflight_bytes: usize,
pub audio_slots_occupied: u32,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct CertificationConfig {
pub enabled: bool,
pub cycles_budget_per_frame: Option<u64>,
pub max_syscalls_per_frame: Option<u32>,
pub max_host_cpu_us_per_frame: Option<u64>,
}
pub struct Certifier {
pub config: CertificationConfig,
}
impl Certifier {
pub fn new(config: CertificationConfig) -> Self {
Self { config }
}
pub fn evaluate(&self, telemetry: &TelemetryFrame, log_service: &mut LogService, ts_ms: u64) -> usize {
if !self.config.enabled {
return 0;
}
let mut violations = 0;
if let Some(budget) = self.config.cycles_budget_per_frame {
if telemetry.cycles_used > budget {
log_service.log(
ts_ms,
telemetry.frame_index,
LogLevel::Warn,
LogSource::Pos,
0xCA01,
format!("Cert: cycles_used exceeded budget ({} > {})", telemetry.cycles_used, budget),
);
violations += 1;
}
}
if let Some(limit) = self.config.max_syscalls_per_frame {
if telemetry.syscalls > limit {
log_service.log(
ts_ms,
telemetry.frame_index,
LogLevel::Warn,
LogSource::Pos,
0xCA02,
format!("Cert: syscalls per frame exceeded limit ({} > {})", telemetry.syscalls, limit),
);
violations += 1;
}
}
if let Some(limit) = self.config.max_host_cpu_us_per_frame {
if telemetry.host_cpu_time_us > limit {
log_service.log(
ts_ms,
telemetry.frame_index,
LogLevel::Warn,
LogSource::Pos,
0xCA03,
format!("Cert: host_cpu_time_us exceeded limit ({} > {})", telemetry.host_cpu_time_us, limit),
);
violations += 1;
}
}
violations
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::log::LogService;
#[test]
fn test_certifier_violations() {
let config = CertificationConfig {
enabled: true,
cycles_budget_per_frame: Some(100),
max_syscalls_per_frame: Some(5),
max_host_cpu_us_per_frame: Some(1000),
};
let cert = Certifier::new(config);
let mut ls = LogService::new(10);
let mut tel = TelemetryFrame::default();
tel.cycles_used = 150;
tel.syscalls = 10;
tel.host_cpu_time_us = 500;
let violations = cert.evaluate(&tel, &mut ls, 1000);
assert_eq!(violations, 2);
let logs = ls.get_recent(10);
assert_eq!(logs.len(), 2);
assert!(logs[0].msg.contains("cycles_used"));
assert!(logs[1].msg.contains("syscalls"));
}
}
+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,75 @@
use crate::color::Color;
/// Standard sizes for square tiles.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TileSize {
/// 8x8 pixels.
Size8 = 8,
/// 16x16 pixels.
Size16 = 16,
/// 32x32 pixels.
Size32 = 32,
}
/// A container for graphical assets.
///
/// A TileBank stores both the raw pixel data (as palette indices) and the
/// color palettes themselves. This encapsulates all the information needed
/// to render a set of tiles.
pub struct TileBank {
/// Dimension of each individual tile in the bank.
pub tile_size: TileSize,
/// Width of the full bank sheet in pixels.
pub width: usize,
/// Height of the full bank sheet in pixels.
pub height: usize,
/// Pixel data stored as 4-bit indices (packed into 8-bit values).
/// Index 0 is always reserved for transparency.
pub pixel_indices: Vec<u8>,
/// Table of 64 palettes, each containing 16 RGB565 colors, total of 1024 colors for a bank.
pub palettes: [[Color; 16]; 64],
}
impl TileBank {
/// Creates an empty tile bank with the specified dimensions.
pub fn new(tile_size: TileSize, width: usize, height: usize) -> Self {
Self {
tile_size,
width,
height,
pixel_indices: vec![0; width * height], // Index 0 = Transparent
palettes: [[Color::BLACK; 16]; 64],
}
}
/// Resolves a global tile ID and local pixel coordinates to a palette index.
/// 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;
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 // Default to transparent if out of bounds
}
}
/// Maps a 4-bit index to a real RGB565 Color using the specified palette.
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Color {
// Hardware Rule: Index 0 is always transparent.
// We use Magenta as the 'transparent' signal color during composition.
if pixel_index == 0 {
return Color::COLOR_KEY;
}
self.palettes[palette_id as usize][pixel_index as usize]
}
}
@@ -0,0 +1,109 @@
use crate::tile::Tile;
use crate::tile_bank::TileSize;
use crate::tile_bank::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,
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,9 @@
use crate::input_signals::InputSignals;
use crate::button::Button;
pub trait TouchBridge {
fn begin_frame(&mut self, signals: &InputSignals);
fn f(&self) -> &Button;
fn x(&self) -> i32;
fn y(&self) -> i32;
}
+21
View File
@@ -0,0 +1,21 @@
use crate::color::Color;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rect {
pub x: i32,
pub y: i32,
pub w: i32,
pub h: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WindowId(pub u32);
#[derive(Debug, Clone)]
pub struct Window {
pub id: WindowId,
pub viewport: Rect,
pub has_focus: bool,
pub title: String,
pub color: Color,
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "prometeu-system"
version = "0.1.0"
edition = "2024"
license.workspace = true
[dependencies]
serde_json = "1.0.149"
prometeu-vm = { path = "../prometeu-vm" }
prometeu-bytecode = { path = "../../compiler/prometeu-bytecode" }
prometeu-abi = { path = "../../compiler/prometeu-abi" }
prometeu-hal = { path = "../prometeu-hal" }
[dev-dependencies]
prometeu-drivers = { path = "../prometeu-drivers" }
@@ -0,0 +1,7 @@
mod virtual_machine_runtime;
mod services;
mod programs;
pub use programs::PrometeuHub;
pub use services::fs;
pub use virtual_machine_runtime::VirtualMachineRuntime;
@@ -0,0 +1,3 @@
mod prometeu_hub;
pub use prometeu_hub::PrometeuHub;
@@ -0,0 +1,4 @@
mod prometeu_hub;
mod window_manager;
pub use prometeu_hub::PrometeuHub;
@@ -0,0 +1,61 @@
use crate::programs::prometeu_hub::window_manager::WindowManager;
use prometeu_hal::log::{LogLevel, LogSource};
use prometeu_hal::color::Color;
use prometeu_hal::HardwareBridge;
use prometeu_hal::window::Rect;
use crate::VirtualMachineRuntime;
/// PrometeuHub: Launcher and system UI environment.
pub struct PrometeuHub {
pub window_manager: WindowManager,
}
impl PrometeuHub {
pub fn new() -> Self {
Self {
window_manager: WindowManager::new(),
}
}
pub fn init(&mut self) {
// Initializes the Window System and lists apps
}
pub fn gui_update(&mut self, os: &mut VirtualMachineRuntime, hw: &mut dyn HardwareBridge) {
hw.gfx_mut().clear(Color::BLACK);
let mut next_window = None;
if hw.pad().a().pressed {
os.log(LogLevel::Debug, LogSource::Hub, 0, "window A opened".to_string());
next_window = Some(("Green Window".to_string(), Rect { x: 0, y: 0, w: 160, h: 90 }, Color::GREEN));
} else if hw.pad().b().pressed {
os.log(LogLevel::Debug, LogSource::Hub, 0, "window B opened".to_string());
next_window = Some(("Indigo Window".to_string(), Rect { x: 160, y: 0, w: 160, h: 90 }, Color::INDIGO));
} else if hw.pad().x().pressed {
os.log(LogLevel::Debug, LogSource::Hub, 0, "window X opened".to_string());
next_window = Some(("Yellow Window".to_string(), Rect { x: 0, y: 90, w: 160, h: 90 }, Color::YELLOW));
} else if hw.pad().y().pressed {
os.log(LogLevel::Debug, LogSource::Hub, 0, "window Y opened".to_string());
next_window = Some(("Red Window".to_string(), Rect { x: 160, y: 90, w: 160, h: 90 }, Color::RED));
}
if let Some((title, rect, color)) = next_window {
self.window_manager.remove_all_windows();
let id = self.window_manager.add_window(title, rect, color);
self.window_manager.set_focus(id);
}
}
pub fn render(&mut self, _os: &mut VirtualMachineRuntime, hw: &mut dyn HardwareBridge) {
for window in &self.window_manager.windows {
hw.gfx_mut().fill_rect(
window.viewport.x,
window.viewport.y,
window.viewport.w,
window.viewport.h,
window.color,
);
}
}
}
@@ -0,0 +1,86 @@
use prometeu_hal::color::Color;
use prometeu_hal::window::{Rect, Window, WindowId};
/// PROMETEU Window Manager.
pub struct WindowManager {
pub windows: Vec<Window>,
pub focused: Option<WindowId>,
}
impl WindowManager {
pub fn new() -> Self {
Self {
windows: Vec::new(),
focused: None,
}
}
pub fn add_window(&mut self, title: String, viewport: Rect, color: Color) -> WindowId {
let id = WindowId(self.windows.len() as u32);
let window = Window {
id,
viewport,
has_focus: false,
title,
color,
};
self.windows.push(window);
id
}
pub fn remove_window(&mut self, id: WindowId) {
self.windows.retain(|w| w.id != id);
if self.focused == Some(id) {
self.focused = None;
}
}
pub fn remove_all_windows(&mut self) {
self.windows.clear();
self.focused = None;
}
pub fn set_focus(&mut self, id: WindowId) {
self.focused = Some(id);
for window in &mut self.windows {
window.has_focus = window.id == id;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_window_manager_focus() {
let mut wm = WindowManager::new();
let id1 = wm.add_window("Window 1".to_string(), Rect { x: 0, y: 0, w: 10, h: 10 }, Color::WHITE);
let id2 = wm.add_window("Window 2".to_string(), Rect { x: 10, y: 10, w: 10, h: 10 }, Color::WHITE);
assert_eq!(wm.windows.len(), 2);
assert_eq!(wm.focused, None);
wm.set_focus(id1);
assert_eq!(wm.focused, Some(id1));
assert!(wm.windows[0].has_focus);
assert!(!wm.windows[1].has_focus);
wm.set_focus(id2);
assert_eq!(wm.focused, Some(id2));
assert!(!wm.windows[0].has_focus);
assert!(wm.windows[1].has_focus);
}
#[test]
fn test_window_manager_remove_window() {
let mut wm = WindowManager::new();
let id = wm.add_window("Window".to_string(), Rect { x: 0, y: 0, w: 10, h: 10 }, Color::WHITE);
wm.set_focus(id);
assert_eq!(wm.focused, Some(id));
wm.remove_window(id);
assert_eq!(wm.windows.len(), 0);
assert_eq!(wm.focused, None);
}
}
@@ -0,0 +1,12 @@
use crate::fs::{FsEntry, FsError};
pub trait FsBackend: Send + Sync {
fn mount(&mut self) -> Result<(), FsError>;
fn unmount(&mut self);
fn list_dir(&self, path: &str) -> Result<Vec<FsEntry>, FsError>;
fn read_file(&self, path: &str) -> Result<Vec<u8>, FsError>;
fn write_file(&mut self, path: &str, data: &[u8]) -> Result<(), FsError>;
fn delete(&mut self, path: &str) -> Result<(), FsError>;
fn exists(&self, path: &str) -> bool;
fn is_healthy(&self) -> bool { true }
}
@@ -0,0 +1,5 @@
pub struct FsEntry {
pub name: String,
pub is_dir: bool,
pub size: u64,
}
@@ -0,0 +1,24 @@
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub enum FsError {
NotFound,
AlreadyExists,
PermissionDenied,
NotMounted,
IOError(String),
Other(String),
}
impl fmt::Display for FsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FsError::NotFound => write!(f, "File or directory not found"),
FsError::AlreadyExists => write!(f, "Already exists"),
FsError::PermissionDenied => write!(f, "Permission denied"),
FsError::NotMounted => write!(f, "Filesystem not mounted"),
FsError::IOError(s) => write!(f, "IO Error: {}", s),
FsError::Other(s) => write!(f, "Error: {}", s),
}
}
}
@@ -0,0 +1,8 @@
use crate::fs::FsError;
#[derive(Debug, Clone, PartialEq)]
pub enum FsState {
Unmounted,
Mounted,
Error(FsError),
}
@@ -0,0 +1,11 @@
mod fs_error;
mod fs_state;
mod fs_entry;
mod fs_backend;
mod virtual_fs;
pub use fs_backend::FsBackend;
pub use fs_entry::FsEntry;
pub use fs_error::FsError;
pub use fs_state::FsState;
pub use virtual_fs::VirtualFS;
@@ -0,0 +1,156 @@
use crate::fs::{FsBackend, FsEntry, FsError};
/// Virtual Filesystem (VFS) interface for Prometeu.
///
/// The VFS provides a sandboxed, unified path interface for user applications.
/// Instead of interacting directly with the host's disk, the VM uses
/// normalized paths (e.g., `/user/save.dat`).
///
/// The actual storage is provided by an `FsBackend`, which can be a real
/// directory on disk, an in-memory map, or even a network resource.
pub struct VirtualFS {
/// The active storage implementation.
backend: Option<Box<dyn FsBackend>>,
}
impl VirtualFS {
pub fn new() -> Self {
Self { backend: None }
}
pub fn mount(&mut self, mut backend: Box<dyn FsBackend>) -> Result<(), FsError> {
backend.mount()?;
self.backend = Some(backend);
Ok(())
}
pub fn unmount(&mut self) {
if let Some(mut backend) = self.backend.take() {
backend.unmount();
}
}
pub fn is_mounted(&self) -> bool {
self.backend.is_some()
}
fn normalize_path(&self, path: &str) -> String {
let mut normalized = path.replace('\\', "/");
if !normalized.starts_with('/') {
normalized = format!("/{}", normalized);
}
normalized
}
pub fn list_dir(&self, path: &str) -> Result<Vec<FsEntry>, FsError> {
let normalized = self.normalize_path(path);
let backend = self.backend.as_ref().ok_or(FsError::NotMounted)?;
backend.list_dir(&normalized)
}
pub fn read_file(&self, path: &str) -> Result<Vec<u8>, FsError> {
let normalized = self.normalize_path(path);
let backend = self.backend.as_ref().ok_or(FsError::NotMounted)?;
backend.read_file(&normalized)
}
pub fn write_file(&mut self, path: &str, data: &[u8]) -> Result<(), FsError> {
let normalized = self.normalize_path(path);
let backend = self.backend.as_mut().ok_or(FsError::NotMounted)?;
backend.write_file(&normalized, data)
}
pub fn delete(&mut self, path: &str) -> Result<(), FsError> {
let normalized = self.normalize_path(path);
let backend = self.backend.as_mut().ok_or(FsError::NotMounted)?;
backend.delete(&normalized)
}
pub fn exists(&self, path: &str) -> bool {
let normalized = self.normalize_path(path);
self.backend.as_ref().map(|b| b.exists(&normalized)).unwrap_or(false)
}
pub fn is_healthy(&self) -> bool {
self.backend.as_ref().map(|b| b.is_healthy()).unwrap_or(false)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
struct MockBackend {
files: HashMap<String, Vec<u8>>,
healthy: bool,
}
impl MockBackend {
fn new() -> Self {
Self {
files: HashMap::new(),
healthy: true,
}
}
}
impl FsBackend for MockBackend {
fn mount(&mut self) -> Result<(), FsError> { Ok(()) }
fn unmount(&mut self) {}
fn list_dir(&self, _path: &str) -> Result<Vec<FsEntry>, FsError> {
Ok(self.files.keys().map(|name| FsEntry {
name: name.clone(),
is_dir: false,
size: 0,
}).collect())
}
fn read_file(&self, path: &str) -> Result<Vec<u8>, FsError> {
self.files.get(path).cloned().ok_or(FsError::NotFound)
}
fn write_file(&mut self, path: &str, data: &[u8]) -> Result<(), FsError> {
self.files.insert(path.to_string(), data.to_vec());
Ok(())
}
fn delete(&mut self, path: &str) -> Result<(), FsError> {
self.files.remove(path);
Ok(())
}
fn exists(&self, path: &str) -> bool {
self.files.contains_key(path)
}
fn is_healthy(&self) -> bool {
self.healthy
}
}
#[test]
fn test_virtual_fs_operations() {
let mut vfs = VirtualFS::new();
let backend = MockBackend::new();
vfs.mount(Box::new(backend)).unwrap();
let test_file = "/user/test.txt";
let content = b"hello world";
vfs.write_file(test_file, content).unwrap();
assert!(vfs.exists(test_file));
let read_content = vfs.read_file(test_file).unwrap();
assert_eq!(read_content, content);
vfs.delete(test_file).unwrap();
assert!(!vfs.exists(test_file));
}
#[test]
fn test_virtual_fs_health() {
let mut vfs = VirtualFS::new();
let mut backend = MockBackend::new();
backend.healthy = false;
vfs.mount(Box::new(backend)).unwrap();
assert!(!vfs.is_healthy());
}
}
@@ -0,0 +1 @@
pub mod fs;
File diff suppressed because it is too large Load Diff
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "prometeu-vm"
version = "0.1.0"
edition = "2024"
license.workspace = true
[dependencies]
serde = { version = "1.0.228", features = ["derive"] }
prometeu-bytecode = { path = "../../compiler/prometeu-bytecode" }
prometeu-abi = { path = "../../compiler/prometeu-abi" }
prometeu-hal = { path = "../prometeu-hal" }
@@ -0,0 +1,5 @@
pub struct CallFrame {
pub return_pc: u32,
pub stack_base: usize,
pub func_idx: usize,
}
+16
View File
@@ -0,0 +1,16 @@
mod virtual_machine;
mod call_frame;
mod scope_frame;
pub mod local_addressing;
pub mod verifier;
pub use prometeu_abi::ProgramImage;
pub use prometeu_abi::{Value, VmFault};
pub use prometeu_bytecode::abi::TrapInfo;
pub use prometeu_bytecode::opcode::OpCode;
pub use prometeu_hal::{
HostContext, HostReturn, NativeInterface, SyscallId,
};
pub type VmInitError = prometeu_abi::VmInitError<VerifierError>;
pub use verifier::VerifierError;
pub use virtual_machine::{BudgetReport, LogicalFrameEndingReason, VirtualMachine};
@@ -0,0 +1,30 @@
use crate::call_frame::CallFrame;
use prometeu_bytecode::abi::{TrapInfo, TRAP_INVALID_LOCAL};
use prometeu_bytecode::FunctionMeta;
/// Computes the absolute stack index for the start of the current frame's locals (including args).
pub fn local_base(frame: &CallFrame) -> usize {
frame.stack_base
}
/// Computes the absolute stack index for a given local slot.
pub fn local_index(frame: &CallFrame, slot: u32) -> usize {
frame.stack_base + slot as usize
}
/// Validates that a local slot index is within the valid range for the function.
/// Range: 0 <= slot < (param_slots + local_slots)
pub fn check_local_slot(meta: &FunctionMeta, slot: u32, opcode: u16, pc: u32) -> Result<(), TrapInfo> {
let limit = meta.param_slots as u32 + meta.local_slots as u32;
if slot < limit {
Ok(())
} else {
Err(TrapInfo {
code: TRAP_INVALID_LOCAL,
opcode,
message: format!("Local slot {} out of bounds for function (limit {})", slot, limit),
pc,
span: None,
})
}
}
@@ -0,0 +1,3 @@
pub struct ScopeFrame {
pub scope_stack_base: usize,
}
+406
View File
@@ -0,0 +1,406 @@
use prometeu_hal::syscalls::Syscall;
use prometeu_bytecode::decoder::{decode_next, DecodeError};
use prometeu_bytecode::opcode::OpCode;
use prometeu_bytecode::opcode_spec::OpCodeSpecExt;
use prometeu_bytecode::FunctionMeta;
use prometeu_bytecode::layout;
use std::collections::{HashMap, HashSet, VecDeque};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerifierError {
UnknownOpcode { pc: usize, opcode: u16 },
TruncatedOpcode { pc: usize },
TruncatedImmediate { pc: usize, opcode: OpCode, need: usize, have: usize },
InvalidJumpTarget { pc: usize, target: usize },
JumpToMidInstruction { pc: usize, target: usize },
StackUnderflow { pc: usize, opcode: OpCode },
StackMismatchJoin { pc: usize, target: usize, height_in: u16, height_target: u16 },
BadRetStackHeight { pc: usize, height: u16, expected: u16 },
FunctionOutOfBounds { func_idx: usize, start: usize, end: usize, code_len: usize },
InvalidSyscallId { pc: usize, id: u32 },
TrailingBytes { func_idx: usize, at_pc: usize },
InvalidFuncId { pc: usize, id: u32 },
}
pub struct Verifier;
impl Verifier {
pub fn verify(code: &[u8], functions: &[FunctionMeta]) -> Result<Vec<u16>, VerifierError> {
let mut max_stacks = Vec::with_capacity(functions.len());
// Precompute function [start, end) ranges once for O(1) lookups
let layouts = layout::compute_function_layouts(functions, code.len());
for (i, func) in functions.iter().enumerate() {
max_stacks.push(Self::verify_function(code, func, i, functions, &layouts)?);
}
Ok(max_stacks)
}
fn verify_function(
code: &[u8],
func: &FunctionMeta,
func_idx: usize,
all_functions: &[FunctionMeta],
layouts: &[layout::FunctionLayout],
) -> Result<u16, VerifierError> {
let func_start = func.code_offset as usize;
// Use precomputed canonical range end
let func_end = layouts.get(func_idx).map(|l| l.end).unwrap_or_else(|| code.len());
if func_start > code.len() || func_end > code.len() || func_start > func_end {
return Err(VerifierError::FunctionOutOfBounds {
func_idx,
start: func_start,
end: func_end,
code_len: code.len(),
});
}
let func_code = &code[func_start..func_end];
// Funções vazias (sem qualquer byte de código) são consideradas válidas no verificador.
// Elas não consomem nem produzem valores na pilha e não possuem fluxo interno.
// Observação: se uma função vazia for chamada em tempo de execução e retorno/efeitos
// forem esperados, caberá ao gerador de código/linker impedir tal situação.
if func_code.is_empty() {
return Ok(0);
}
// First pass: find all valid instruction boundaries
let mut valid_pc = HashSet::new();
let mut pc = 0;
while pc < func_code.len() {
valid_pc.insert(pc);
let instr = decode_next(pc, func_code).map_err(|e| match e {
DecodeError::UnknownOpcode { pc: _, opcode } =>
VerifierError::UnknownOpcode { pc: func_start + pc, opcode },
DecodeError::TruncatedOpcode { pc: _ } =>
VerifierError::TruncatedOpcode { pc: func_start + pc },
DecodeError::TruncatedImmediate { pc: _, opcode, need, have } =>
VerifierError::TruncatedImmediate { pc: func_start + pc, opcode, need, have },
DecodeError::ImmediateSizeMismatch { pc: _, opcode, expected, actual } =>
VerifierError::TruncatedImmediate { pc: func_start + pc, opcode, need: expected, have: actual },
})?;
pc = instr.next_pc;
}
if pc != func_code.len() {
return Err(VerifierError::TrailingBytes { func_idx, at_pc: func_start + pc });
}
let mut stack_height_in: HashMap<usize, u16> = HashMap::new();
let mut worklist = VecDeque::new();
let mut max_stack: u16 = 0;
// Start from function entry
stack_height_in.insert(0, 0);
worklist.push_back(0);
while let Some(pc) = worklist.pop_front() {
let in_height = *stack_height_in.get(&pc).unwrap();
let instr = decode_next(pc, func_code).unwrap(); // Guaranteed to succeed due to first pass
let spec = instr.opcode.spec();
// Resolve dynamic pops/pushes
let (pops, pushes) = match instr.opcode {
OpCode::PopN => {
let n = instr.imm_u32().unwrap() as u16;
(n, 0)
}
OpCode::Call => {
let func_id = instr.imm_u32().unwrap();
let callee = all_functions.get(func_id as usize).ok_or_else(|| {
VerifierError::InvalidFuncId { pc: func_start + pc, id: func_id }
})?;
(callee.param_slots, callee.return_slots)
}
OpCode::Ret => {
(func.return_slots, 0)
}
OpCode::Syscall => {
let id = instr.imm_u32().unwrap();
let syscall = Syscall::from_u32(id).ok_or_else(|| {
VerifierError::InvalidSyscallId { pc: func_start + pc, id }
})?;
(syscall.args_count() as u16, syscall.results_count() as u16)
}
_ => (spec.pops, spec.pushes),
};
if in_height < pops {
return Err(VerifierError::StackUnderflow { pc: func_start + pc, opcode: instr.opcode });
}
let out_height = in_height - pops + pushes;
max_stack = max_stack.max(out_height);
if instr.opcode == OpCode::Ret {
if in_height != func.return_slots {
return Err(VerifierError::BadRetStackHeight { pc: func_start + pc, height: in_height, expected: func.return_slots });
}
}
// Propagate to successors
if spec.is_branch {
// Canonical contract: branch immediate is RELATIVE to function start.
let target_rel = instr.imm_u32().unwrap() as usize;
let func_end_abs = layouts.get(func_idx).map(|l| l.end).unwrap_or_else(|| code.len());
let func_len = func_end_abs - func_start;
if target_rel > func_len {
// Mandatory structured diagnostic for InvalidJumpTarget
let pc_abs = func_start + pc;
let opcode = instr.opcode;
let imm_raw = instr.imm_u32().unwrap();
let func_start_abs = func_start;
let func_end_abs_log = func_end_abs;
let target_abs_expected = func_start_abs + target_rel;
let is_boundary_target_rel = valid_pc.contains(&target_rel);
eprintln!(
"[VERIFIER] invalid jump: pc_abs={} opcode={:?} imm_raw={} func=F{} start={} end={} len={} target_rel={} target_abs_expected={} boundary_rel={}",
pc_abs,
opcode,
imm_raw,
func_idx,
func_start_abs,
func_end_abs_log,
func_len,
target_rel,
target_abs_expected,
is_boundary_target_rel
);
return Err(VerifierError::InvalidJumpTarget { pc: pc_abs, target: target_abs_expected });
}
if target_rel == func_len {
// salto para o fim da função
if out_height != func.return_slots {
return Err(VerifierError::BadRetStackHeight { pc: func_start + pc, height: out_height, expected: func.return_slots });
}
// caminho termina aqui
} else {
if !valid_pc.contains(&target_rel) {
return Err(VerifierError::JumpToMidInstruction { pc: func_start + pc, target: func_start + target_rel });
}
if let Some(&existing_height) = stack_height_in.get(&target_rel) {
if existing_height != out_height {
return Err(VerifierError::StackMismatchJoin { pc: func_start + pc, target: func_start + target_rel, height_in: out_height, height_target: existing_height });
}
} else {
stack_height_in.insert(target_rel, out_height);
worklist.push_back(target_rel);
}
}
}
if !spec.is_terminator {
let next_pc = instr.next_pc;
let func_len = layouts.get(func_idx).map(|l| l.end - l.start).unwrap_or_else(|| 0);
if next_pc < func_len {
if let Some(&existing_height) = stack_height_in.get(&next_pc) {
if existing_height != out_height {
return Err(VerifierError::StackMismatchJoin { pc: func_start + pc, target: func_start + next_pc, height_in: out_height, height_target: existing_height });
}
} else {
stack_height_in.insert(next_pc, out_height);
worklist.push_back(next_pc);
}
}
}
}
Ok(max_stack)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_verifier_underflow() {
// OpCode::Add (2 bytes)
let code = vec![OpCode::Add as u8, 0x00];
let functions = vec![FunctionMeta {
code_offset: 0,
code_len: 2,
..Default::default()
}];
let res = Verifier::verify(&code, &functions);
assert_eq!(res, Err(VerifierError::StackUnderflow { pc: 0, opcode: OpCode::Add }));
}
#[test]
fn test_verifier_dup_underflow() {
let code = vec![(OpCode::Dup as u16).to_le_bytes()[0], (OpCode::Dup as u16).to_le_bytes()[1]];
let functions = vec![FunctionMeta { code_offset: 0, code_len: 2, ..Default::default() }];
let res = Verifier::verify(&code, &functions);
assert_eq!(res, Err(VerifierError::StackUnderflow { pc: 0, opcode: OpCode::Dup }));
}
#[test]
fn test_verifier_invalid_jmp_target() {
// Jmp (2 bytes) + 100u32 (4 bytes)
let mut code = vec![OpCode::Jmp as u8, 0x00];
code.extend_from_slice(&100u32.to_le_bytes());
let functions = vec![FunctionMeta {
code_offset: 0,
code_len: 6,
..Default::default()
}];
let res = Verifier::verify(&code, &functions);
assert_eq!(res, Err(VerifierError::InvalidJumpTarget { pc: 0, target: 100 }));
}
#[test]
fn test_verifier_jmp_to_mid_instr() {
// PushI32 (2 bytes) + 42u32 (4 bytes)
// Jmp 1 (middle of PushI32)
let mut code = vec![OpCode::PushI32 as u8, 0x00];
code.extend_from_slice(&42u32.to_le_bytes());
code.push(OpCode::Jmp as u8);
code.push(0x00);
code.extend_from_slice(&1u32.to_le_bytes());
let functions = vec![FunctionMeta {
code_offset: 0,
code_len: 12,
..Default::default()
}];
let res = Verifier::verify(&code, &functions);
assert_eq!(res, Err(VerifierError::JumpToMidInstruction { pc: 6, target: 1 }));
}
#[test]
fn test_verifier_jump_to_end_ok() {
// Single-instruction function where JMP targets exactly func_len (end-exclusive)
// Encoding: [JMP][u32 imm], with imm == total function length (6 bytes)
let mut code = Vec::new();
code.push(OpCode::Jmp as u8);
code.push(0x00);
code.extend_from_slice(&6u32.to_le_bytes());
let functions = vec![FunctionMeta {
code_offset: 0,
code_len: 6,
return_slots: 0,
..Default::default()
}];
let res = Verifier::verify(&code, &functions).unwrap();
// No stack usage; max stack remains 0
assert_eq!(res[0], 0);
}
#[test]
fn test_verifier_truncation_opcode() {
let code = vec![OpCode::PushI32 as u8]; // Truncated u16 opcode
let functions = vec![FunctionMeta {
code_offset: 0,
code_len: 1,
..Default::default()
}];
let res = Verifier::verify(&code, &functions);
assert_eq!(res, Err(VerifierError::TruncatedOpcode { pc: 0 }));
}
#[test]
fn test_verifier_truncation_immediate() {
let mut code = vec![OpCode::PushI32 as u8, 0x00];
code.push(0x42); // Only 1 byte of 4-byte immediate
let functions = vec![FunctionMeta {
code_offset: 0,
code_len: 3,
..Default::default()
}];
let res = Verifier::verify(&code, &functions);
assert_eq!(res, Err(VerifierError::TruncatedImmediate { pc: 0, opcode: OpCode::PushI32, need: 4, have: 1 }));
}
#[test]
fn test_verifier_stack_mismatch_join() {
// Let's make it reachable:
// 0: PushBool true
// 3: JmpIfTrue 15
// 9: Jmp 27
// 15: PushI32 1
// 21: Jmp 27
// 27: Nop
let mut code = Vec::new();
code.push(OpCode::PushBool as u8); code.push(0x00); code.push(1); // 0: PushBool (3 bytes)
code.push(OpCode::JmpIfTrue as u8); code.push(0x00); code.extend_from_slice(&15u32.to_le_bytes()); // 3: JmpIfTrue (6 bytes)
code.push(OpCode::Jmp as u8); code.push(0x00); code.extend_from_slice(&27u32.to_le_bytes()); // 9: Jmp (6 bytes)
code.push(OpCode::PushI32 as u8); code.push(0x00); code.extend_from_slice(&1u32.to_le_bytes()); // 15: PushI32 (6 bytes)
code.push(OpCode::Jmp as u8); code.push(0x00); code.extend_from_slice(&27u32.to_le_bytes()); // 21: Jmp (6 bytes)
code.push(OpCode::Nop as u8); code.push(0x00); // 27: Nop (2 bytes)
let functions = vec![FunctionMeta {
code_offset: 0,
code_len: 29,
..Default::default()
}];
let res = Verifier::verify(&code, &functions);
// Path 0->3->9->27: height 1-1+0 = 0.
// Path 0->3->15->21->27: height 1-1+1 = 1.
// Mismatch at 27: 0 vs 1.
assert_eq!(res, Err(VerifierError::StackMismatchJoin { pc: 21, target: 27, height_in: 1, height_target: 0 }));
}
#[test]
fn test_verifier_bad_ret_height() {
// PushI32 1 (6 bytes)
// Ret (2 bytes)
let mut code = vec![OpCode::PushI32 as u8, 0x00];
code.extend_from_slice(&1u32.to_le_bytes());
code.push(OpCode::Ret as u8);
code.push(0x00);
let functions = vec![FunctionMeta {
code_offset: 0,
code_len: 8,
return_slots: 0, // Expected 0, but got 1
..Default::default()
}];
let res = Verifier::verify(&code, &functions);
assert_eq!(res, Err(VerifierError::BadRetStackHeight { pc: 6, height: 1, expected: 0 }));
}
#[test]
fn test_verifier_max_stack() {
// PushI32 1
// PushI32 2
// Add
// Ret
let mut code = Vec::new();
code.push(OpCode::PushI32 as u8); code.push(0x00); code.extend_from_slice(&1u32.to_le_bytes());
code.push(OpCode::PushI32 as u8); code.push(0x00); code.extend_from_slice(&2u32.to_le_bytes());
code.push(OpCode::Add as u8); code.push(0x00);
code.push(OpCode::Ret as u8); code.push(0x00);
let functions = vec![FunctionMeta {
code_offset: 0,
code_len: 16,
return_slots: 1,
..Default::default()
}];
let res = Verifier::verify(&code, &functions).unwrap();
assert_eq!(res[0], 2);
}
#[test]
fn test_verifier_invalid_syscall_id() {
let mut code = Vec::new();
code.push(OpCode::Syscall as u8); code.push(0x00);
code.extend_from_slice(&0xDEADBEEFu32.to_le_bytes()); // Unknown ID
let functions = vec![FunctionMeta {
code_offset: 0,
code_len: 6,
..Default::default()
}];
let res = Verifier::verify(&code, &functions);
assert_eq!(res, Err(VerifierError::InvalidSyscallId { pc: 0, id: 0xDEADBEEF }));
}
}
File diff suppressed because it is too large Load Diff