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:
Dejvino
2026-11-10 22:06:41 +01:00
parent 9aac147a31
commit d4e6b4e6be
16 changed files with 2466 additions and 2 deletions
+1
View File
@@ -0,0 +1 @@
missilecommand-emu
+34
View File
@@ -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
+215
View File
@@ -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;
}
+181
View File
@@ -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;
+9
View File
@@ -0,0 +1,9 @@
#pragma once
class SPIClass {
public:
void begin(int = -1, int = -1, int = -1) {}
void end() {}
};
extern SPIClass SPI;
+253
View File
@@ -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;
};
+28
View File
@@ -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;
}
};
+43
View File
@@ -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;
+75
View File
@@ -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) {}
+15
View File
@@ -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
+24
View File
@@ -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