add audio

This commit is contained in:
Nilton Constantino
2026-01-14 17:55:06 +00:00
parent b0f4a865ad
commit acd09a6468
11 changed files with 861 additions and 49 deletions
+127
View File
@@ -0,0 +1,127 @@
use crate::model::Sample;
use std::sync::Arc;
pub const MAX_CHANNELS: usize = 16;
pub const OUTPUT_SAMPLE_RATE: u32 = 48000;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LoopMode {
Off,
On,
}
pub struct Channel {
pub sample: Option<Arc<Sample>>,
pub pos: f64,
pub pitch: f64,
pub volume: u8, // 0..255
pub pan: u8, // 0..255
pub loop_mode: LoopMode,
pub priority: u8,
}
impl Default for Channel {
fn default() -> Self {
Self {
sample: None,
pos: 0.0,
pitch: 1.0,
volume: 255,
pan: 127,
loop_mode: LoopMode::Off,
priority: 0,
}
}
}
pub enum AudioCommand {
Play {
sample: Arc<Sample>,
voice_id: usize,
volume: u8,
pan: u8,
pitch: f64,
priority: u8,
loop_mode: LoopMode,
},
Stop {
voice_id: usize,
},
SetVolume {
voice_id: usize,
volume: u8,
},
SetPan {
voice_id: usize,
pan: u8,
},
SetPitch {
voice_id: usize,
pitch: f64,
},
}
pub struct Audio {
pub voices: [Channel; MAX_CHANNELS],
pub commands: Vec<AudioCommand>,
}
impl Audio {
pub fn new() -> Self {
Self {
voices: Default::default(),
commands: Vec::new(),
}
}
pub fn play(&mut self, sample: Arc<Sample>, voice_id: usize, volume: u8, pan: u8, pitch: f64, priority: u8, loop_mode: LoopMode) {
if voice_id < MAX_CHANNELS {
self.commands.push(AudioCommand::Play {
sample,
voice_id,
volume,
pan,
pitch,
priority,
loop_mode,
});
}
}
pub fn stop(&mut self, voice_id: usize) {
if voice_id < MAX_CHANNELS {
self.commands.push(AudioCommand::Stop { voice_id });
}
}
pub fn set_volume(&mut self, voice_id: usize, volume: u8) {
if voice_id < MAX_CHANNELS {
self.commands.push(AudioCommand::SetVolume { voice_id, volume });
}
}
pub fn set_pan(&mut self, voice_id: usize, pan: u8) {
if voice_id < MAX_CHANNELS {
self.commands.push(AudioCommand::SetPan { voice_id, pan });
}
}
pub fn set_pitch(&mut self, voice_id: usize, pitch: f64) {
if voice_id < MAX_CHANNELS {
self.commands.push(AudioCommand::SetPitch { voice_id, pitch });
}
}
pub fn is_playing(&self, voice_id: usize) -> bool {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].sample.is_some()
} else {
false
}
}
/// Limpa a fila de comandos. O Host deve consumir isso a cada frame.
pub fn clear_commands(&mut self) {
self.commands.clear();
}
}
+35 -24
View File
@@ -30,6 +30,9 @@ pub struct Gfx {
pub scene_fade_color: Color,
pub hud_fade_level: u8, // 0..31
pub hud_fade_color: Color,
// Cache de prioridades para evitar alocações por frame
priority_buckets: [Vec<usize>; 5],
}
impl Gfx {
@@ -65,6 +68,13 @@ impl Gfx {
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),
],
}
}
@@ -125,33 +135,29 @@ impl Gfx {
/// Segue a ordem de prioridade do manual (Capítulo 4.11).
pub fn render_all(&mut self) {
// 0. Fase de Preparação: Organiza quem deve ser desenhado em cada camada
// Criamos listas de índices para evitar percorrer os 512 sprites 5 vezes
let mut priority_buckets: [Vec<usize>; 5] = [
Vec::with_capacity(128),
Vec::with_capacity(128),
Vec::with_capacity(128),
Vec::with_capacity(128),
Vec::with_capacity(128),
];
// Limpa os buckets sem desalocar memória
for bucket in self.priority_buckets.iter_mut() {
bucket.clear();
}
for (idx, sprite) in self.sprites.iter().enumerate() {
if sprite.active && sprite.priority < 5 {
priority_buckets[sprite.priority as usize].push(idx);
self.priority_buckets[sprite.priority as usize].push(idx);
}
}
// 1. Sprites de prioridade 0 (Atrás da Layer 0 - o fundo do fundo)
self.draw_bucket(&priority_buckets[0]);
Self::draw_bucket_on_buffer(&mut self.back, self.w, self.h, &self.priority_buckets[0], &self.sprites, &self.banks);
for i in 0..self.layers.len() {
// 2. Layers de jogo (0 a 3)
self.render_layer(i);
let bank_id = self.layers[i].bank_id as usize;
if let Some(Some(bank)) = self.banks.get(bank_id) {
Self::draw_tile_map(&mut self.back, self.w, self.h, &self.layers[i].map, bank, self.layers[i].scroll_x, self.layers[i].scroll_y);
}
// 3. Sprites de acordo com prioridade
// i=0 desenha sprites priority 1 (sobre layer 0)
// i=1 desenha sprites priority 2 (sobre layer 1)
// i=2 desenha sprites priority 3 (sobre layer 2)
// i=3 desenha sprites priority 4 (sobre layer 3 - à frente de tudo)
self.draw_bucket(&priority_buckets[i + 1]);
Self::draw_bucket_on_buffer(&mut self.back, self.w, self.h, &self.priority_buckets[i + 1], &self.sprites, &self.banks);
}
// 4. Aplica Scene Fade (Afeta tudo desenhado até agora)
@@ -262,15 +268,20 @@ impl Gfx {
}
}
fn draw_bucket(&mut self, bucket: &[usize]) {
fn draw_bucket_on_buffer(
back: &mut [u16],
screen_w: usize,
screen_h: usize,
bucket: &[usize],
sprites: &[Sprite],
banks: &[Option<TileBank>],
) {
for &idx in bucket {
let sprite = &self.sprites[idx];
let bank = match self.banks.get(sprite.bank_id as usize) {
Some(Some(b)) => b,
_ => continue,
};
Self::draw_sprite_pixel_by_pixel(&mut self.back, self.w, self.h, sprite, bank);
let s = &sprites[idx];
let bank_id = s.bank_id as usize;
if let Some(Some(bank)) = banks.get(bank_id) {
Self::draw_sprite_pixel_by_pixel(back, screen_w, screen_h, s, bank);
}
}
}
+2
View File
@@ -2,9 +2,11 @@ mod gfx;
mod pad;
mod touch;
mod input_signal;
mod audio;
pub use gfx::Gfx;
pub use gfx::BlendMode;
pub use input_signal::InputSignals;
pub use pad::Pad;
pub use touch::Touch;
pub use audio::{Audio, Channel, AudioCommand, LoopMode, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};