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,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 }
}