add audio
This commit is contained in:
+114
-1
@@ -1,14 +1,22 @@
|
||||
use crate::model::Color;
|
||||
use crate::peripherals::{Gfx, InputSignals, Pad, Touch};
|
||||
use crate::peripherals::{Gfx, InputSignals, Pad, Touch, Audio, LoopMode};
|
||||
use std::sync::Arc;
|
||||
use crate::model::Sample;
|
||||
|
||||
/// PROMETEU "hardware lógico" (v0).
|
||||
/// O Host alimenta INPUT SIGNALS e chama `step_frame()` em 60Hz.
|
||||
pub struct Machine {
|
||||
pub gfx: Gfx,
|
||||
pub audio: Audio,
|
||||
pub pad: Pad,
|
||||
pub touch: Touch,
|
||||
pub frame_index: u64,
|
||||
pub last_frame_cpu_time_us: u64,
|
||||
|
||||
// Assets de exemplo
|
||||
pub sample_square: Option<Arc<Sample>>,
|
||||
pub sample_kick: Option<Arc<Sample>>,
|
||||
pub sample_snare: Option<Arc<Sample>>,
|
||||
}
|
||||
|
||||
impl Machine {
|
||||
@@ -18,10 +26,14 @@ impl Machine {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
gfx: Gfx::new(Self::W, Self::H),
|
||||
audio: Audio::new(),
|
||||
pad: Pad::default(),
|
||||
touch: Touch::default(),
|
||||
frame_index: 0,
|
||||
last_frame_cpu_time_us: 0,
|
||||
sample_square: None,
|
||||
sample_kick: None,
|
||||
sample_snare: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +52,11 @@ impl Machine {
|
||||
pub fn begin_frame(&mut self, signals: &InputSignals) {
|
||||
self.frame_index += 1;
|
||||
|
||||
// Limpa comandos de áudio do frame anterior.
|
||||
// Nota: O Host deve consumir esses comandos ANTES ou DURANTE o step_frame se quiser processá-los.
|
||||
// Como o Host atual consome logo após o step_frame, limpar aqui no início do PRÓXIMO frame está correto.
|
||||
self.audio.clear_commands();
|
||||
|
||||
// Flags transitórias do TOUCH devem durar 1 frame.
|
||||
self.touch.begin_frame(signals);
|
||||
|
||||
@@ -178,6 +195,91 @@ impl Machine {
|
||||
// Se soltar o Start, podemos pausar algo futuramente
|
||||
}
|
||||
|
||||
// --- DEMO DE ÁUDIO ---
|
||||
// Inicializa assets de áudio se não existirem
|
||||
if self.sample_square.is_none() {
|
||||
// 1. Onda Quadrada com Loop (Instrumento)
|
||||
let freq = 440.0;
|
||||
let sample_rate = 44100;
|
||||
let period = (sample_rate as f32 / freq) as usize;
|
||||
let mut data = Vec::with_capacity(period);
|
||||
for i in 0..period {
|
||||
data.push(if i < period / 2 { 4000 } else { -4000 });
|
||||
}
|
||||
self.sample_square = Some(Arc::new(Sample::new(sample_rate, data).with_loop(0, period as u32)));
|
||||
|
||||
// 2. "Kick" simples (Pitch descent)
|
||||
let mut kick_data = Vec::new();
|
||||
for i in 0..4000 {
|
||||
let t = i as f32 / 4000.0;
|
||||
let f = 100.0 * (1.0 - t * 0.9);
|
||||
let val = (i as f32 * f * 2.0 * std::f32::consts::PI / 44100.0).sin();
|
||||
kick_data.push((val * 12000.0 * (1.0 - t)) as i16);
|
||||
}
|
||||
self.sample_kick = Some(Arc::new(Sample::new(44100, kick_data)));
|
||||
|
||||
// 3. "Snare" simples (White noise)
|
||||
let mut snare_data = Vec::new();
|
||||
for i in 0..3000 {
|
||||
let t = i as f32 / 3000.0;
|
||||
let noise = Self::rand_f32(i as u32) * 2.0 - 1.0;
|
||||
snare_data.push((noise * 8000.0 * (1.0 - t)) as i16);
|
||||
}
|
||||
self.sample_snare = Some(Arc::new(Sample::new(44100, snare_data)));
|
||||
}
|
||||
|
||||
// --- SEQUENCER SIMPLES (60Hz) ---
|
||||
let bpm = 125;
|
||||
let frames_per_beat = (60 * 60) / bpm;
|
||||
let frames_per_step = frames_per_beat / 4; // 16th notes
|
||||
|
||||
let step = (self.frame_index / frames_per_step) % 16;
|
||||
let is_new_step = self.frame_index % frames_per_step == 0;
|
||||
|
||||
if is_new_step {
|
||||
// Bassline (Square)
|
||||
// Notas: C-2, C-2, Eb2, F-2, C-2, C-2, G-2, Bb2...
|
||||
let melody = [
|
||||
36, 36, 39, 41,
|
||||
36, 36, 43, 46,
|
||||
36, 36, 39, 41,
|
||||
34, 35, 36, 0,
|
||||
];
|
||||
|
||||
let note = melody[step as usize];
|
||||
if note > 0 {
|
||||
// Cálculo de pitch otimizado (tabela simples ou aproximação rápida se necessário,
|
||||
// mas powf uma vez por step está ok. O problema é se fosse todo frame)
|
||||
let freq = 440.0 * 2.0f64.powf((note as f64 - 69.0) / 12.0);
|
||||
let pitch = freq / 440.0;
|
||||
if let Some(s) = &self.sample_square {
|
||||
self.audio.play(s.clone(), 0, 160, 100, pitch, 0, LoopMode::On);
|
||||
}
|
||||
}
|
||||
|
||||
// Drums
|
||||
let kick_pattern = 0b0101100100011001u16; // Invertido para facilitar bitshift
|
||||
let snare_pattern = 0b0001000000001000u16;
|
||||
|
||||
if (kick_pattern >> step) & 1 == 1 {
|
||||
if let Some(s) = &self.sample_kick {
|
||||
self.audio.play(s.clone(), 1, 255, 127, 1.0, 1, LoopMode::Off);
|
||||
}
|
||||
}
|
||||
if (snare_pattern >> step) & 1 == 1 {
|
||||
if let Some(s) = &self.sample_snare {
|
||||
self.audio.play(s.clone(), 2, 140, 150, 1.0, 1, LoopMode::Off);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Toca um "beep" extra se apertar A (mantendo interatividade)
|
||||
if self.pad.a.pressed {
|
||||
if let Some(s) = &self.sample_square {
|
||||
self.audio.play(s.clone(), 3, 255, 60, 2.0, 10, LoopMode::Off);
|
||||
}
|
||||
}
|
||||
|
||||
// Post-FX Fade Pulsante
|
||||
let pulse = (self.frame_index / 4) % 64;
|
||||
let level = if pulse > 31 { 63 - pulse } else { pulse };
|
||||
@@ -190,4 +292,15 @@ impl Machine {
|
||||
pub fn end_frame(&mut self) {
|
||||
self.gfx.present();
|
||||
}
|
||||
|
||||
/// Helper para noise determinístico
|
||||
fn rand_f32(seed: u32) -> f32 {
|
||||
let mut x = seed.wrapping_add(0x9E3779B9);
|
||||
x = x ^ (x >> 16);
|
||||
x = x.wrapping_mul(0x85EBCA6B);
|
||||
x = x ^ (x >> 13);
|
||||
x = x.wrapping_mul(0xC2B2AE35);
|
||||
x = x ^ (x >> 16);
|
||||
(x as f32) / (u32::MAX as f32)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ mod tile;
|
||||
mod tile_layer;
|
||||
mod tile_bank;
|
||||
mod sprite;
|
||||
mod sample;
|
||||
|
||||
pub use button::Button;
|
||||
pub use color::Color;
|
||||
@@ -11,3 +12,4 @@ pub use tile::Tile;
|
||||
pub use tile_bank::{TileBank, TileSize};
|
||||
pub use tile_layer::{HudTileLayer, ScrollableTileLayer, TileMap};
|
||||
pub use sprite::Sprite;
|
||||
pub use sample::Sample;
|
||||
|
||||
@@ -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,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();
|
||||
}
|
||||
}
|
||||
@@ -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,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};
|
||||
|
||||
Reference in New Issue
Block a user