new music on color-square

This commit is contained in:
Nilton Constantino
2026-01-22 13:28:39 +00:00
parent 9704274707
commit f7b60c2688
20 changed files with 978 additions and 551 deletions
@@ -18,8 +18,10 @@ pub struct Codegen {
pub symbols: Vec<Symbol>,
instructions: Vec<(Asm, bool)>, // (Asm, has_symbol)
locals: HashMap<String, u32>,
globals: HashMap<String, u32>,
constant_pool: Vec<ConstantPoolEntry>,
next_local: u32,
next_global: u32,
label_count: u32,
}
@@ -31,8 +33,10 @@ impl Codegen {
symbols: Vec::new(),
instructions: Vec::new(),
locals: HashMap::new(),
globals: HashMap::new(),
constant_pool: vec![ConstantPoolEntry::Null], // Index 0 is always Null
next_local: 0,
next_global: 0,
label_count: 0,
}
}
@@ -52,7 +56,7 @@ impl Codegen {
}
pub fn compile_programs(&mut self, programs: Vec<(String, String, &Program)>) -> Result<Vec<u8>> {
// First pass: collect all functions and their indices
// First pass: collect all functions and global variables
let mut all_functions = Vec::new();
for (file, source, program) in &programs {
for item in &program.body {
@@ -63,6 +67,29 @@ impl Codegen {
Statement::ExportNamedDeclaration(decl) => {
if let Some(Declaration::FunctionDeclaration(f)) = &decl.declaration {
all_functions.push((file.clone(), source.clone(), f.as_ref()));
} else if let Some(Declaration::VariableDeclaration(var)) = &decl.declaration {
for decl in &var.declarations {
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
let name = ident.name.to_string();
if !self.globals.contains_key(&name) {
let id = self.next_global;
self.globals.insert(name, id);
self.next_global += 1;
}
}
}
}
}
Statement::VariableDeclaration(var) => {
for decl in &var.declarations {
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
let name = ident.name.to_string();
if !self.globals.contains_key(&name) {
let id = self.next_global;
self.globals.insert(name, id);
self.next_global += 1;
}
}
}
}
_ => {}
@@ -99,6 +126,40 @@ impl Codegen {
let frame_fn_name = frame_fn_name.ok_or_else(|| anyhow!("export function frame() not found in entry file"))?;
// Initialize globals
for (file, source, program) in &programs {
self.file_name = file.clone();
self.source_text = source.clone();
for item in &program.body {
let var_opt = match item {
Statement::VariableDeclaration(var) => Some(var.as_ref()),
Statement::ExportNamedDeclaration(decl) => {
if let Some(Declaration::VariableDeclaration(var)) = &decl.declaration {
Some(var.as_ref())
} else {
None
}
}
_ => None,
};
if let Some(var) = var_opt {
for decl in &var.declarations {
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
let name = ident.name.to_string();
let id = *self.globals.get(&name).unwrap();
if let Some(init) = &decl.init {
self.compile_expr(init)?;
} else {
self.emit_op(OpCode::PushI32, vec![Operand::I32(0)], decl.span);
}
self.emit_op(OpCode::SetGlobal, vec![Operand::U32(id)], decl.span);
}
}
}
}
}
// Entry point: loop calling frame
self.emit_label("entry".to_string());
self.emit_op(OpCode::Call, vec![Operand::Label(frame_fn_name), Operand::U32(0)], Span::default());
@@ -221,7 +282,7 @@ impl Codegen {
if val.fract() == 0.0 && val >= i32::MIN as f64 && val <= i32::MAX as f64 {
self.emit_op(OpCode::PushI32, vec![Operand::I32(val as i32)], n.span);
} else {
self.emit_op(OpCode::PushI64, vec![Operand::I64(val as i64)], n.span);
self.emit_op(OpCode::PushF64, vec![Operand::F64(val)], n.span);
}
}
Expression::BooleanLiteral(b) => {
@@ -238,6 +299,8 @@ impl Codegen {
let name = ident.name.to_string();
if let Some(&id) = self.locals.get(&name) {
self.emit_op(OpCode::GetLocal, vec![Operand::U32(id)], ident.span);
} else if let Some(&id) = self.globals.get(&name) {
self.emit_op(OpCode::GetGlobal, vec![Operand::U32(id)], ident.span);
} else {
return Err(anyhow!("Undefined variable: {} at {:?}", name, ident.span));
}
@@ -249,6 +312,9 @@ impl Codegen {
if let Some(&id) = self.locals.get(&name) {
self.emit_op(OpCode::SetLocal, vec![Operand::U32(id)], assign.span);
self.emit_op(OpCode::GetLocal, vec![Operand::U32(id)], assign.span);
} else if let Some(&id) = self.globals.get(&name) {
self.emit_op(OpCode::SetGlobal, vec![Operand::U32(id)], assign.span);
self.emit_op(OpCode::GetGlobal, vec![Operand::U32(id)], assign.span);
} else {
return Err(anyhow!("Undefined variable: {} at {:?}", name, ident.span));
}
@@ -80,6 +80,14 @@ pub enum DebugEvent {
vm_steps: u32,
syscalls: u32,
cycles: 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 {
+96 -4
View File
@@ -151,12 +151,50 @@ impl AssetManager {
pub fn initialize_for_cartridge(&self, assets: Vec<AssetEntry>, assets_data: Vec<u8>) {
self.shutdown();
let mut asset_map = self.assets.write().unwrap();
asset_map.clear();
for entry in assets {
asset_map.insert(entry.asset_id.clone(), entry);
{
let mut asset_map = self.assets.write().unwrap();
asset_map.clear();
for entry in assets.iter() {
asset_map.insert(entry.asset_id.clone(), entry.clone());
}
}
*self.assets_data.write().unwrap() = assets_data;
// Perform Preload for assets marked with preload_slot
for entry in assets {
if let Some(slot_index) = entry.preload_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.clone(), 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.clone());
}
println!("[AssetManager] Preloaded tile asset '{}' into slot {}", entry.asset_id, slot_index);
} else {
eprintln!("[AssetManager] Failed to preload tile asset '{}'", entry.asset_id);
}
}
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.clone(), 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.clone());
}
println!("[AssetManager] Preloaded sound asset '{}' into slot {}", entry.asset_id, slot_index);
} else {
eprintln!("[AssetManager] Failed to preload sound asset '{}'", entry.asset_id);
}
}
}
}
}
}
pub fn load(&self, asset_id: &str, slot: SlotRef) -> Result<HandleId, String> {
@@ -460,12 +498,21 @@ impl AssetManager {
}
}
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 => {
@@ -492,12 +539,21 @@ impl AssetManager {
}
}
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,
}
}
}
@@ -582,6 +638,7 @@ mod tests {
"width": 16,
"height": 16
}),
preload_slot: None,
};
let am = AssetManager::new(vec![asset_entry], data, gfx_installer, sound_installer);
@@ -631,6 +688,7 @@ mod tests {
"width": 16,
"height": 16
}),
preload_slot: None,
};
let am = AssetManager::new(vec![asset_entry], data, gfx_installer, sound_installer);
@@ -669,6 +727,7 @@ mod tests {
metadata: serde_json::json!({
"sample_rate": 44100
}),
preload_slot: None,
};
let am = AssetManager::new(vec![asset_entry], data, gfx_installer, sound_installer);
@@ -689,4 +748,37 @@ mod tests {
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: "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
}),
preload_slot: Some(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], 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("preload_sound".to_string()));
}
}
+17 -1
View File
@@ -126,7 +126,10 @@ impl Audio {
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);
}
}
@@ -134,7 +137,20 @@ impl Audio {
if voice_id >= MAX_CHANNELS {
return;
}
// Push command to the host
// 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,
+3
View File
@@ -20,6 +20,8 @@ pub struct AssetEntry {
pub decoded_size: u64,
pub codec: String, // e.g., "RAW"
pub metadata: serde_json::Value,
#[serde(default)]
pub preload_slot: Option<usize>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -39,6 +41,7 @@ pub struct BankStats {
pub free_bytes: usize,
pub inflight_bytes: usize,
pub slot_count: usize,
pub slots_occupied: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -1,7 +1,7 @@
use crate::fs::{FsBackend, FsState, VirtualFS};
use crate::hardware::{HardwareBridge, InputSignals};
use crate::log::{LogLevel, LogService, LogSource};
use crate::model::{Cartridge, Color};
use crate::model::{BankType, Cartridge, Color};
use crate::prometeu_os::{NativeInterface, Syscall};
use crate::telemetry::{CertificationConfig, Certifier, TelemetryFrame};
use crate::virtual_machine::{Value, VirtualMachine};
@@ -263,9 +263,26 @@ impl PrometeuOS {
self.last_frame_cpu_time_us = start.elapsed().as_micros() as u64;
// Update bank telemetry in current frame (snapshot)
let gfx_stats = hw.assets().bank_info(BankType::TILES);
self.telemetry_current.gfx_used_bytes = gfx_stats.used_bytes;
self.telemetry_current.gfx_inflight_bytes = gfx_stats.inflight_bytes;
self.telemetry_current.gfx_slots_occupied = gfx_stats.slots_occupied as u32;
let audio_stats = hw.assets().bank_info(BankType::SOUNDS);
self.telemetry_current.audio_used_bytes = audio_stats.used_bytes;
self.telemetry_current.audio_inflight_bytes = audio_stats.inflight_bytes;
self.telemetry_current.audio_slots_occupied = audio_stats.slots_occupied as u32;
// If the frame ended exactly in this tick, we update the final real time in the latch.
if !self.logical_frame_active && self.telemetry_last.frame_index == self.logical_frame_index.wrapping_sub(1) {
self.telemetry_last.host_cpu_time_us = self.last_frame_cpu_time_us;
self.telemetry_last.gfx_used_bytes = self.telemetry_current.gfx_used_bytes;
self.telemetry_last.gfx_inflight_bytes = self.telemetry_current.gfx_inflight_bytes;
self.telemetry_last.gfx_slots_occupied = self.telemetry_current.gfx_slots_occupied;
self.telemetry_last.audio_used_bytes = self.telemetry_current.audio_used_bytes;
self.telemetry_last.audio_inflight_bytes = self.telemetry_current.audio_inflight_bytes;
self.telemetry_last.audio_slots_occupied = self.telemetry_current.audio_slots_occupied;
}
None
@@ -695,21 +712,29 @@ impl NativeInterface for PrometeuOS {
let voice_id = vm.pop_integer()? as usize;
let sample_id = vm.pop_integer()? as u32;
// let sample = match sample_id {
// 0 => self.sample_square.clone(),
// 1 => self.sample_kick.clone(),
// 2 => self.sample_snare.clone(),
// _ => None,
// };
// if let Some(s) = sample {
// hw.audio_mut().play(s, voice_id, volume, pan, pitch, 0, crate::hardware::LoopMode::Off);
// }
hw.audio_mut().play(0, sample_id as u16, voice_id, volume, pan, pitch, 0, crate::hardware::LoopMode::Off);
vm.push(Value::Null);
Ok(300)
}
// audio.play(bank_id, sample_id, voice_id, volume, pan, pitch, loop_mode)
Syscall::AudioPlay => {
let loop_mode = match vm.pop_integer()? {
0 => crate::hardware::LoopMode::Off,
_ => crate::hardware::LoopMode::On,
};
let pitch = vm.pop_number()?;
let pan = vm.pop_integer()? as u8;
let volume = vm.pop_integer()? as u8;
let voice_id = vm.pop_integer()? as usize;
let sample_id = vm.pop_integer()? as u16;
let bank_id = vm.pop_integer()? as u8;
hw.audio_mut().play(bank_id, sample_id, voice_id, volume, pan, pitch, 0, loop_mode);
vm.push(Value::Null);
Ok(300)
}
// --- Filesystem Syscalls (0x4000) ---
// FS_OPEN(path) -> handle
@@ -28,6 +28,7 @@ pub enum Syscall {
// Audio
AudioPlaySample = 0x3001,
AudioPlay = 0x3002,
// FS
FsOpen = 0x4001,
@@ -75,6 +76,7 @@ impl Syscall {
0x2105 => Some(Self::TouchIsReleased),
0x2106 => Some(Self::TouchGetHold),
0x3001 => Some(Self::AudioPlaySample),
0x3002 => Some(Self::AudioPlay),
0x4001 => Some(Self::FsOpen),
0x4002 => Some(Self::FsRead),
0x4003 => Some(Self::FsWrite),
@@ -147,6 +149,7 @@ impl Syscall {
"touch.isReleased" | "touch.is_released" => Some(Self::TouchIsReleased),
"touch.getHold" | "touch.get_hold" => Some(Self::TouchGetHold),
"audio.playSample" | "audio.play_sample" => Some(Self::AudioPlaySample),
"audio.play" => Some(Self::AudioPlay),
"fs.open" => Some(Self::FsOpen),
"fs.read" => Some(Self::FsRead),
"fs.write" => Some(Self::FsWrite),
+10
View File
@@ -8,6 +8,16 @@ pub struct TelemetryFrame {
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)]
+4 -1
View File
@@ -69,7 +69,9 @@ impl HostAudio {
pub fn send_commands(&mut self, commands: &mut Vec<AudioCommand>) {
if let Some(producer) = &mut self.producer {
for cmd in commands.drain(..) {
let _ = producer.try_push(cmd);
if let Err(_) = producer.try_push(cmd) {
eprintln!("[HostAudio] Command ringbuffer full, dropping command.");
}
}
}
}
@@ -108,6 +110,7 @@ impl AudioMixer {
loop_mode,
} => {
if voice_id < MAX_CHANNELS {
println!("[AudioMixer] Playing voice {}: vol={}, pitch={}, loop={:?}", voice_id, volume, pitch, loop_mode);
self.voices[voice_id] = Channel {
sample: Some(sample),
active: true,
@@ -230,17 +230,32 @@ impl HostDebugger {
// Map Certification tags (0xCA01-0xCA03) to 'Cert' protocol events.
if event.tag >= 0xCA01 && event.tag <= 0xCA03 {
let rule = match event.tag {
0xCA01 => "cycles_budget",
0xCA02 => "max_syscalls",
0xCA03 => "max_host_cpu_us",
_ => "unknown"
}.to_string();
let tel = &firmware.os.telemetry_last;
let cert_config = &firmware.os.certifier.config;
let (rule, used, limit) = match event.tag {
0xCA01 => (
"cycles_budget".to_string(),
tel.cycles_used,
cert_config.cycles_budget_per_frame.unwrap_or(0),
),
0xCA02 => (
"max_syscalls".to_string(),
tel.syscalls as u64,
cert_config.max_syscalls_per_frame.unwrap_or(0) as u64,
),
0xCA03 => (
"max_host_cpu_us".to_string(),
tel.host_cpu_time_us,
cert_config.max_host_cpu_us_per_frame.unwrap_or(0),
),
_ => ("unknown".to_string(), 0, 0),
};
self.send_event(DebugEvent::Cert {
rule,
used: 0,
limit: 0,
used,
limit,
frame_index: firmware.os.logical_frame_index,
});
}
@@ -261,6 +276,14 @@ impl HostDebugger {
vm_steps: tel.vm_steps,
syscalls: tel.syscalls,
cycles: tel.cycles_used,
host_cpu_time_us: tel.host_cpu_time_us,
violations: tel.violations,
gfx_used_bytes: tel.gfx_used_bytes,
gfx_inflight_bytes: tel.gfx_inflight_bytes,
gfx_slots_occupied: tel.gfx_slots_occupied,
audio_used_bytes: tel.audio_used_bytes,
audio_inflight_bytes: tel.audio_inflight_bytes,
audio_slots_occupied: tel.audio_slots_occupied,
});
self.last_telemetry_frame = current_frame;
}
+13 -3
View File
@@ -124,21 +124,31 @@ impl HostRunner {
let color_bg = prometeu_core::model::Color::INDIGO; // Dark blue to stand out
let color_warn = prometeu_core::model::Color::RED;
self.hardware.gfx.fill_rect(5, 5, 140, 65, color_bg);
self.hardware.gfx.fill_rect(5, 5, 140, 100, color_bg);
self.hardware.gfx.draw_text(10, 10, &format!("FPS: {:.1}", self.stats.current_fps), color_text);
self.hardware.gfx.draw_text(10, 18, &format!("HOST: {:.2}MS", tel.host_cpu_time_us as f64 / 1000.0), color_text);
self.hardware.gfx.draw_text(10, 26, &format!("STEPS: {}", tel.vm_steps), color_text);
self.hardware.gfx.draw_text(10, 34, &format!("SYSC: {}", tel.syscalls), color_text);
self.hardware.gfx.draw_text(10, 42, &format!("CYC: {}", tel.cycles_used), color_text);
self.hardware.gfx.draw_text(10, 50, &format!("GFX: {}K/16M ({}S)", tel.gfx_used_bytes / 1024, tel.gfx_slots_occupied), color_text);
if tel.gfx_inflight_bytes > 0 {
self.hardware.gfx.draw_text(10, 58, &format!("LOAD GFX: {}KB", tel.gfx_inflight_bytes / 1024), color_warn);
}
self.hardware.gfx.draw_text(10, 66, &format!("AUD: {}K/32M ({}S)", tel.audio_used_bytes / 1024, tel.audio_slots_occupied), color_text);
if tel.audio_inflight_bytes > 0 {
self.hardware.gfx.draw_text(10, 74, &format!("LOAD AUD: {}KB", tel.audio_inflight_bytes / 1024), color_warn);
}
let cert_color = if tel.violations > 0 { color_warn } else { color_text };
self.hardware.gfx.draw_text(10, 50, &format!("CERT LAST: {}", tel.violations), cert_color);
self.hardware.gfx.draw_text(10, 82, &format!("CERT LAST: {}", tel.violations), cert_color);
if tel.violations > 0 {
if let Some(event) = self.firmware.os.log_service.get_recent(10).into_iter().rev().find(|e| e.tag >= 0xCA01 && e.tag <= 0xCA03) {
let mut msg = event.msg.clone();
if msg.len() > 30 { msg.truncate(30); }
self.hardware.gfx.draw_text(10, 58, &msg, color_warn);
self.hardware.gfx.draw_text(10, 90, &msg, color_warn);
}
}
}