- Ignore all input for ~1.2 s after power-up/reset (INPUT_GRACE_MS): the keyboard controller can emit stale bytes and pins can float, which used to start a game right after a restart. - High score + volume survive power cycles: Preferences (NVS, 'mc' namespace) loaded in setup(), saved on game over and on every volume key (U/V/M). arduino-esp32 commits NVS in end(), so savePrefs() does putUInt x2 + end() + begin() reopen. - SoundEngine::setVolume() restores a saved level (0 = stay muted, lastVol_ keeps unmute working). - Emulator: file-backed Preferences shim (mc-prefs.cfg, gitignored) so persistence is testable on the desktop.
56 lines
1.7 KiB
C++
56 lines
1.7 KiB
C++
/**
|
|
* @file sound_engine.h
|
|
* @brief Tiny non-blocking I2S sound engine for the T-Deck speaker.
|
|
*
|
|
* A FreeRTOS task owns the I2S peripheral (speaker, I2S_NUM_0) and renders
|
|
* queued sound events one after another. The game only ever pushes events,
|
|
* so it never blocks. Event types:
|
|
*
|
|
* SND_TONE fixed square-wave beep
|
|
* SND_SWEEP square wave gliding from freq down/up to freq2 (sirens, booms)
|
|
* SND_NOISE white-noise burst with linear decay (explosions)
|
|
*/
|
|
#pragma once
|
|
|
|
#include <Arduino.h>
|
|
|
|
enum SndType : uint8_t {
|
|
SND_TONE = 0, // fixed square wave
|
|
SND_SWEEP, // square wave gliding freq -> freq2
|
|
SND_NOISE, // white noise burst
|
|
};
|
|
|
|
struct SndEvent {
|
|
SndType type;
|
|
uint16_t freq; // Hz (tone, or sweep start)
|
|
uint16_t freq2; // Hz (sweep end; ignored for tone/noise)
|
|
uint16_t dur; // duration in ms
|
|
uint16_t amp; // peak amplitude 0..32767
|
|
};
|
|
|
|
class SoundEngine {
|
|
public:
|
|
static const uint8_t VOL_MAX = 8;
|
|
|
|
bool begin();
|
|
void play(const SndEvent &e);
|
|
|
|
// Master volume, applied to every rendered sound
|
|
void volumeUp();
|
|
void volumeDown();
|
|
void toggleMute();
|
|
void setVolume(uint8_t v); // restore a saved level (0 = muted)
|
|
uint8_t volume() const { return vol_; }
|
|
|
|
private:
|
|
static void trampoline(void *arg);
|
|
void task();
|
|
void renderTone(uint16_t freq, uint16_t durMs, uint16_t amp);
|
|
void renderSweep(uint16_t freq0, uint16_t freq1, uint16_t durMs, uint16_t amp);
|
|
void renderNoise(uint16_t durMs, uint16_t amp);
|
|
|
|
QueueHandle_t q_ = nullptr;
|
|
uint8_t vol_ = 5; // default: moderate
|
|
uint8_t lastVol_ = 5; // remembered for mute toggle
|
|
};
|