Add Missile Command game for T-Deck + desktop emulator
Game (examples/MissileCommand): - Classic Missile Command: 6 cities, 3 batteries x 10 missiles, escalating waves, smart bombs, score multiplier, session high score - Trackball aims, press/tap fires, keyboard A/S/D selects battery, screen tap aims+fires - Rendering: incremental TFT_eSPI drawing (persistent enemy trails that vanish on death, no AA-rocket trails, explosion circles that repair terrain, ghost-free crosshair) - Sound (sound_engine.cpp): non-blocking I2S task on core 0; wave-start alarm of four falling tones (like the original), sweeps/noise effects, U/V/M keyboard volume control with OSD, master volume scaling Emulator (emulator/): - SDL2 host that compiles the unmodified sketch against shim headers (Arduino, TFT_eSPI->framebuffer, GT911 touch, I2C keyboard, I2S->SDL audio); arrow keys emulate the trackball, --autoplay/--frames/--dump flags for headless smoke tests
This commit is contained in:
@@ -0,0 +1 @@
|
||||
missilecommand-emu
|
||||
@@ -0,0 +1,34 @@
|
||||
# Local SDL2 emulator for MissileCommand (run the game on your PC)
|
||||
#
|
||||
# make build ./missilecommand-emu
|
||||
# make run build + launch the window
|
||||
# make smoke headless test: 240 frames, dump the last frame to a BMP
|
||||
#
|
||||
CXX ?= g++
|
||||
CXXFLAGS ?= -std=gnu++17 -O2 -Wall -Wextra
|
||||
SDLFLAGS := -I/usr/include/SDL2
|
||||
INC := -Isrc/shim -I../examples/MissileCommand
|
||||
LIBS := -lSDL2 -lSDL2_ttf
|
||||
|
||||
GAME_DIR := ../examples/MissileCommand
|
||||
SHIMS := $(wildcard src/shim/*.h) $(wildcard src/shim/driver/*.h)
|
||||
EMU := missilecommand-emu
|
||||
|
||||
.PHONY: all run smoke clean
|
||||
|
||||
all: $(EMU)
|
||||
|
||||
$(EMU): src/main.cpp $(GAME_DIR)/sound_engine.cpp $(GAME_DIR)/MissileCommand.ino $(SHIMS)
|
||||
$(CXX) $(CXXFLAGS) $(SDLFLAGS) $(INC) \
|
||||
src/main.cpp $(GAME_DIR)/sound_engine.cpp -o $@ $(LIBS)
|
||||
|
||||
run: $(EMU)
|
||||
./$(EMU)
|
||||
|
||||
# Headless smoke test: dummy video/audio, run N frames, save the last frame.
|
||||
# Feed some keys: 'a' starts the game, arrows steer, etc. via --script.
|
||||
smoke: $(EMU)
|
||||
./$(EMU) --frames 240 --dump smoke_frame.bmp
|
||||
|
||||
clean:
|
||||
rm -f $(EMU) smoke_frame.bmp
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* SDL2 host for the MissileCommand sketch — run the game on your PC.
|
||||
*
|
||||
* Input mapping:
|
||||
* Arrow keys trackball roll (hold to keep rolling)
|
||||
* Enter / right-click trackball press (fire)
|
||||
* Left-click screen tap (aim + fire)
|
||||
* A S D fire from left / center / right battery
|
||||
* Space fire from nearest battery
|
||||
* U / V volume up / down
|
||||
* M mute toggle
|
||||
*/
|
||||
#include <SDL.h>
|
||||
#include <SDL_ttf.h>
|
||||
#include <cstdio>
|
||||
#include <cctype>
|
||||
#include <cstring>
|
||||
#include "emu_gfx.h"
|
||||
#include "emu_input.h"
|
||||
|
||||
// pull in the whole game as a single translation unit
|
||||
#include "MissileCommand.ino"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Global instances declared extern in the shims
|
||||
// ---------------------------------------------------------------------------
|
||||
namespace emu {
|
||||
uint8_t pinLevels[64];
|
||||
bool touchDown = false;
|
||||
int touchX = 0, touchY = 0;
|
||||
std::deque<uint8_t> keyboard;
|
||||
bool quitRequested = false;
|
||||
} // namespace emu
|
||||
|
||||
namespace emuGfx {
|
||||
uint32_t fb[W * H];
|
||||
SDL_Texture *tex = nullptr;
|
||||
bool dirty = true;
|
||||
} // namespace emuGfx
|
||||
|
||||
SerialSim Serial;
|
||||
TwoWire Wire;
|
||||
SPIClass SPI;
|
||||
|
||||
const FreeFontStub FreeSansBold24pt7b {0};
|
||||
const FreeFontStub FreeSansBold18pt7b {0};
|
||||
const FreeFontStub FreeSansOblique12pt7b {0};
|
||||
const FreeFontStub FreeSans12pt7b {0};
|
||||
|
||||
static void saveBmp(const char *path)
|
||||
{
|
||||
SDL_Surface *s = SDL_CreateRGBSurfaceWithFormatFrom(
|
||||
emuGfx::fb, emuGfx::W, emuGfx::H, 32, emuGfx::W * 4, SDL_PIXELFORMAT_ABGR8888);
|
||||
if (s) {
|
||||
SDL_SaveBMP(s, path);
|
||||
SDL_FreeSurface(s);
|
||||
std::printf("[emu] frame dumped to %s\n", path);
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
long maxFrames = -1;
|
||||
const char *dumpPath = nullptr;
|
||||
bool autoplay = false;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--frames") && i + 1 < argc) maxFrames = atol(argv[++i]);
|
||||
else if (!strcmp(argv[i], "--dump") && i + 1 < argc) dumpPath = argv[++i];
|
||||
else if (!strcmp(argv[i], "--autoplay")) autoplay = true;
|
||||
}
|
||||
|
||||
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) {
|
||||
std::printf("SDL_Init failed: %s\n", SDL_GetError());
|
||||
return 1;
|
||||
}
|
||||
TTF_Init();
|
||||
|
||||
SDL_Window *win = SDL_CreateWindow("Missile Command — T-Deck emulator",
|
||||
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
|
||||
640, 480, SDL_WINDOW_RESIZABLE);
|
||||
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
|
||||
if (!ren) ren = SDL_CreateRenderer(win, -1, 0); // software fallback (headless)
|
||||
SDL_RenderSetLogicalSize(ren, emuGfx::W, emuGfx::H);
|
||||
emuGfx::tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_ABGR8888,
|
||||
SDL_TEXTUREACCESS_STREAMING, emuGfx::W, emuGfx::H);
|
||||
|
||||
for (auto &p : emu::pinLevels) p = 1; // everything pulled up
|
||||
|
||||
setup();
|
||||
|
||||
const uint8_t dirPin[4] = { BOARD_TBOX_G02, BOARD_TBOX_G01, BOARD_TBOX_G04, BOARD_TBOX_G03 };
|
||||
bool held[4] = { false, false, false, false };
|
||||
uint32_t frame = 0;
|
||||
|
||||
bool running = true;
|
||||
while (running && !emu::quitRequested) {
|
||||
SDL_Event e;
|
||||
while (SDL_PollEvent(&e)) {
|
||||
switch (e.type) {
|
||||
case SDL_QUIT:
|
||||
running = false;
|
||||
break;
|
||||
|
||||
case SDL_KEYDOWN: {
|
||||
if (e.key.repeat) break;
|
||||
SDL_Keycode k = e.key.keysym.sym;
|
||||
switch (k) {
|
||||
case SDLK_RIGHT: held[0] = true; emu::pinLevels[dirPin[0]] = 0; break;
|
||||
case SDLK_UP: held[1] = true; emu::pinLevels[dirPin[1]] = 0; break;
|
||||
case SDLK_LEFT: held[2] = true; emu::pinLevels[dirPin[2]] = 0; break;
|
||||
case SDLK_DOWN: held[3] = true; emu::pinLevels[dirPin[3]] = 0; break;
|
||||
case SDLK_RETURN:
|
||||
case SDLK_KP_ENTER:
|
||||
emu::pinLevels[BOARD_BOOT_PIN] = 0; // trackball press
|
||||
break;
|
||||
case SDLK_SPACE:
|
||||
emu::keyboard.push_back(' ');
|
||||
break;
|
||||
case SDLK_ESCAPE:
|
||||
running = false;
|
||||
break;
|
||||
default: {
|
||||
const char *name = SDL_GetKeyName(k);
|
||||
if (name && strlen(name) == 1) {
|
||||
emu::keyboard.push_back((uint8_t)tolower((unsigned char)name[0]));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case SDL_KEYUP: {
|
||||
SDL_Keycode k = e.key.keysym.sym;
|
||||
switch (k) {
|
||||
case SDLK_RIGHT: held[0] = false; emu::pinLevels[dirPin[0]] = 1; break;
|
||||
case SDLK_UP: held[1] = false; emu::pinLevels[dirPin[1]] = 1; break;
|
||||
case SDLK_LEFT: held[2] = false; emu::pinLevels[dirPin[2]] = 1; break;
|
||||
case SDLK_DOWN: held[3] = false; emu::pinLevels[dirPin[3]] = 1; break;
|
||||
case SDLK_RETURN:
|
||||
case SDLK_KP_ENTER:
|
||||
emu::pinLevels[BOARD_BOOT_PIN] = 1;
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case SDL_MOUSEBUTTONDOWN:
|
||||
case SDL_MOUSEBUTTONUP: {
|
||||
int ww, wh;
|
||||
SDL_GetWindowSize(win, &ww, &wh);
|
||||
int wx = (int)((int64_t)e.button.x * emuGfx::W / (ww > 0 ? ww : 1));
|
||||
int wy = (int)((int64_t)e.button.y * emuGfx::H / (wh > 0 ? wh : 1));
|
||||
if (wx < 0) wx = 0;
|
||||
if (wx > emuGfx::W - 1) wx = emuGfx::W - 1;
|
||||
if (wy < 0) wy = 0;
|
||||
if (wy > emuGfx::H - 1) wy = emuGfx::H - 1;
|
||||
|
||||
if (e.button.button == SDL_BUTTON_LEFT) {
|
||||
bool down = (e.type == SDL_MOUSEBUTTONDOWN);
|
||||
emu::touchDown = down;
|
||||
emu::touchX = wx;
|
||||
emu::touchY = wy;
|
||||
} else if (e.button.button == SDL_BUTTON_RIGHT) {
|
||||
emu::pinLevels[BOARD_BOOT_PIN] =
|
||||
(e.type == SDL_MOUSEBUTTONDOWN) ? 0 : 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Simulate a rolling trackball: toggle the held quadrant pin so the
|
||||
// game keeps seeing edges while the arrow key is down.
|
||||
if (++frame % 3 == 0) {
|
||||
for (int d = 0; d < 4; d++) {
|
||||
if (held[d]) emu::pinLevels[dirPin[d]] ^= 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Headless test mode: start the game, wander the crosshair, keep firing.
|
||||
if (autoplay) {
|
||||
static bool started = false;
|
||||
if (!started && frame >= 5) {
|
||||
emu::keyboard.push_back('a');
|
||||
started = true;
|
||||
}
|
||||
static int dir = 0;
|
||||
if (frame % 45 == 0) dir = (dir + 1) & 3;
|
||||
if (frame % 4 == 0) emu::pinLevels[dirPin[dir]] ^= 1;
|
||||
if (frame % 75 == 0) emu::keyboard.push_back('s');
|
||||
}
|
||||
|
||||
loop();
|
||||
|
||||
if (emuGfx::dirty) {
|
||||
SDL_UpdateTexture(emuGfx::tex, nullptr, emuGfx::fb,
|
||||
emuGfx::W * sizeof(uint32_t));
|
||||
emuGfx::dirty = false;
|
||||
}
|
||||
SDL_RenderClear(ren);
|
||||
SDL_RenderCopy(ren, emuGfx::tex, nullptr, nullptr);
|
||||
SDL_RenderPresent(ren);
|
||||
|
||||
if (maxFrames > 0 && --maxFrames == 0) {
|
||||
running = false;
|
||||
if (dumpPath) saveBmp(dumpPath);
|
||||
}
|
||||
}
|
||||
|
||||
TTF_Quit();
|
||||
SDL_Quit();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* Arduino compatibility shim for the desktop emulator (no real hardware).
|
||||
* Implements the exact subset of the Arduino API used by MissileCommand.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cmath>
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
|
||||
#include "emu_input.h"
|
||||
|
||||
typedef uint8_t byte;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// String
|
||||
// ---------------------------------------------------------------------------
|
||||
class String {
|
||||
public:
|
||||
std::string s;
|
||||
String() {}
|
||||
String(const char *c) : s(c) {}
|
||||
String(const std::string &x) : s(x) {}
|
||||
String(char c) : s(1, c) {}
|
||||
String(int v) : s(std::to_string(v)) {}
|
||||
String(long v) : s(std::to_string(v)) {}
|
||||
String(unsigned v) : s(std::to_string(v)) {}
|
||||
String(unsigned long v) : s(std::to_string(v)) {}
|
||||
String(float v) : s(std::to_string(v)) {}
|
||||
const char *c_str() const { return s.c_str(); }
|
||||
unsigned length() const { return (unsigned)s.length(); }
|
||||
};
|
||||
|
||||
inline String operator+(const String &a, const String &b) { return String(a.s + b.s); }
|
||||
inline String operator+(const String &a, const char *b) { return String(a.s + b); }
|
||||
inline String operator+(const char *a, const String &b) { return String(std::string(a) + b.s); }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Time
|
||||
// ---------------------------------------------------------------------------
|
||||
inline unsigned long millis()
|
||||
{
|
||||
using namespace std::chrono;
|
||||
static const auto start = steady_clock::now();
|
||||
return (unsigned long)duration_cast<milliseconds>(steady_clock::now() - start).count();
|
||||
}
|
||||
|
||||
inline unsigned long micros()
|
||||
{
|
||||
using namespace std::chrono;
|
||||
static const auto start = steady_clock::now();
|
||||
return (unsigned long)duration_cast<microseconds>(steady_clock::now() - start).count();
|
||||
}
|
||||
|
||||
inline void delay(unsigned long ms)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
|
||||
}
|
||||
|
||||
inline void delayMicroseconds(unsigned int us)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(us));
|
||||
}
|
||||
|
||||
inline void yield() {}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Random (Arduino-style)
|
||||
// ---------------------------------------------------------------------------
|
||||
inline long random(long maxv) { return maxv > 0 ? std::rand() % maxv : 0; }
|
||||
inline long random(long lo, long hi) { return hi > lo ? lo + std::rand() % (hi - lo) : lo; }
|
||||
inline void randomSeed(unsigned long seed) { std::srand((unsigned)seed); }
|
||||
inline uint32_t esp_random()
|
||||
{
|
||||
return ((uint32_t)std::rand() << 17) ^ (uint32_t)std::rand() ^ millis();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GPIO
|
||||
// ---------------------------------------------------------------------------
|
||||
#define INPUT 0
|
||||
#define OUTPUT 1
|
||||
#define INPUT_PULLUP 2
|
||||
#define HIGH 1
|
||||
#define LOW 0
|
||||
|
||||
inline void pinMode(int, int) {}
|
||||
inline int digitalRead(int pin) { return emu::pinLevels[pin & 63]; }
|
||||
inline void digitalWrite(int, int) {}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FreeRTOS-ish primitives (queues + detached threads)
|
||||
// ---------------------------------------------------------------------------
|
||||
#define portMAX_DELAY 0xFFFFFFFFu
|
||||
#define pdTRUE 1
|
||||
#define pdFALSE 0
|
||||
|
||||
typedef void *TaskHandle_t;
|
||||
|
||||
namespace emu {
|
||||
struct FakeQueue {
|
||||
std::mutex m;
|
||||
std::condition_variable cv;
|
||||
std::deque<std::string> items; // one raw byte blob per item
|
||||
size_t itemSize = 0;
|
||||
size_t capacity = 0;
|
||||
};
|
||||
} // namespace emu
|
||||
|
||||
typedef emu::FakeQueue *QueueHandle_t;
|
||||
|
||||
inline QueueHandle_t xQueueCreate(unsigned len, unsigned itemSize)
|
||||
{
|
||||
auto *q = new emu::FakeQueue();
|
||||
q->itemSize = itemSize;
|
||||
q->capacity = len;
|
||||
return q;
|
||||
}
|
||||
|
||||
inline int xQueueSend(QueueHandle_t q, const void *item, unsigned /*timeout*/)
|
||||
{
|
||||
if (!q) return pdFALSE;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(q->m);
|
||||
if (q->items.size() >= q->capacity) return pdFALSE; // drop, like the device
|
||||
q->items.emplace_back((const char *)item, q->itemSize);
|
||||
}
|
||||
q->cv.notify_one();
|
||||
return pdTRUE;
|
||||
}
|
||||
|
||||
inline int xQueueReceive(QueueHandle_t q, void *out, unsigned timeout)
|
||||
{
|
||||
if (!q) return pdFALSE;
|
||||
std::unique_lock<std::mutex> lk(q->m);
|
||||
if (timeout == portMAX_DELAY) {
|
||||
q->cv.wait(lk, [&] { return !q->items.empty(); });
|
||||
} else if (timeout == 0) {
|
||||
if (q->items.empty()) return pdFALSE;
|
||||
} else if (!q->cv.wait_for(lk, std::chrono::milliseconds(timeout),
|
||||
[&] { return !q->items.empty(); })) {
|
||||
return pdFALSE;
|
||||
}
|
||||
std::string it = q->items.front();
|
||||
q->items.pop_front();
|
||||
size_t n = q->itemSize < it.size() ? q->itemSize : it.size();
|
||||
memcpy(out, it.data(), n);
|
||||
return pdTRUE;
|
||||
}
|
||||
|
||||
inline int xTaskCreatePinnedToCore(void (*fn)(void *), const char *, unsigned, void *arg, int,
|
||||
TaskHandle_t *, int)
|
||||
{
|
||||
std::thread([fn, arg]() { fn(arg); }).detach();
|
||||
return pdTRUE;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Serial
|
||||
// ---------------------------------------------------------------------------
|
||||
struct SerialSim {
|
||||
void begin(unsigned long) {}
|
||||
template <typename... A> void printf(const char *fmt, A... a) { std::printf(fmt, a...); }
|
||||
void println() { std::printf("\n"); }
|
||||
void println(const char *s) { std::printf("%s\n", s); }
|
||||
void println(const String &s) { std::printf("%s\n", s.c_str()); }
|
||||
void println(int v) { std::printf("%d\n", v); }
|
||||
void setDebugOutput(bool) {}
|
||||
};
|
||||
|
||||
extern SerialSim Serial;
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
class SPIClass {
|
||||
public:
|
||||
void begin(int = -1, int = -1, int = -1) {}
|
||||
void end() {}
|
||||
};
|
||||
|
||||
extern SPIClass SPI;
|
||||
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* TFT_eSPI shim: renders the same drawing calls into a 320x240 ABGR8888
|
||||
* framebuffer that the SDL2 host pushes to a window. Text uses SDL_ttf with
|
||||
* DejaVu fonts as stand-ins for the TFT_eSPI font set.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <SDL.h>
|
||||
#include <SDL_ttf.h>
|
||||
#include "emu_gfx.h"
|
||||
#include <map>
|
||||
|
||||
// ---- TFT_eSPI RGB565 color constants (the ones the game uses) ----
|
||||
#define TFT_BLACK 0x0000
|
||||
#define TFT_NAVY 0x000F
|
||||
#define TFT_DARKGREEN 0x0320
|
||||
#define TFT_DARKGREY 0x7BEF
|
||||
#define TFT_BLUE 0x001F
|
||||
#define TFT_GREEN 0x07E0
|
||||
#define TFT_CYAN 0x07FF
|
||||
#define TFT_RED 0xF800
|
||||
#define TFT_MAGENTA 0xF81F
|
||||
#define TFT_YELLOW 0xFFE0
|
||||
#define TFT_ORANGE 0xFDA0
|
||||
#define TFT_GREENYELLOW 0xAFE5
|
||||
#define TFT_GOLD 0xFEA0
|
||||
#define TFT_WHITE 0xFFFF
|
||||
#define TFT_SKYBLUE 0x867D
|
||||
|
||||
enum TextDatum {
|
||||
TL_DATUM = 0, TC_DATUM = 1, TR_DATUM = 2,
|
||||
ML_DATUM = 3, MC_DATUM = 4, MR_DATUM = 5,
|
||||
BL_DATUM = 6, BC_DATUM = 7, BR_DATUM = 8
|
||||
};
|
||||
|
||||
// The .ino only needs the address of these font objects.
|
||||
struct FreeFontStub { int _; };
|
||||
extern const FreeFontStub FreeSansBold24pt7b;
|
||||
extern const FreeFontStub FreeSansBold18pt7b;
|
||||
extern const FreeFontStub FreeSansOblique12pt7b;
|
||||
extern const FreeFontStub FreeSans12pt7b;
|
||||
|
||||
static inline uint32_t rgb565to888(uint16_t c)
|
||||
{
|
||||
uint32_t r = ((c >> 11) & 0x1F) * 255 / 31;
|
||||
uint32_t g = ((c >> 5) & 0x3F) * 255 / 63;
|
||||
uint32_t b = (c & 0x1F) * 255 / 31;
|
||||
return 0xFF000000u | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
|
||||
class TFT_eSPI {
|
||||
public:
|
||||
TFT_eSPI() {}
|
||||
|
||||
void begin() {}
|
||||
void setRotation(uint8_t) {}
|
||||
int width() { return emuGfx::W; }
|
||||
int height() { return emuGfx::H; }
|
||||
|
||||
void fillScreen(uint32_t c) { fillRect(0, 0, emuGfx::W, emuGfx::H, c); }
|
||||
|
||||
void drawPixel(int32_t x, int32_t y, uint32_t c)
|
||||
{
|
||||
if (x < 0 || y < 0 || x >= emuGfx::W || y >= emuGfx::H) return;
|
||||
emuGfx::fb[y * emuGfx::W + x] = rgb565to888((uint16_t)c);
|
||||
emuGfx::dirty = true;
|
||||
}
|
||||
|
||||
void fillRect(int32_t x, int32_t y, int32_t w, int32_t h, uint32_t c)
|
||||
{
|
||||
uint32_t px = rgb565to888((uint16_t)c);
|
||||
for (int32_t j = y; j < y + h; j++) {
|
||||
if (j < 0 || j >= emuGfx::H) continue;
|
||||
for (int32_t i = x; i < x + w; i++) {
|
||||
if (i < 0 || i >= emuGfx::W) continue;
|
||||
emuGfx::fb[j * emuGfx::W + i] = px;
|
||||
}
|
||||
}
|
||||
emuGfx::dirty = true;
|
||||
}
|
||||
|
||||
void drawRect(int32_t x, int32_t y, int32_t w, int32_t h, uint32_t c)
|
||||
{
|
||||
drawFastHLine(x, y, w, c);
|
||||
drawFastHLine(x, y + h - 1, w, c);
|
||||
drawFastVLine(x, y, h, c);
|
||||
drawFastVLine(x + w - 1, y, h, c);
|
||||
}
|
||||
|
||||
void drawFastHLine(int32_t x, int32_t y, int32_t w, uint32_t c) { fillRect(x, y, w, 1, c); }
|
||||
void drawFastVLine(int32_t x, int32_t y, int32_t h, uint32_t c) { fillRect(x, y, 1, h, c); }
|
||||
|
||||
void drawLine(int32_t x0, int32_t y0, int32_t x1, int32_t y1, uint32_t c)
|
||||
{
|
||||
int dx = std::abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
|
||||
int dy = -std::abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
|
||||
int err = dx + dy;
|
||||
for (;;) {
|
||||
drawPixel(x0, y0, c);
|
||||
if (x0 == x1 && y0 == y1) break;
|
||||
int e2 = 2 * err;
|
||||
if (e2 >= dy) { err += dy; x0 += sx; }
|
||||
if (e2 <= dx) { err += dx; y0 += sy; }
|
||||
}
|
||||
}
|
||||
|
||||
void fillCircle(int32_t x0, int32_t y0, int32_t r, uint32_t c)
|
||||
{
|
||||
for (int dy = -r; dy <= r; dy++) {
|
||||
int dx = (int)sqrtf((float)(r * r - dy * dy));
|
||||
drawFastHLine(x0 - dx, y0 + dy, dx * 2 + 1, c);
|
||||
}
|
||||
}
|
||||
|
||||
void drawCircle(int32_t x0, int32_t y0, int32_t r, uint32_t c)
|
||||
{
|
||||
for (int x = -r; x <= r; x++) {
|
||||
int y = (int)(sqrtf((float)(r * r - x * x)) + 0.5f);
|
||||
drawPixel(x0 + x, y0 + y, c);
|
||||
drawPixel(x0 + x, y0 - y, c);
|
||||
drawPixel(x0 + y, y0 + x, c);
|
||||
drawPixel(x0 - y, y0 + x, c);
|
||||
drawPixel(x0 + y, y0 - x, c);
|
||||
drawPixel(x0 - y, y0 - x, c);
|
||||
}
|
||||
}
|
||||
|
||||
void fillTriangle(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t x2, int32_t y2,
|
||||
uint32_t c)
|
||||
{
|
||||
int32_t minx = std::min(std::min(x0, x1), x2);
|
||||
int32_t maxx = std::max(std::max(x0, x1), x2);
|
||||
int32_t miny = std::min(std::min(y0, y1), y2);
|
||||
int32_t maxy = std::max(std::max(y0, y1), y2);
|
||||
float d = (float)((y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2));
|
||||
if (d == 0) return;
|
||||
for (int32_t y = miny; y <= maxy; y++) {
|
||||
for (int32_t x = minx; x <= maxx; x++) {
|
||||
float l0 = ((y1 - y2) * (x - x2) + (x2 - x1) * (y - y2)) / d;
|
||||
float l1 = ((y2 - y0) * (x - x2) + (x0 - x2) * (y - y2)) / d;
|
||||
float l2 = 1.0f - l0 - l1;
|
||||
if (l0 >= -0.001f && l1 >= -0.001f && l2 >= -0.001f) {
|
||||
drawPixel(x, y, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setTextDatum(uint8_t d) { datum = d; }
|
||||
void setTextFont(uint8_t f) { fontNum = f; freeFontActive = false; }
|
||||
void setFreeFont(const void *f) { fontPtr = f; freeFontActive = true; }
|
||||
void setTextColor(uint16_t fg) { this->fg = fg; bgOpaque = false; }
|
||||
void setTextColor(uint16_t fg, uint16_t bg) { this->fg = fg; this->bg = bg; bgOpaque = true; }
|
||||
|
||||
void drawString(const String &s, int32_t x, int32_t y)
|
||||
{
|
||||
if (s.s.empty()) return;
|
||||
int size = freeFontActive ? freeFontSize(fontPtr) : (fontNum >= 2 ? 15 : 10);
|
||||
TTF_Font *f = getFont(size, freeFontActive);
|
||||
if (!f) return;
|
||||
|
||||
SDL_Color col = sdlColor(fg);
|
||||
SDL_Surface *surf = TTF_RenderUTF8_Blended(f, s.s.c_str(), col);
|
||||
if (!surf) return;
|
||||
SDL_Surface *conv = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_ABGR8888, 0);
|
||||
SDL_FreeSurface(surf);
|
||||
if (!conv) return;
|
||||
|
||||
int w = conv->w, h = conv->h;
|
||||
int dx = x, dy = y;
|
||||
switch (datum) {
|
||||
case TL_DATUM: dx = x; dy = y; break;
|
||||
case TC_DATUM: dx = x - w/2; dy = y; break;
|
||||
case TR_DATUM: dx = x - w; dy = y; break;
|
||||
case ML_DATUM: dx = x; dy = y - h/2; break;
|
||||
case MC_DATUM: dx = x - w/2; dy = y - h/2; break;
|
||||
case MR_DATUM: dx = x - w; dy = y - h/2; break;
|
||||
case BL_DATUM: dx = x; dy = y - h; break;
|
||||
case BC_DATUM: dx = x - w/2; dy = y - h; break;
|
||||
case BR_DATUM: dx = x - w; dy = y - h; break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
if (bgOpaque) fillRect(dx, dy, w, h, bg);
|
||||
|
||||
uint32_t *px = (uint32_t *)conv->pixels;
|
||||
int pitch = conv->pitch / 4;
|
||||
for (int j = 0; j < h; j++) {
|
||||
int ty = dy + j;
|
||||
if (ty < 0 || ty >= emuGfx::H) continue;
|
||||
for (int i = 0; i < w; i++) {
|
||||
int tx = dx + i;
|
||||
if (tx < 0 || tx >= emuGfx::W) continue;
|
||||
uint32_t p = px[j * pitch + i];
|
||||
if ((p >> 24) > 0) emuGfx::fb[ty * emuGfx::W + tx] = p;
|
||||
}
|
||||
}
|
||||
SDL_FreeSurface(conv);
|
||||
emuGfx::dirty = true;
|
||||
}
|
||||
|
||||
private:
|
||||
static SDL_Color sdlColor(uint16_t c565)
|
||||
{
|
||||
uint32_t p = rgb565to888(c565);
|
||||
SDL_Color c;
|
||||
c.r = (uint8_t)(p & 0xFF);
|
||||
c.g = (uint8_t)((p >> 8) & 0xFF);
|
||||
c.b = (uint8_t)((p >> 16) & 0xFF);
|
||||
c.a = 255;
|
||||
return c;
|
||||
}
|
||||
|
||||
static int freeFontSize(const void *f)
|
||||
{
|
||||
if (f == (const void *)&FreeSansBold18pt7b) return 24;
|
||||
if (f == (const void *)&FreeSansOblique12pt7b) return 16;
|
||||
if (f == (const void *)&FreeSans12pt7b) return 16;
|
||||
return 32; // 24pt and anything unknown
|
||||
}
|
||||
|
||||
static TTF_Font *getFont(int size, bool bold)
|
||||
{
|
||||
static std::map<std::pair<int, bool>, TTF_Font *> cache;
|
||||
auto key = std::make_pair(size, bold);
|
||||
auto it = cache.find(key);
|
||||
if (it != cache.end()) return it->second;
|
||||
|
||||
const char *paths[] = {
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
|
||||
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
|
||||
"/usr/share/fonts/dejavu/DejaVuSans-Bold.ttf",
|
||||
};
|
||||
const char *path = bold ? paths[1] : paths[0];
|
||||
TTF_Font *f = TTF_OpenFont(path, size);
|
||||
if (!f) {
|
||||
f = TTF_OpenFont(paths[2], size);
|
||||
if (!f) f = TTF_OpenFont(paths[3], size);
|
||||
}
|
||||
cache[key] = f;
|
||||
return f;
|
||||
}
|
||||
|
||||
uint8_t datum = MC_DATUM;
|
||||
uint8_t fontNum = 1;
|
||||
const void *fontPtr = nullptr;
|
||||
bool freeFontActive = false;
|
||||
uint16_t fg = TFT_WHITE;
|
||||
uint16_t bg = TFT_BLACK;
|
||||
bool bgOpaque = false;
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include "Wire.h"
|
||||
#include "emu_input.h"
|
||||
|
||||
/**
|
||||
* Touch shim: left mouse button on the canvas acts as a GT911 touch tap.
|
||||
*/
|
||||
class TouchDrvGT911 {
|
||||
public:
|
||||
void setPins(int, int) {}
|
||||
bool begin(TwoWire &) { return true; }
|
||||
bool begin(TwoWire &, uint8_t) { return true; }
|
||||
void setMaxCoordinates(int, int) {}
|
||||
void setSwapXY(bool) {}
|
||||
void setMirrorXY(bool, bool) {}
|
||||
void sleep() {}
|
||||
|
||||
bool isPressed() { return emu::touchDown; }
|
||||
|
||||
uint8_t getPoint(int16_t *x, int16_t *y, uint8_t n)
|
||||
{
|
||||
if (n == 0 || !emu::touchDown) return 0;
|
||||
x[0] = (int16_t)emu::touchX;
|
||||
y[0] = (int16_t)emu::touchY;
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include "emu_input.h"
|
||||
|
||||
/**
|
||||
* TwoWire shim. Address 0x55 behaves like the T-Deck keyboard controller:
|
||||
* requestFrom() pops at most `len` queued ASCII bytes; empty buffer returns 0
|
||||
* bytes (available() == 0), just like an absent keyboard.
|
||||
*/
|
||||
class TwoWire {
|
||||
public:
|
||||
void begin(int, int) {}
|
||||
void beginTransmission(uint8_t) { txBuf.clear(); }
|
||||
uint8_t endTransmission() { return 0; }
|
||||
size_t write(uint8_t b) { txBuf.push_back(b); return 1; }
|
||||
|
||||
uint8_t requestFrom(uint8_t /*addr*/, uint8_t len)
|
||||
{
|
||||
rx.clear();
|
||||
while (len-- > 0 && !emu::keyboard.empty()) {
|
||||
rx.push_back(emu::keyboard.front());
|
||||
emu::keyboard.pop_front();
|
||||
}
|
||||
return (uint8_t)rx.size();
|
||||
}
|
||||
uint8_t requestFrom(uint8_t a, uint8_t l, uint8_t) { return requestFrom(a, l); }
|
||||
|
||||
int available() { return (int)rx.size(); }
|
||||
|
||||
int read()
|
||||
{
|
||||
if (rx.empty()) return -1;
|
||||
int v = rx.front();
|
||||
rx.pop_front();
|
||||
return v;
|
||||
}
|
||||
|
||||
private:
|
||||
std::deque<uint8_t> txBuf;
|
||||
std::deque<uint8_t> rx;
|
||||
};
|
||||
|
||||
extern TwoWire Wire;
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* I2S driver shim: routes i2s_write() output to an SDL audio device
|
||||
* (8 kHz mono S16, queue-based, exactly what the sound engine feeds).
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <SDL.h>
|
||||
|
||||
#define ESP_OK 0
|
||||
#define ESP_FAIL -1
|
||||
#define ESP_INTR_FLAG_LEVEL1 1
|
||||
|
||||
typedef int i2s_port_t;
|
||||
typedef int i2s_mode_t;
|
||||
enum { I2S_NUM_0 = 0, I2S_NUM_1 = 1 };
|
||||
enum { I2S_MODE_MASTER = 0x01, I2S_MODE_TX = 0x04 };
|
||||
enum { I2S_BITS_PER_SAMPLE_16BIT = 16 };
|
||||
enum { I2S_CHANNEL_FMT_ONLY_LEFT = 0 };
|
||||
enum { I2S_COMM_FORMAT_STAND_I2S = 0x01 };
|
||||
#define I2S_PIN_NO_CHANGE (-1)
|
||||
|
||||
struct i2s_config_t {
|
||||
int mode;
|
||||
unsigned sample_rate;
|
||||
int bits_per_sample;
|
||||
int channel_format;
|
||||
int communication_format;
|
||||
int intr_alloc_flags;
|
||||
int dma_buf_count;
|
||||
int dma_buf_len;
|
||||
};
|
||||
|
||||
struct i2s_pin_config_t {
|
||||
int bck_io_num;
|
||||
int ws_io_num;
|
||||
int data_out_num;
|
||||
int data_in_num;
|
||||
};
|
||||
|
||||
inline SDL_AudioDeviceID &emuAudioDev()
|
||||
{
|
||||
static SDL_AudioDeviceID d = 0;
|
||||
return d;
|
||||
}
|
||||
|
||||
inline int i2s_driver_install(i2s_port_t, const i2s_config_t *cfg, int, void *)
|
||||
{
|
||||
SDL_AudioSpec want {}, have {};
|
||||
want.freq = (int)cfg->sample_rate;
|
||||
want.format = AUDIO_S16SYS;
|
||||
want.channels = 1;
|
||||
want.samples = 512;
|
||||
want.callback = nullptr; // SDL_QueueAudio mode
|
||||
|
||||
emuAudioDev() = SDL_OpenAudioDevice(nullptr, 0, &want, &have, 0);
|
||||
if (emuAudioDev() == 0) {
|
||||
std::printf("[emu] no audio device: %s (running silent)\n", SDL_GetError());
|
||||
return ESP_FAIL;
|
||||
}
|
||||
SDL_PauseAudioDevice(emuAudioDev(), 0);
|
||||
std::printf("[emu] audio open: %d Hz (requested %u)\n", have.freq, cfg->sample_rate);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
inline int i2s_set_pin(i2s_port_t, const i2s_pin_config_t *) { return ESP_OK; }
|
||||
|
||||
inline int i2s_write(i2s_port_t, const void *src, size_t size, size_t *written, unsigned)
|
||||
{
|
||||
if (emuAudioDev()) SDL_QueueAudio(emuAudioDev(), src, (uint32_t)size);
|
||||
if (written) *written = size;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
inline void i2s_zero_dma_buffer(i2s_port_t) {}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Framebuffer shared between the TFT_eSPI shim and the SDL2 host.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
struct SDL_Texture;
|
||||
|
||||
namespace emuGfx {
|
||||
constexpr int W = 320;
|
||||
constexpr int H = 240;
|
||||
extern uint32_t fb[W * H]; // ABGR8888 pixels
|
||||
extern SDL_Texture *tex;
|
||||
extern bool dirty;
|
||||
} // namespace emuGfx
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Emulator <-> shim shared state. Included by both the Arduino shim headers
|
||||
* and the SDL2 host (main.cpp).
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
|
||||
namespace emu {
|
||||
// GPIO levels as the game sees them via digitalRead() (1 = high / released).
|
||||
// Trackball quadrant pins 2,3,1,15 and center click pin 0 are driven by SDL
|
||||
// keyboard/mouse events in main.cpp.
|
||||
extern uint8_t pinLevels[64];
|
||||
|
||||
// GT911 touch emulation (left mouse button on the canvas)
|
||||
extern bool touchDown;
|
||||
extern int touchX;
|
||||
extern int touchY;
|
||||
|
||||
// Fake keyboard device @ 0x55 (ASCII bytes queued on keypress)
|
||||
extern std::deque<uint8_t> keyboard;
|
||||
|
||||
extern bool quitRequested;
|
||||
} // namespace emu
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* @file sound_engine.cpp
|
||||
* @brief I2S speaker rendering task (8 kHz, 16-bit, mono).
|
||||
*
|
||||
* Based on the wiring used by examples/SimpleTone:
|
||||
* BCK = GPIO7, WS = GPIO5, DOUT = GPIO6.
|
||||
*
|
||||
* Sounds are rendered strictly in queue order; layering is achieved by
|
||||
* queueing several events back to back (e.g. a rumble sweep followed by a
|
||||
* noise tail reads as one big explosion).
|
||||
*/
|
||||
#include "sound_engine.h"
|
||||
#include "utilities.h"
|
||||
#include <driver/i2s.h>
|
||||
|
||||
#define SND_SAMPLE_RATE 8000
|
||||
#define SND_I2S_PORT I2S_NUM_0
|
||||
#define SND_CHUNK 128 // samples per i2s_write call
|
||||
#define SND_FADE_MS 8 // fade in/out to avoid clicks
|
||||
|
||||
bool SoundEngine::begin()
|
||||
{
|
||||
i2s_config_t cfg = {};
|
||||
cfg.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX);
|
||||
cfg.sample_rate = SND_SAMPLE_RATE;
|
||||
cfg.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT;
|
||||
cfg.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;
|
||||
cfg.communication_format = I2S_COMM_FORMAT_STAND_I2S;
|
||||
cfg.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1;
|
||||
cfg.dma_buf_count = 8;
|
||||
cfg.dma_buf_len = 64;
|
||||
|
||||
if (i2s_driver_install(SND_I2S_PORT, &cfg, 0, NULL) != ESP_OK) {
|
||||
return false;
|
||||
}
|
||||
|
||||
i2s_pin_config_t pins = {};
|
||||
pins.bck_io_num = BOARD_I2S_BCK;
|
||||
pins.ws_io_num = BOARD_I2S_WS;
|
||||
pins.data_out_num = BOARD_I2S_DOUT;
|
||||
pins.data_in_num = I2S_PIN_NO_CHANGE;
|
||||
i2s_set_pin(SND_I2S_PORT, &pins);
|
||||
|
||||
q_ = xQueueCreate(12, sizeof(SndEvent));
|
||||
if (q_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Render on core 0; the game loop runs on core 1.
|
||||
return xTaskCreatePinnedToCore(trampoline, "sound", 4096, this, 5, nullptr, 0) == pdTRUE;
|
||||
}
|
||||
|
||||
void SoundEngine::play(const SndEvent &e)
|
||||
{
|
||||
if (q_) {
|
||||
xQueueSend(q_, &e, 0); // drop instead of blocking the game
|
||||
}
|
||||
}
|
||||
|
||||
void SoundEngine::trampoline(void *arg)
|
||||
{
|
||||
static_cast<SoundEngine *>(arg)->task();
|
||||
}
|
||||
|
||||
void SoundEngine::task()
|
||||
{
|
||||
for (;;) {
|
||||
SndEvent e;
|
||||
xQueueReceive(q_, &e, portMAX_DELAY);
|
||||
switch (e.type) {
|
||||
case SND_TONE: renderTone(e.freq, e.dur, e.amp); break;
|
||||
case SND_SWEEP: renderSweep(e.freq, e.freq2, e.dur, e.amp); break;
|
||||
case SND_NOISE: renderNoise(e.dur, e.amp); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SoundEngine::volumeUp()
|
||||
{
|
||||
if (vol_ < VOL_MAX) vol_++;
|
||||
}
|
||||
|
||||
void SoundEngine::volumeDown()
|
||||
{
|
||||
if (vol_ > 0) vol_--;
|
||||
}
|
||||
|
||||
void SoundEngine::toggleMute()
|
||||
{
|
||||
if (vol_ > 0) {
|
||||
lastVol_ = vol_;
|
||||
vol_ = 0;
|
||||
} else {
|
||||
vol_ = lastVol_ > 0 ? lastVol_ : VOL_MAX / 2;
|
||||
}
|
||||
}
|
||||
|
||||
// scaled peak amplitude for the current volume level
|
||||
static inline uint32_t scaledAmp(uint16_t amp, uint8_t vol)
|
||||
{
|
||||
return ((uint32_t)amp * vol) / SoundEngine::VOL_MAX;
|
||||
}
|
||||
|
||||
// fade envelope over the first/last SND_FADE_MS of the whole event
|
||||
static inline uint32_t envelope(uint32_t pos, uint32_t total, uint32_t fade, uint32_t amp)
|
||||
{
|
||||
if (fade * 2 > total) fade = total / 2;
|
||||
uint32_t s = amp;
|
||||
if (pos < fade) s = s * pos / fade;
|
||||
uint32_t tail = total - pos;
|
||||
if (tail < fade) s = s * tail / fade;
|
||||
return s;
|
||||
}
|
||||
|
||||
void SoundEngine::renderTone(uint16_t freq, uint16_t durMs, uint16_t amp)
|
||||
{
|
||||
static int16_t buf[SND_CHUNK];
|
||||
|
||||
uint32_t a = scaledAmp(amp, vol_);
|
||||
if (a == 0) return;
|
||||
|
||||
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
|
||||
if (total == 0) return;
|
||||
uint32_t half = (freq > 0) ? (SND_SAMPLE_RATE / 2) / freq : 1;
|
||||
if (half == 0) half = 1;
|
||||
uint32_t fade = (uint32_t)SND_SAMPLE_RATE * SND_FADE_MS / 1000;
|
||||
if (fade < 2) fade = 2;
|
||||
|
||||
uint32_t phase = 0;
|
||||
for (uint32_t i = 0; i < total; ) {
|
||||
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
|
||||
for (uint32_t k = 0; k < n; k++) {
|
||||
int32_t s = ((phase / half) & 1) ? (int32_t)a : -(int32_t)a;
|
||||
buf[k] = (int16_t)(s * (int32_t)envelope(i + k, total, fade, 256) / 256);
|
||||
phase++;
|
||||
}
|
||||
size_t bw;
|
||||
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
|
||||
i += n;
|
||||
}
|
||||
}
|
||||
|
||||
// Square wave gliding from freq0 to freq1 (Hz) over the duration.
|
||||
// Phase is carried in a float cycle counter (0..1) so frequency changes
|
||||
// never click.
|
||||
void SoundEngine::renderSweep(uint16_t freq0, uint16_t freq1, uint16_t durMs, uint16_t amp)
|
||||
{
|
||||
static int16_t buf[SND_CHUNK];
|
||||
|
||||
uint32_t a = scaledAmp(amp, vol_);
|
||||
if (a == 0) return;
|
||||
|
||||
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
|
||||
if (total == 0) return;
|
||||
uint32_t fade = (uint32_t)SND_SAMPLE_RATE * SND_FADE_MS / 1000;
|
||||
if (fade < 2) fade = 2;
|
||||
|
||||
float phase = 0.0f;
|
||||
for (uint32_t i = 0; i < total; ) {
|
||||
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
|
||||
for (uint32_t k = 0; k < n; k++) {
|
||||
uint32_t pos = i + k;
|
||||
float f = (float)freq0 +
|
||||
((float)(int16_t)(freq1 - freq0) * (float)pos) / (float)total;
|
||||
if (f < 20.0f) f = 20.0f;
|
||||
phase += f / (float)SND_SAMPLE_RATE;
|
||||
if (phase >= 1.0f) phase -= 1.0f;
|
||||
int32_t s = (phase < 0.5f) ? (int32_t)a : -(int32_t)a;
|
||||
buf[k] = (int16_t)(s * (int32_t)envelope(pos, total, fade, 256) / 256);
|
||||
}
|
||||
size_t bw;
|
||||
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
|
||||
i += n;
|
||||
}
|
||||
}
|
||||
|
||||
void SoundEngine::renderNoise(uint16_t durMs, uint16_t amp)
|
||||
{
|
||||
static int16_t buf[SND_CHUNK];
|
||||
|
||||
uint32_t a = scaledAmp(amp, vol_);
|
||||
if (a == 0) return;
|
||||
|
||||
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
|
||||
if (total == 0) return;
|
||||
|
||||
uint32_t seed = esp_random() | 1;
|
||||
for (uint32_t i = 0; i < total; ) {
|
||||
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
|
||||
for (uint32_t k = 0; k < n; k++) {
|
||||
// xorshift32 for cheap white noise
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
int32_t signedS = (int32_t)(seed & 0xFFFF) - 32768;
|
||||
// linear decay over the burst
|
||||
int32_t s = (int32_t)(((int64_t)signedS * a * (int64_t)(total - i - k)) /
|
||||
((int64_t)32768 * (int64_t)total));
|
||||
buf[k] = (int16_t)s;
|
||||
}
|
||||
size_t bw;
|
||||
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
|
||||
i += n;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* @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();
|
||||
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
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* @file utilities.h
|
||||
* @author Lewis He (lewishe@outlook.com)
|
||||
* @license MIT
|
||||
* @copyright Copyright (c) 2023 Shenzhen Xin Yuan Electronic Technology Co., Ltd
|
||||
* @date 2023-04-11
|
||||
*
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
|
||||
|
||||
//! The board peripheral power control pin needs to be set to HIGH when using the peripheral
|
||||
#define BOARD_POWERON 10
|
||||
|
||||
#define BOARD_I2S_WS 5
|
||||
#define BOARD_I2S_BCK 7
|
||||
#define BOARD_I2S_DOUT 6
|
||||
|
||||
#define BOARD_I2C_SDA 18
|
||||
#define BOARD_I2C_SCL 8
|
||||
|
||||
#define BOARD_BAT_ADC 4
|
||||
|
||||
#define BOARD_TOUCH_INT 16
|
||||
#define BOARD_KEYBOARD_INT 46
|
||||
|
||||
#define BOARD_SDCARD_CS 39
|
||||
#define BOARD_TFT_CS 12
|
||||
#define RADIO_CS_PIN 9
|
||||
|
||||
#define BOARD_TFT_DC 11
|
||||
#define BOARD_TFT_BACKLIGHT 42
|
||||
|
||||
#define BOARD_SPI_MOSI 41
|
||||
#define BOARD_SPI_MISO 38
|
||||
#define BOARD_SPI_SCK 40
|
||||
|
||||
#define BOARD_TBOX_G02 2
|
||||
#define BOARD_TBOX_G01 3
|
||||
#define BOARD_TBOX_G04 1
|
||||
#define BOARD_TBOX_G03 15
|
||||
|
||||
#define BOARD_ES7210_MCLK 48
|
||||
#define BOARD_ES7210_LRCK 21
|
||||
#define BOARD_ES7210_SCK 47
|
||||
#define BOARD_ES7210_DIN 14
|
||||
|
||||
#define RADIO_BUSY_PIN 13
|
||||
#define RADIO_RST_PIN 17
|
||||
#define RADIO_DIO1_PIN 45
|
||||
|
||||
#define BOARD_BOOT_PIN 0
|
||||
|
||||
#define BOARD_BL_PIN 42
|
||||
|
||||
|
||||
#define BOARD_GPS_TX_PIN 43
|
||||
#define BOARD_GPS_RX_PIN 44
|
||||
|
||||
|
||||
#ifndef RADIO_FREQ
|
||||
#define RADIO_FREQ 868.0
|
||||
#endif
|
||||
|
||||
#ifndef RADIO_BANDWIDTH
|
||||
#define RADIO_BANDWIDTH 125.0
|
||||
#endif
|
||||
|
||||
#ifndef RADIO_SF
|
||||
#define RADIO_SF 10
|
||||
#endif
|
||||
|
||||
#ifndef RADIO_CR
|
||||
#define RADIO_CR 6
|
||||
#endif
|
||||
|
||||
#ifndef RADIO_TX_POWER
|
||||
#define RADIO_TX_POWER 22
|
||||
#endif
|
||||
|
||||
#define DEFAULT_OPA 100
|
||||
|
||||
|
||||
|
||||
+4
-2
@@ -22,15 +22,17 @@ default_envs = T-Deck
|
||||
|
||||
|
||||
;; Examples only one is valid
|
||||
src_dir = examples/UnitTest
|
||||
; src_dir = examples/UnitTest
|
||||
; src_dir = examples/Microphone
|
||||
; src_dir = examples/Touchpad
|
||||
; src_dir = examples/lvgl_example
|
||||
;src_dir = examples/lvgl_example
|
||||
; src_dir = examples/Keyboard_T_Deck_Master
|
||||
; src_dir = examples/GPSShield
|
||||
; src_dir = examples/LoRaWAN_Starter
|
||||
; src_dir = examples/I2SPlay
|
||||
; src_dir = examples/LvglArduinoVNC_VGA
|
||||
; src_dir = examples/SimpleTone
|
||||
src_dir = examples/MissileCommand
|
||||
|
||||
|
||||
;! Don't make changes
|
||||
|
||||
Reference in New Issue
Block a user