From d4e6b4e6bed5d709db765c9538ecd7260f2c2c83 Mon Sep 17 00:00:00 2001 From: Dejvino Date: Tue, 10 Nov 2026 22:06:36 +0100 Subject: [PATCH] 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 --- emulator/.gitignore | 1 + emulator/Makefile | 34 + emulator/src/main.cpp | 215 ++++ emulator/src/shim/Arduino.h | 181 +++ emulator/src/shim/SPI.h | 9 + emulator/src/shim/TFT_eSPI.h | 253 ++++ emulator/src/shim/TouchDrvGT911.hpp | 28 + emulator/src/shim/Wire.h | 43 + emulator/src/shim/driver/i2s.h | 75 ++ emulator/src/shim/emu_gfx.h | 15 + emulator/src/shim/emu_input.h | 24 + examples/MissileCommand/MissileCommand.ino | 1240 ++++++++++++++++++++ examples/MissileCommand/sound_engine.cpp | 205 ++++ examples/MissileCommand/sound_engine.h | 54 + examples/MissileCommand/utilities.h | 85 ++ platformio.ini | 6 +- 16 files changed, 2466 insertions(+), 2 deletions(-) create mode 100644 emulator/.gitignore create mode 100644 emulator/Makefile create mode 100644 emulator/src/main.cpp create mode 100644 emulator/src/shim/Arduino.h create mode 100644 emulator/src/shim/SPI.h create mode 100644 emulator/src/shim/TFT_eSPI.h create mode 100644 emulator/src/shim/TouchDrvGT911.hpp create mode 100644 emulator/src/shim/Wire.h create mode 100644 emulator/src/shim/driver/i2s.h create mode 100644 emulator/src/shim/emu_gfx.h create mode 100644 emulator/src/shim/emu_input.h create mode 100644 examples/MissileCommand/MissileCommand.ino create mode 100644 examples/MissileCommand/sound_engine.cpp create mode 100644 examples/MissileCommand/sound_engine.h create mode 100644 examples/MissileCommand/utilities.h diff --git a/emulator/.gitignore b/emulator/.gitignore new file mode 100644 index 0000000..8d7496d --- /dev/null +++ b/emulator/.gitignore @@ -0,0 +1 @@ +missilecommand-emu diff --git a/emulator/Makefile b/emulator/Makefile new file mode 100644 index 0000000..2c890c8 --- /dev/null +++ b/emulator/Makefile @@ -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 diff --git a/emulator/src/main.cpp b/emulator/src/main.cpp new file mode 100644 index 0000000..67c94ca --- /dev/null +++ b/emulator/src/main.cpp @@ -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 +#include +#include +#include +#include +#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 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; +} diff --git a/emulator/src/shim/Arduino.h b/emulator/src/shim/Arduino.h new file mode 100644 index 0000000..9b7bcec --- /dev/null +++ b/emulator/src/shim/Arduino.h @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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(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(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 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 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 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 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; diff --git a/emulator/src/shim/SPI.h b/emulator/src/shim/SPI.h new file mode 100644 index 0000000..3296c73 --- /dev/null +++ b/emulator/src/shim/SPI.h @@ -0,0 +1,9 @@ +#pragma once + +class SPIClass { +public: + void begin(int = -1, int = -1, int = -1) {} + void end() {} +}; + +extern SPIClass SPI; diff --git a/emulator/src/shim/TFT_eSPI.h b/emulator/src/shim/TFT_eSPI.h new file mode 100644 index 0000000..1acf4d7 --- /dev/null +++ b/emulator/src/shim/TFT_eSPI.h @@ -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 +#include +#include +#include "emu_gfx.h" +#include + +// ---- 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, 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; +}; diff --git a/emulator/src/shim/TouchDrvGT911.hpp b/emulator/src/shim/TouchDrvGT911.hpp new file mode 100644 index 0000000..92d461c --- /dev/null +++ b/emulator/src/shim/TouchDrvGT911.hpp @@ -0,0 +1,28 @@ +#pragma once +#include +#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; + } +}; diff --git a/emulator/src/shim/Wire.h b/emulator/src/shim/Wire.h new file mode 100644 index 0000000..16fc733 --- /dev/null +++ b/emulator/src/shim/Wire.h @@ -0,0 +1,43 @@ +#pragma once +#include +#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 txBuf; + std::deque rx; +}; + +extern TwoWire Wire; diff --git a/emulator/src/shim/driver/i2s.h b/emulator/src/shim/driver/i2s.h new file mode 100644 index 0000000..1851aa1 --- /dev/null +++ b/emulator/src/shim/driver/i2s.h @@ -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 +#include +#include + +#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) {} diff --git a/emulator/src/shim/emu_gfx.h b/emulator/src/shim/emu_gfx.h new file mode 100644 index 0000000..b5426dd --- /dev/null +++ b/emulator/src/shim/emu_gfx.h @@ -0,0 +1,15 @@ +/** + * Framebuffer shared between the TFT_eSPI shim and the SDL2 host. + */ +#pragma once +#include + +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 diff --git a/emulator/src/shim/emu_input.h b/emulator/src/shim/emu_input.h new file mode 100644 index 0000000..e6cc082 --- /dev/null +++ b/emulator/src/shim/emu_input.h @@ -0,0 +1,24 @@ +/** + * Emulator <-> shim shared state. Included by both the Arduino shim headers + * and the SDL2 host (main.cpp). + */ +#pragma once +#include +#include + +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 keyboard; + +extern bool quitRequested; +} // namespace emu diff --git a/examples/MissileCommand/MissileCommand.ino b/examples/MissileCommand/MissileCommand.ino new file mode 100644 index 0000000..0cb4838 --- /dev/null +++ b/examples/MissileCommand/MissileCommand.ino @@ -0,0 +1,1240 @@ +/** + * @file MissileCommand.ino + * @brief Classic Missile Command for the LilyGo T-Deck (ESP32-S3). + * + * Controls + * Trackball : move the aiming crosshair + * Trackball press : fire from the closest battery with ammo + * Screen tap : move crosshair + fire + * Keyboard A / S / D : fire from left / center / right battery + * + * Rendering: incremental drawing with TFT_eSPI (no full frame buffer). + * Missile trails are persistent lines, explosions are animated circles + * that repair the terrain underneath when they clear. + * + * Sound: I2S speaker via sound_engine (see sound_engine.cpp). Each wave + * opens with the original-style attack alarm (four falling tones), then + * layered sweeps/noise effects for launches, explosions and city hits. + */ + +#include +#include +#include +#include +#include "utilities.h" +#include "TouchDrvGT911.hpp" +#include "sound_engine.h" + +// --------------------------------------------------------------------------- +// Hardware +// --------------------------------------------------------------------------- +TFT_eSPI tft; +TouchDrvGT911 touch; +SoundEngine sound; + +static bool touchAvail = false; +static bool kbAvail = false; + +// Screen metrics (filled in during setup, rotation 1 -> 320x240) +static int scrW, scrH, groundY; + +// --------------------------------------------------------------------------- +// Tunables +// --------------------------------------------------------------------------- +static const int FRAME_MS = 33; // ~30 fps +static const int CITY_COUNT = 6; +static const int AMMO_MAX = 10; +static const int MAX_BOMBS = 20; +static const int MAX_ROCKETS = 8; +static const int MAX_EXPL = 12; +static const int CROSS_STEP = 14; // px per trackball step +static const float ROCKET_SPEED = 6.0f; // px / frame +static const float ROCKET_RADIUS = 24.0f; +static const uint32_t BANNER_MS = 1500; +static const uint32_t BONUS_MS = 3400; + +static const uint16_t EXPL_COLORS[3] = { TFT_WHITE, TFT_ORANGE, TFT_YELLOW }; + +// --------------------------------------------------------------------------- +// Entities +// --------------------------------------------------------------------------- +struct Bomb { + bool alive; + float x, y; // current tip position + float sx, sy; // origin + float tx, ty; // target + float dirx, diry; // unit direction + float speed; // px per frame + float wob; // wiggle phase (smart bombs) + bool smart; +}; + +struct Rocket { + bool alive; + float x, y; + float tx, ty; + float dirx, diry; + float speed; +}; + +struct Explosion { + bool alive; + float x, y; + float r, maxR, vel; + int hold; +}; + +static Bomb bombs[MAX_BOMBS]; +static Rocket rockets[MAX_ROCKETS]; +static Explosion expls[MAX_EXPL]; + +// --------------------------------------------------------------------------- +// Game state +// --------------------------------------------------------------------------- +enum GameState { ST_TITLE, ST_BANNER, ST_PLAYING, ST_BONUS, ST_GAMEOVER }; +static GameState gameState = ST_TITLE; +static uint32_t stateT0 = 0; +static uint32_t frameCount = 0; + +static int cityX[CITY_COUNT]; +static bool cityAlive[CITY_COUNT]; +static int BATX[3]; +static bool batAlive[3]; +static int batAmmo[3]; + +static int score = 0; +static int highScore = 0; +static int wave = 1; + +static int bombsSpawned = 0; +static int waveQuota = 0; +static float bombSpeed = 0.5f; // px per frame +static uint32_t spawnIntervalMs = 1400; +static uint32_t lastSpawnMs = 0; +static int waveKills = 0; +static bool spawningStopped = false; + +static struct { + int x, y; // current + int dx, dy; // last drawn position (erase here, NOT at px/py: several + // moves can happen per frame and would leave ghosts) + bool drawn; + bool moved; +} cross; + +static uint32_t volOSDUntil = 0; // volume bar overlay timer + +// --------------------------------------------------------------------------- +// Forward declarations +// --------------------------------------------------------------------------- +static void drawWorld(); +static void drawHUD(); +static void drawAmmoPyramid(int bat); +static void redrawGroundArea(float cx, float cy, float r); + +// --------------------------------------------------------------------------- +// Sound helpers +// --------------------------------------------------------------------------- +static void sfx(SndType t, uint16_t f0, uint16_t f1, uint16_t d, uint16_t a) +{ + SndEvent e; + e.type = t; + e.freq = f0; + e.freq2 = f1; + e.dur = d; + e.amp = a; + sound.play(e); +} + +static void sfxTone(uint16_t f, uint16_t d, uint16_t a) { sfx(SND_TONE, f, f, d, a); } +static void sfxSweep(uint16_t f0, uint16_t f1, uint16_t d, uint16_t a) { sfx(SND_SWEEP, f0, f1, d, a); } +static void sfxNoise(uint16_t d, uint16_t a) { sfx(SND_NOISE, 0, 0, d, a); } + +static void sfxDeny() { sfxTone(220, 90, 8000); } + +// Attack alarm, played once as a wave-start intro (like the original): +// four falling tones, then gameplay begins and the alarm is done. +static void sfxSirenIntro() +{ + for (int i = 0; i < 4; i++) { + sfxSweep(760 - i * 40, 330, 280, 12000); + } +} + +static void sfxFire() +{ + sfxSweep(280, 1100, 70, 8000); // rising "pew" + sfxNoise(50, 9000); // launch puff +} + +static void sfxKill() // enemy warhead destroyed +{ + sfxNoise(150, 20000); + sfxSweep(500, 120, 150, 12000); +} + +static void sfxBoom() // counter-missile explosion +{ + sfxNoise(260, 24000); + sfxSweep(200, 55, 260, 16000); // deep rumble tail +} + +static void sfxCityBoom() +{ + sfxSweep(150, 40, 420, 22000); // very deep boom + sfxNoise(380, 24000); +} + +static void sfxWaveClear() +{ + sfxTone(800, 90, 9000); + sfxTone(1000, 90, 9000); + sfxTone(1300, 140, 9000); +} + +static void sfxGameOver() +{ + sfxSweep(600, 300, 220, 12000); + sfxSweep(450, 200, 220, 12000); + sfxSweep(300, 90, 420, 14000); +} + +// --------------------------------------------------------------------------- +// Layout / terrain drawing +// --------------------------------------------------------------------------- +static void layout() +{ + BATX[0] = 18; + BATX[1] = scrW / 2; + BATX[2] = scrW - 18; + float frac[CITY_COUNT] = { 0.18f, 0.30f, 0.42f, 0.58f, 0.70f, 0.82f }; + for (int i = 0; i < CITY_COUNT; i++) { + cityX[i] = (int)(scrW * frac[i]); + } +} + +static void drawGround() +{ + tft.fillRect(0, groundY, scrW, scrH - groundY, TFT_DARKGREEN); + tft.drawFastHLine(0, groundY, scrW, TFT_GREEN); +} + +static void drawCity(int i) +{ + int x = cityX[i]; + if (cityAlive[i]) { + tft.fillRect(x - 10, groundY - 12, 7, 12, TFT_WHITE); + tft.fillRect(x - 2, groundY - 9, 5, 9, TFT_WHITE); + tft.fillRect(x + 4, groundY - 14, 6, 14, TFT_WHITE); + } else { + tft.fillRect(x - 10, groundY - 4, 20, 4, TFT_DARKGREY); + } +} + +static void drawBattery(int i) +{ + int x = BATX[i]; + if (batAlive[i]) { + tft.fillTriangle(x - 5, groundY, x + 5, groundY, x, groundY - 7, TFT_BLUE); + } else { + tft.fillRect(x - 4, groundY - 3, 9, 3, TFT_DARKGREY); + } + drawAmmoPyramid(i); +} + +// Classic pyramid of up-pointing triangles above each battery +static void drawAmmoPyramid(int bat) +{ + int x = BATX[bat]; + tft.fillRect(x - 12, groundY - 32, 25, 24, TFT_BLACK); + if (!batAlive[bat]) return; + + int n = batAmmo[bat]; + int drawn = 0; + for (int row = 0; row < 4 && drawn < n; row++) { + int count = 4 - row; // bottom row has 4 + int rowY = groundY - 9 - row * 5; // base line of this row + for (int t = 0; t < count && drawn < n; t++, drawn++) { + int cx = x - (count - 1) * 3 + t * 6; + tft.fillTriangle(cx - 2, rowY, cx + 2, rowY, cx, rowY - 4, TFT_CYAN); + } + } +} + +static void stars(int n) +{ + for (int i = 0; i < n; i++) { + int x = random(0, scrW); + int y = random(0, groundY - 50); + tft.drawPixel(x, y, random(10) < 8 ? TFT_DARKGREY : TFT_WHITE); + } +} + +static void drawWorld() +{ + tft.fillScreen(TFT_BLACK); + stars(70); + drawGround(); + for (int i = 0; i < CITY_COUNT; i++) drawCity(i); + for (int i = 0; i < 3; i++) drawBattery(i); + drawHUD(); + cross.drawn = false; +} + +// Redraw the part of the terrain that an explosion circle just erased. +static void redrawGroundArea(float cx, float cy, float r) +{ + (void)cy; // the strip is redrawn at ground level regardless of blast height + int x0 = (int)(cx - r) - 2; + int x1 = (int)(cx + r) + 2; + if (x0 < 0) x0 = 0; + if (x1 > scrW - 1) x1 = scrW - 1; + if (x1 < x0) return; + tft.fillRect(x0, groundY, x1 - x0 + 1, scrH - groundY, TFT_DARKGREEN); + tft.drawFastHLine(x0, groundY, x1 - x0 + 1, TFT_GREEN); + for (int i = 0; i < CITY_COUNT; i++) { + if (cityX[i] + 10 >= x0 && cityX[i] - 10 <= x1) drawCity(i); + } + for (int i = 0; i < 3; i++) { + if (BATX[i] + 12 >= x0 && BATX[i] - 12 <= x1) drawBattery(i); + } +} + +// --------------------------------------------------------------------------- +// HUD +// --------------------------------------------------------------------------- +static int scoreMult() +{ + int m = 1 + (wave - 1) / 2; + return m > 6 ? 6 : m; +} + +static void drawHUD() +{ + tft.fillRect(0, 0, scrW, 16, TFT_BLACK); + tft.setTextFont(2); + tft.setTextColor(TFT_WHITE, TFT_BLACK); + tft.setTextDatum(TL_DATUM); + tft.drawString("WAVE " + String(wave), 4, 2); + tft.setTextDatum(TC_DATUM); + tft.drawString(String(score), scrW / 2, 2); + tft.setTextDatum(TR_DATUM); + tft.drawString("x" + String(scoreMult()) + " HI " + String(highScore), scrW - 4, 2); + tft.setTextDatum(MC_DATUM); +} + +// Brief volume bar shown after U / V / M keypresses +static void drawVolumeOSD() +{ + static bool shown = false; + bool want = millis() < volOSDUntil; + int bx = scrW - 108, by = 20; + if (want) { + shown = true; + tft.fillRect(bx, by, 104, 14, TFT_BLACK); + tft.drawRect(bx, by, 104, 14, TFT_DARKGREY); + int vol = sound.volume(); + if (vol == 0) { + tft.setTextFont(2); + tft.setTextColor(TFT_RED, TFT_BLACK); + tft.setTextDatum(MC_DATUM); + tft.drawString("MUTE", bx + 52, by + 7); + } else { + for (int i = 0; i < SoundEngine::VOL_MAX; i++) { + if (i < vol) { + tft.fillRect(bx + 3 + i * 12, by + 3, 9, 8, TFT_GREEN); + } + } + } + } else if (shown) { + shown = false; + tft.fillRect(bx - 2, by - 2, 108, 18, TFT_BLACK); + } +} + +// --------------------------------------------------------------------------- +// Crosshair +// --------------------------------------------------------------------------- +static void drawCrossAt(int x, int y, uint16_t c) +{ + tft.drawFastHLine(x - 5, y, 4, c); + tft.drawFastHLine(x + 1, y, 4, c); + tft.drawFastVLine(x, y - 5, 4, c); + tft.drawFastVLine(x, y + 1, 4, c); +} + +static void renderCross() +{ + if (!cross.drawn || cross.moved) { + if (cross.drawn) drawCrossAt(cross.dx, cross.dy, TFT_BLACK); + drawCrossAt(cross.x, cross.y, TFT_GREEN); + cross.dx = cross.x; + cross.dy = cross.y; + cross.drawn = true; + cross.moved = false; + } +} + +static void clampCross() +{ + if (cross.x < 2) cross.x = 2; + if (cross.x > scrW - 3) cross.x = scrW - 3; + if (cross.y < 18) cross.y = 18; + if (cross.y > groundY - 3) cross.y = groundY - 3; +} + +static void moveCross(int dir) +{ + if (gameState != ST_PLAYING && gameState != ST_BANNER) return; + switch (dir) { + case 0: cross.x += CROSS_STEP; break; // right + case 1: cross.y -= CROSS_STEP; break; // up + case 2: cross.x -= CROSS_STEP; break; // left + case 3: cross.y += CROSS_STEP; break; // down + } + clampCross(); + cross.moved = true; +} + +static void setCross(int x, int y) +{ + if (gameState != ST_PLAYING && gameState != ST_BANNER) return; + cross.x = x; + cross.y = y; + clampCross(); + cross.moved = true; +} + +// --------------------------------------------------------------------------- +// Entities +// --------------------------------------------------------------------------- +static void spawnExpl(float x, float y, float maxR, float vel) +{ + for (int i = 0; i < MAX_EXPL; i++) { + if (!expls[i].alive) { + expls[i].alive = true; + expls[i].x = x; + expls[i].y = y; + expls[i].r = 0; + expls[i].maxR = maxR; + expls[i].vel = vel; + expls[i].hold = 0; + return; + } + } + // no free slot: replace the smallest one + int best = 0; + for (int i = 1; i < MAX_EXPL; i++) { + if (expls[i].r < expls[best].r) best = i; + } + expls[best].x = x; + expls[best].y = y; + expls[best].maxR = maxR; + expls[best].vel = vel; + expls[best].r = 0; + expls[best].hold = 0; +} + +static int pickTargetX() +{ + int cand[9]; + int n = 0; + for (int i = 0; i < CITY_COUNT; i++) { + if (cityAlive[i]) cand[n++] = cityX[i]; + } + for (int i = 0; i < 3; i++) { + if (batAlive[i]) cand[n++] = BATX[i]; + } + if (n == 0) return random(10, scrW - 10); + int tx = cand[random(0, n)] + random(-6, 7); + if (tx < 4) tx = 4; + if (tx > scrW - 5) tx = scrW - 5; + return tx; +} + +static void spawnBomb() +{ + for (int i = 0; i < MAX_BOMBS; i++) { + Bomb &b = bombs[i]; + if (b.alive) continue; + + b.smart = (random(100) < (wave >= 3 ? (2 + wave > 30 ? 30 : 2 + wave) : 0)); + b.sx = random(4, scrW - 4); + b.sy = 2; + b.tx = pickTargetX(); + b.ty = groundY; + float dx = b.tx - b.sx; + float dy = b.ty - b.sy; + float len = sqrtf(dx * dx + dy * dy); + b.dirx = dx / len; + b.diry = dy / len; + b.speed = bombSpeed * (b.smart ? 1.25f : 1.0f); + b.x = b.sx; + b.y = b.sy; + b.wob = random(0, 100) * 0.06f; + b.alive = true; + bombsSpawned++; + return; + } +} + +static bool anyBombAlive() +{ + for (int i = 0; i < MAX_BOMBS; i++) if (bombs[i].alive) return true; + return false; +} + +static bool anyRocketAlive() +{ + for (int i = 0; i < MAX_ROCKETS; i++) if (rockets[i].alive) return true; + return false; +} + +static bool anyExplAlive() +{ + for (int i = 0; i < MAX_EXPL; i++) if (expls[i].alive) return true; + return false; +} + +static bool waveDone() +{ + return bombsSpawned >= waveQuota && !anyBombAlive() && !anyRocketAlive() && !anyExplAlive(); +} + +// --------------------------------------------------------------------------- +// Firing +// --------------------------------------------------------------------------- +static void launch(int bat, int tx, int ty) +{ + if (!batAlive[bat] || batAmmo[bat] <= 0) { + sfxDeny(); + return; + } + for (int i = 0; i < MAX_ROCKETS; i++) { + Rocket &r = rockets[i]; + if (r.alive) continue; + batAmmo[bat]--; + drawAmmoPyramid(bat); + + r.x = BATX[bat]; + r.y = groundY - 8; + r.tx = tx; + r.ty = ty; + float dx = tx - r.x; + float dy = ty - r.y; + float len = sqrtf(dx * dx + dy * dy); + if (len < 1) len = 1; + r.dirx = dx / len; + r.diry = dy / len; + r.speed = ROCKET_SPEED; + r.alive = true; + sfxFire(); + return; + } + sfxDeny(); // no free rocket slot +} + +static void fireAuto() +{ + int best = -1; + int bestD = 1 << 30; + for (int i = 0; i < 3; i++) { + if (batAlive[i] && batAmmo[i] > 0) { + int d = abs(BATX[i] - cross.x); + if (d < bestD) { + bestD = d; + best = i; + } + } + } + if (best < 0) { + sfxDeny(); + return; + } + launch(best, cross.x, cross.y); +} + +// --------------------------------------------------------------------------- +// Trail cleanup +// --------------------------------------------------------------------------- +// Does the segment (x0,y0)-(x1,y1) pass within `rad` of (px,py)? +static bool linePassesNear(int x0, int y0, int x1, int y1, int px, int py, int rad) +{ + long dx = x1 - x0, dy = y1 - y0; + long len2 = dx * dx + dy * dy; + if (len2 == 0) { + long ddx = px - x0, ddy = py - y0; + return ddx * ddx + ddy * ddy <= (long)rad * rad; + } + long t = (long)(px - x0) * dx + (long)(py - y0) * dy; + if (t < 0) t = 0; + if (t > len2) t = len2; + int cx = x0 + (int)((long)t * dx / len2); + int cy = y0 + (int)((long)t * dy / len2); + long ddx = px - cx, ddy = py - cy; + return ddx * ddx + ddy * ddy <= (long)rad * rad; +} + +// Enemy trails persist while the bomb falls (classic look), but vanish the +// moment the bomb is destroyed or reaches the ground, like the Atari 2600. +static void eraseBombTrail(const Bomb &b) +{ + tft.drawLine((int)b.sx, (int)b.sy, (int)b.x, (int)b.y, TFT_BLACK); + tft.fillCircle((int)b.x, (int)b.y, 1, TFT_BLACK); + // repair anything the erase swept over + if (cross.drawn && linePassesNear((int)b.sx, (int)b.sy, (int)b.x, (int)b.y, + cross.dx, cross.dy, 8)) { + drawCrossAt(cross.dx, cross.dy, TFT_BLACK); // remove it now, + cross.drawn = false; // redraw next frame + } + redrawGroundArea(b.tx, (float)groundY, 14.0f); // target-end terrain + drawHUD(); // trails start inside the HUD band +} + +// --------------------------------------------------------------------------- +// Updates +// --------------------------------------------------------------------------- +static void updateRockets() +{ + for (int i = 0; i < MAX_ROCKETS; i++) { + Rocket &r = rockets[i]; + if (!r.alive) continue; + + // AA rockets have no trail (like the 2600): just a moving dot. + // Erase the previous dot, then draw the new position. + tft.fillCircle((int)r.x, (int)r.y, 2, TFT_BLACK); + + float dx = r.tx - r.x; + float dy = r.ty - r.y; + float d = sqrtf(dx * dx + dy * dy); + if (d <= r.speed) { + r.alive = false; + spawnExpl(r.tx, r.ty, ROCKET_RADIUS, 1.6f); + sfxBoom(); + } else { + r.x += r.dirx * r.speed; + r.y += r.diry * r.speed; + tft.fillCircle((int)r.x, (int)r.y, 2, TFT_CYAN); + } + } +} + +static void killCity(int i) +{ + cityAlive[i] = false; + drawCity(i); + sfxCityBoom(); +} + +static void killBattery(int i) +{ + batAlive[i] = false; + batAmmo[i] = 0; + drawBattery(i); +} + +static void updateBombs() +{ + for (int i = 0; i < MAX_BOMBS; i++) { + Bomb &b = bombs[i]; + if (!b.alive) continue; + + float edx = b.dirx; + float edy = b.diry; + if (b.smart) { // wiggle perpendicular to the flight path + b.wob += 0.55f; + float s = sinf(b.wob) * 0.4f; + edx = b.dirx - b.diry * s; + edy = b.diry + b.dirx * s; + float len = sqrtf(edx * edx + edy * edy); + edx /= len; + edy /= len; + } + + // NOTE: keep float positions between frames; truncating to int and + // storing back would make slow missiles stall (0.5 px/frame rounds + // back to the same pixel forever). + float nxf = b.x + edx * b.speed; + float nyf = b.y + edy * b.speed; + uint16_t col = b.smart ? TFT_MAGENTA : TFT_RED; + tft.drawLine((int)b.x, (int)b.y, (int)nxf, (int)nyf, col); + if ((int)nxf != (int)b.x || (int)nyf != (int)b.y) { + tft.fillCircle((int)nxf, (int)nyf, 1, col); + } + b.x = nxf; + b.y = nyf; + + // caught by an explosion? + for (int e = 0; e < MAX_EXPL; e++) { + Explosion &ex = expls[e]; + if (!ex.alive || ex.r < 2) continue; + float ddx = b.x - ex.x; + float ddy = b.y - ex.y; + if (ddx * ddx + ddy * ddy < ex.r * ex.r) { + b.alive = false; + waveKills++; + score += 25 * scoreMult(); + eraseBombTrail(b); // also refreshes the HUD with the new score + spawnExpl(b.x, b.y, 14.0f, 1.4f); + sfxKill(); + break; + } + } + if (!b.alive) continue; + + // reached the ground? + if (b.y >= b.ty) { + b.alive = false; + eraseBombTrail(b); + spawnExpl(b.tx, groundY - 4, 11.0f, 1.3f); + sfxBoom(); + } + } +} + +static void updateExpls() +{ + for (int i = 0; i < MAX_EXPL; i++) { + Explosion &e = expls[i]; + if (!e.alive) continue; + + float oldR = e.r; + if (e.hold > 0) { + e.hold--; + } else { + e.r += e.vel; + if (e.r >= e.maxR) { + e.r = e.maxR; + e.hold = 5; + e.vel = -1.6f; + } else if (e.r <= 0.5f && e.vel < 0) { + e.r = 0; + e.alive = false; + } + } + + // erase old circle and repair the terrain it covered + if (oldR > 0.5f) { + tft.fillCircle((int)e.x, (int)e.y, (int)oldR, TFT_BLACK); + redrawGroundArea(e.x, e.y, oldR); + // if the crosshair was inside the erased circle, remove the + // remaining arms and redraw it next frame + float cdx = cross.dx - e.x; + float cdy = cross.dy - e.y; + if (cross.drawn && cdx * cdx + cdy * cdy < (oldR + 6) * (oldR + 6)) { + drawCrossAt(cross.dx, cross.dy, TFT_BLACK); + cross.drawn = false; + } + } + + if (e.alive && e.r > 0.5f) { + // flickering fireball + tft.fillCircle((int)e.x, (int)e.y, (int)e.r, EXPL_COLORS[frameCount % 3]); + + // burn cities and batteries caught inside + for (int c = 0; c < CITY_COUNT; c++) { + if (!cityAlive[c]) continue; + float dx = cityX[c] - e.x; + float dy = (groundY - 6) - e.y; + if (dx * dx + dy * dy < e.r * e.r) killCity(c); + } + for (int b = 0; b < 3; b++) { + if (!batAlive[b]) continue; + float dx = BATX[b] - e.x; + float dy = (groundY - 4) - e.y; + if (dx * dx + dy * dy < e.r * e.r) killBattery(b); + } + } + } +} + +// --------------------------------------------------------------------------- +// Waves / game flow +// --------------------------------------------------------------------------- +static void resetGame() +{ + for (int i = 0; i < CITY_COUNT; i++) cityAlive[i] = true; + for (int i = 0; i < 3; i++) { + batAlive[i] = true; + batAmmo[i] = AMMO_MAX; + } + for (int i = 0; i < MAX_BOMBS; i++) bombs[i].alive = false; + for (int i = 0; i < MAX_ROCKETS; i++) rockets[i].alive = false; + for (int i = 0; i < MAX_EXPL; i++) expls[i].alive = false; + score = 0; + wave = 0; + cross.x = cross.dx = scrW / 2; + cross.y = cross.dy = scrH / 2; +} + +static void startWave(int n) +{ + wave = n; + for (int i = 0; i < 3; i++) { + if (batAlive[i]) batAmmo[i] = AMMO_MAX; + } + // every third wave one destroyed city is rebuilt + if (n > 1 && (n - 1) % 3 == 0) { + for (int i = 0; i < CITY_COUNT; i++) { + if (!cityAlive[i]) { + cityAlive[i] = true; + break; + } + } + } + waveQuota = 8 + 2 * n; + if (waveQuota > 24) waveQuota = 24; + bombSpeed = 0.5f + 0.12f * (n - 1); + if (bombSpeed > 2.4f) bombSpeed = 2.4f; + spawnIntervalMs = 1400 - 70 * n; + if (spawnIntervalMs < 500) spawnIntervalMs = 500; + bombsSpawned = 0; + waveKills = 0; + spawningStopped = false; + lastSpawnMs = millis(); + + drawWorld(); + + tft.setFreeFont(&FreeSansBold18pt7b); + tft.setTextColor(TFT_YELLOW, TFT_BLACK); + tft.setTextDatum(MC_DATUM); + tft.drawString("WAVE " + String(n), scrW / 2, 70); + tft.setTextFont(2); + + cross.drawn = false; + gameState = ST_BANNER; + stateT0 = millis(); + + // Attack alarm: four falling tones as a wave-start intro, like the + // original. By the time it ends, the banner clears and gameplay begins. + sfxSirenIntro(); +} + +static void eraseBanner() +{ + tft.fillRect(0, 50, scrW, 40, TFT_BLACK); + stars(12); + cross.drawn = false; +} + +static void enterBonus() +{ + sfxWaveClear(); + + int aliveCities = 0; + for (int i = 0; i < CITY_COUNT; i++) if (cityAlive[i]) aliveCities++; + + int ammoLeft = 0; + for (int i = 0; i < 3; i++) ammoLeft += batAmmo[i]; + + int mult = scoreMult(); + int cityPts = aliveCities * 100 * mult; + int ammoPts = ammoLeft * 5 * mult; + score += cityPts + ammoPts; + if (score > highScore) highScore = score; + + int px = 60, pw = scrW - 120, py = 64, ph = 108; + tft.fillRect(px, py, pw, ph, TFT_BLACK); + tft.drawRect(px, py, pw, ph, TFT_WHITE); + + tft.setTextFont(2); + tft.setTextColor(TFT_YELLOW, TFT_BLACK); + tft.setTextDatum(MC_DATUM); + tft.drawString("WAVE " + String(wave) + " CLEARED", scrW / 2, py + 12); + tft.setTextColor(TFT_WHITE, TFT_BLACK); + tft.drawString("MISSILES " + String(waveKills) + " x " + String(25 * mult), scrW / 2, py + 34); + tft.drawString("CITIES " + String(aliveCities) + " x " + String(100 * mult), scrW / 2, py + 52); + tft.drawString("AMMO " + String(ammoLeft) + " x " + String(5 * mult), scrW / 2, py + 70); + tft.setTextColor(TFT_GOLD, TFT_BLACK); + tft.drawString("SCORE " + String(score), scrW / 2, py + 90); + + gameState = ST_BONUS; + stateT0 = millis(); +} + +static void enterGameOver() +{ + sfxGameOver(); + if (score > highScore) highScore = score; + + tft.fillScreen(TFT_BLACK); + stars(40); + tft.setFreeFont(&FreeSansBold24pt7b); + tft.setTextColor(TFT_RED, TFT_BLACK); + tft.setTextDatum(MC_DATUM); + tft.drawString("THE END", scrW / 2, 80); + tft.setTextFont(2); + tft.setTextColor(TFT_WHITE, TFT_BLACK); + tft.drawString("FINAL SCORE " + String(score), scrW / 2, 130); + tft.setTextColor(TFT_GOLD, TFT_BLACK); + tft.drawString("HIGH SCORE " + String(highScore), scrW / 2, 152); + tft.setTextColor(TFT_DARKGREY, TFT_BLACK); + tft.drawString("press to continue", scrW / 2, 186); + + gameState = ST_GAMEOVER; + stateT0 = millis(); +} + +static void drawTitle() +{ + tft.fillScreen(TFT_BLACK); + stars(70); + drawGround(); + for (int i = 0; i < CITY_COUNT; i++) { + cityAlive[i] = true; + drawCity(i); + } + for (int i = 0; i < 3; i++) { + batAlive[i] = true; + batAmmo[i] = AMMO_MAX; + drawBattery(i); + } + + tft.setTextDatum(MC_DATUM); + tft.setFreeFont(&FreeSansBold24pt7b); + tft.setTextColor(TFT_RED, TFT_BLACK); + tft.drawString("MISSILE", scrW / 2, 55); + tft.setTextColor(TFT_CYAN, TFT_BLACK); + tft.drawString("COMMAND", scrW / 2, 95); + + tft.setTextFont(2); + tft.setTextColor(TFT_WHITE, TFT_BLACK); + tft.drawString("Trackball: aim press / tap: fire", scrW / 2, 136); + tft.drawString("A / S / D: battery U / V / M: volume", scrW / 2, 154); + tft.setTextColor(TFT_GOLD, TFT_BLACK); + if (highScore > 0) tft.drawString("HIGH " + String(highScore), scrW / 2, 178); + + gameState = ST_TITLE; + stateT0 = millis(); +} + +// --------------------------------------------------------------------------- +// Input +// --------------------------------------------------------------------------- +static void pollTrackball() +{ + // Quadrant pins + center click, per UnitTest's mouse mapping: + // G02 -> right, G01 -> up, G04 -> left, G03 -> down, BOOT -> click + static const uint8_t tbPins[5] = { + BOARD_TBOX_G02, BOARD_TBOX_G01, BOARD_TBOX_G04, BOARD_TBOX_G03, BOARD_BOOT_PIN + }; + static bool last[5]; + bool cur[5]; + for (int i = 0; i < 5; i++) { + cur[i] = digitalRead(tbPins[i]); + } + + for (int i = 0; i < 4; i++) { + if (cur[i] != last[i]) moveCross(i); + } + + bool pressed = (!cur[4] && last[4]); // falling edge = click + for (int i = 0; i < 5; i++) last[i] = cur[i]; + + if (!pressed) return; + + switch (gameState) { + case ST_TITLE: + resetGame(); + startWave(1); + break; + case ST_BONUS: + startWave(wave + 1); + break; + case ST_GAMEOVER: + drawTitle(); + break; + case ST_PLAYING: + fireAuto(); + break; + default: + break; + } +} + +static void pollTouch() +{ + if (!touchAvail) return; + static bool wasDown = false; + bool down = touch.isPressed(); + if (!down) { + wasDown = false; + return; + } + if (wasDown) return; // only act on new taps + int16_t x[1], y[1]; + if (touch.getPoint(x, y, 1) > 0) { + wasDown = true; + switch (gameState) { + case ST_TITLE: + resetGame(); + startWave(1); + break; + case ST_BONUS: + startWave(wave + 1); + break; + case ST_GAMEOVER: + drawTitle(); + break; + case ST_PLAYING: + case ST_BANNER: + setCross(x[0], y[0]); + fireAuto(); + break; + default: + break; + } + } +} + +static void pollKeyboard() +{ + static char lastKey = 0; + Wire.requestFrom((uint8_t)0x55, (uint8_t)1); + if (Wire.available() == 0) { + lastKey = 0; // idle: arm the next press (same key can repeat) + return; + } + char k = (char)Wire.read(); + if (k == 0) { + lastKey = 0; + return; + } + if (k == lastKey) return; + lastKey = k; + kbAvail = true; + + char c = tolower(k); + + // volume keys work in every state + if (c == 'u') { + sound.volumeUp(); + volOSDUntil = millis() + 1200; + return; + } + if (c == 'v') { + sound.volumeDown(); + volOSDUntil = millis() + 1200; + return; + } + if (c == 'm') { + sound.toggleMute(); + volOSDUntil = millis() + 1200; + return; + } + + switch (gameState) { + case ST_TITLE: + resetGame(); + startWave(1); + break; + case ST_BONUS: + startWave(wave + 1); + break; + case ST_GAMEOVER: + drawTitle(); + break; + case ST_PLAYING: + if (c == 'a') launch(0, cross.x, cross.y); + else if (c == 's') launch(1, cross.x, cross.y); + else if (c == 'd') launch(2, cross.x, cross.y); + else if (c == ' ') fireAuto(); + break; + default: + break; + } +} + +// --------------------------------------------------------------------------- +// Per-state loop handlers +// --------------------------------------------------------------------------- +static void loopPlaying() +{ + uint32_t now = millis(); + + if (spawningStopped) { + // no cities left: let the screen settle, then game over + if (!anyBombAlive() && !anyRocketAlive() && !anyExplAlive()) { + enterGameOver(); + return; + } + } else { + if (bombsSpawned < waveQuota && now - lastSpawnMs >= spawnIntervalMs) { + lastSpawnMs = now; + int burst = 1 + random(0, 1 + wave / 4); + while (burst-- > 0 && bombsSpawned < waveQuota) spawnBomb(); + } + } + + updateRockets(); + updateBombs(); + updateExpls(); + renderCross(); + + if (!spawningStopped) { + bool citiesLeft = false; + for (int i = 0; i < CITY_COUNT; i++) { + if (cityAlive[i]) citiesLeft = true; + } + if (!citiesLeft) spawningStopped = true; + } + + if (waveDone()) enterBonus(); +} + +static void loopTitle() +{ + // blinking start prompt + static bool shown = true; + static uint32_t lastBlink = 0; + uint32_t now = millis(); + if (now - lastBlink >= 700) { + lastBlink = now; + shown = !shown; + tft.setTextFont(2); + tft.setTextColor(shown ? TFT_WHITE : TFT_BLACK, TFT_BLACK); + tft.setTextDatum(MC_DATUM); + tft.drawString("TAP OR PRESS TO START", scrW / 2, 200); + } +} + +// --------------------------------------------------------------------------- +// Init +// --------------------------------------------------------------------------- +// LilyGo T-Deck backlight has 16 levels (0..16) +static void setBrightness(uint8_t value) +{ + static uint8_t level = 0; + static uint8_t steps = 16; + if (value == 0) { + digitalWrite(BOARD_BL_PIN, 0); + delay(3); + level = 0; + return; + } + if (level == 0) { + digitalWrite(BOARD_BL_PIN, 1); + level = steps; + delayMicroseconds(30); + } + int from = steps - level; + int to = steps - value; + int num = (steps + to - from) % steps; + for (int i = 0; i < num; i++) { + digitalWrite(BOARD_BL_PIN, 0); + digitalWrite(BOARD_BL_PIN, 1); + } + level = value; +} + +static void hardwareInit() +{ + Serial.begin(115200); + Serial.println("T-Deck Missile Command"); + + pinMode(BOARD_POWERON, OUTPUT); + digitalWrite(BOARD_POWERON, HIGH); + + // CS lines high during init + pinMode(BOARD_SDCARD_CS, OUTPUT); + pinMode(RADIO_CS_PIN, OUTPUT); + pinMode(BOARD_TFT_CS, OUTPUT); + digitalWrite(BOARD_SDCARD_CS, HIGH); + digitalWrite(RADIO_CS_PIN, HIGH); + digitalWrite(BOARD_TFT_CS, HIGH); + + pinMode(BOARD_SPI_MISO, INPUT_PULLUP); + SPI.begin(BOARD_SPI_SCK, BOARD_SPI_MISO, BOARD_SPI_MOSI); + + tft.begin(); + tft.setRotation(1); + tft.fillScreen(TFT_BLACK); + + pinMode(BOARD_BL_PIN, OUTPUT); + for (int i = 0; i <= 16; ++i) { + setBrightness(i); + delay(20); + } + + // I2C: touch + keyboard share the bus + Wire.begin(BOARD_I2C_SDA, BOARD_I2C_SCL); + + touch.setPins(-1, BOARD_TOUCH_INT); + touchAvail = touch.begin(Wire); + if (touchAvail) { + touch.setMaxCoordinates(scrW, scrH); + touch.setSwapXY(true); + touch.setMirrorXY(false, true); + Serial.println("GT911 touch ready"); + } else { + Serial.println("No GT911 touch found"); + } + + // Trackball pins (quadrants + center click) + const uint8_t tbPins[5] = { + BOARD_TBOX_G02, BOARD_TBOX_G01, BOARD_TBOX_G04, BOARD_TBOX_G03, BOARD_BOOT_PIN + }; + for (int i = 0; i < 5; i++) { + pinMode(tbPins[i], INPUT_PULLUP); + } + + randomSeed(esp_random()); +} + +void setup() +{ + hardwareInit(); + + scrW = tft.width(); + scrH = tft.height(); + groundY = scrH - 12; + layout(); + + if (!sound.begin()) { + Serial.println("Sound engine init failed (no I2S?)"); + } + + Serial.printf("Screen %dx%d, ground at %d\n", scrW, scrH, groundY); + drawTitle(); +} + +void loop() +{ + static uint32_t nextFrame = 0; + uint32_t now = millis(); + if ((int32_t)(now - nextFrame) < 0) { + delay(1); + return; + } + nextFrame = now + FRAME_MS; + frameCount++; + + pollTrackball(); + pollTouch(); + pollKeyboard(); + + switch (gameState) { + case ST_TITLE: + loopTitle(); + break; + case ST_BANNER: + if (now - stateT0 > BANNER_MS) { + eraseBanner(); + gameState = ST_PLAYING; + } + break; + case ST_PLAYING: + loopPlaying(); + break; + case ST_BONUS: + if (now - stateT0 > BONUS_MS) { + startWave(wave + 1); + } + break; + case ST_GAMEOVER: + default: + break; + } + + drawVolumeOSD(); +} diff --git a/examples/MissileCommand/sound_engine.cpp b/examples/MissileCommand/sound_engine.cpp new file mode 100644 index 0000000..fdc75e8 --- /dev/null +++ b/examples/MissileCommand/sound_engine.cpp @@ -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 + +#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(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; + } +} diff --git a/examples/MissileCommand/sound_engine.h b/examples/MissileCommand/sound_engine.h new file mode 100644 index 0000000..6afa9ae --- /dev/null +++ b/examples/MissileCommand/sound_engine.h @@ -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 + +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 +}; diff --git a/examples/MissileCommand/utilities.h b/examples/MissileCommand/utilities.h new file mode 100644 index 0000000..3ca5aa7 --- /dev/null +++ b/examples/MissileCommand/utilities.h @@ -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 + + + diff --git a/platformio.ini b/platformio.ini index 4228363..37ed0b4 100644 --- a/platformio.ini +++ b/platformio.ini @@ -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