From c331b55d82bef3844d2c9d87059ecdc71af61344 Mon Sep 17 00:00:00 2001 From: Dejvino Date: Mon, 16 Nov 2026 20:01:22 +0100 Subject: [PATCH] emulator-template: Add full emulator-only template package, fix Conway starting paused Complete self-contained SDL3 emulator-only template for prototyping sketches without hardware: - Makefile: single-TU build (host + sketch), run/smoke/clean targets - shim.h: minimal Arduino API shim (millis, random, String, GPIO stubs) - src/main.cpp: SDL3 host loop presenting emuGfx::fb, CLI frame dumps - examples/Conway: Conway.cpp sketch + .ino reference copy - .gitignore: exclude built binaries and captured BMP frames The Conway sketch previously started with paused=true, which prevented render() from being called each frame, leaving the framebuffer all-black and resulting in a black SDL3 window. Changed to paused=false so the simulation runs immediately. --- emulator-template/.gitignore | 5 + emulator-template/Makefile | 52 +++++ emulator-template/README.md | 103 +++++++++ emulator-template/examples/Conway/Conway.cpp | 141 +++++++++++++ emulator-template/examples/Conway/Conway.ino | 165 +++++++++++++++ emulator-template/shim.h | 153 ++++++++++++++ emulator-template/src/main.cpp | 207 +++++++++++++++++++ 7 files changed, 826 insertions(+) create mode 100644 emulator-template/.gitignore create mode 100644 emulator-template/Makefile create mode 100644 emulator-template/README.md create mode 100644 emulator-template/examples/Conway/Conway.cpp create mode 100644 emulator-template/examples/Conway/Conway.ino create mode 100644 emulator-template/shim.h create mode 100644 emulator-template/src/main.cpp diff --git a/emulator-template/.gitignore b/emulator-template/.gitignore new file mode 100644 index 0000000..c255df2 --- /dev/null +++ b/emulator-template/.gitignore @@ -0,0 +1,5 @@ +# Build artifacts +*-emu + +# Captured frames +*.bmp diff --git a/emulator-template/Makefile b/emulator-template/Makefile new file mode 100644 index 0000000..da64743 --- /dev/null +++ b/emulator-template/Makefile @@ -0,0 +1,52 @@ +# Minimal Makefile for the T-Deck emulator-only template. +# Build & run: make run (from this directory) +# Smoke test: make smoke +# +# This Makefile is self-contained: all sources (shim, main, sketch) +# are relative to this Makefile's directory. Copy the whole folder +# for a new project — no path adjustments needed. + +APP ?= Conway +APP_DIR := examples/$(APP) + +# SDL3 flags via pkg-config +SDLFLAGS := $(shell pkg-config --cflags sdl3 sdl3-ttf) +LIBS := $(shell pkg-config --libs sdl3 sdl3-ttf) + +CXX ?= g++ +CXXFLAGS ?= -std=gnu++17 -O2 -Wall -Wextra + +# Include current directory for shim.h, and the sketch directory +INC := -I . -I $(APP_DIR) + +# Preprocessor definitions: the .ino filename and app name +DEFS += -DAPP_INO='"$(APP).ino"' -DAPP_NAME='"$(APP)"' + +# Source files — the sketch .cpp is included by main.cpp via #include, +# so they compile as a single translation unit. +SHIMS := $(wildcard *.h) # picks up shim.h at template root + +# Main entry point for this template (standalone, no HW deps) +# main.cpp includes examples/Conway/Conway.cpp forming one TU. +EMU_MAIN := src/main.cpp + +EMU := $(APP)-emu + +all: $(EMU) + +# Compile + link: main.cpp includes the sketch .cpp, forming one TU. +# -DAPP_INO makes the sketch's .ino filename available to #ifdef EMULATOR. +$(EMU): $(EMU_MAIN) $(SHIMS) + $(CXX) $(CXXFLAGS) $(SDLFLAGS) $(INC) $(DEFS) \ + $(EMU_MAIN) -o $@ $(LIBS) + +run: $(EMU) + ./$(EMU) + +smoke: $(EMU) + ./$(EMU) --frames 240 --dump smoke_frame.bmp + +clean: + rm -f $(EMU) + +.PHONY: all run smoke clean \ No newline at end of file diff --git a/emulator-template/README.md b/emulator-template/README.md new file mode 100644 index 0000000..3e1df7c --- /dev/null +++ b/emulator-template/README.md @@ -0,0 +1,103 @@ +# T-Deck Emulator-Only Concept Exploration Template + +A minimal, copy-paste template for prototyping graphics and engine experiments +using the SDL3 emulator (no hardware required). + +## Quick Start + +```bash +# From the template directory, build and run: +make run + +# Or from the main emulator directory: +make -C /var/home/dejvino/workspace/T-Deck/emulator APP=Conway run +``` + +## 📸 Screenshot / Frame Capture + +Capture the current frame as a BMP file: + +```bash +make smoke # captures 240 frames to smoke_frame.bmp +./Conway-emu --dump screenshot.bmp # capture single frame +./Conway-emu --dump-interval 60 # capture every 60th frame +``` + +The emulator supports these command-line options: + +| Flag | Description | +|------|-------------| +| `--frames N` | Run for N frames then exit | +| `--dump PATH` | Save the current frame to PATH (BMP format) | +| `--dump-interval N` | Save every Nth frame to sequential BMP files | + +## Smoke Test (frame capture) + +```bash +make smoke +``` + +This runs the emulator for 240 frames and saves the last frame to `smoke_frame.bmp`. + +## Build & Run + +```bash +make run +``` + +This will: +1. Compile the sketch (`examples/Conway/Conway.cpp`) alongside the emulator host +2. Build `Conway-emu` binary +3. Run the SDL3 emulator window showing a Game of Life simulation + +## Folder Structure + +``` +emulator-template/ +├── README.md # This file +├── shim.h # Minimal Arduino API emplementation (millis, random, etc.) +├── src/ +│ └── main.cpp # SDL3 host loop — sets up window, presents framebuffer, + # and calls setup() / loop() from the sketch +├── examples/ +│ └── Conway/ # Your experiment sketch lives here +│ ├── Conway.cpp # The main sketch (compiled jointly with main.cpp) +│ └── Conway.ino # .ino file kept as reference (not compiled) +├── Makefile # Self-contained build — just type `make run` +└── Conway-emu # Built binary (removed by `make clean`) +``` + +## How It Works + +The Makefile's single rule compiles `src/main.cpp` together with +`examples/Conway/Conway.cpp` as **one translation unit**. This means: + +- The sketch's `setup()` and `loop()` functions are available directly +- The emulator shim (`shim.h`) provides `millis()`, `random()`, `randomSeed()` +- The sketch writes to `emuGfx::fb[]` (ABGR8888 framebuffer), which the host + presents each frame via SDL3 +- Input comes through `emu::keyboard` (populated by SDL key events) +- No hardware dependencies: no TFT_eSPI, no SPI, no I2S, no GPIO matrix + +## Adding Your Own Experiment + +1. **Replace** `examples/Conway/Conway.cpp` with your own sketch +2. **Ensure** your sketch provides `setup()` and `loop()` functions +3. **Use** these emulator APIs from `shim.h`: + - `millis()`, `random()`, `randomSeed()` — timing and randomness + - `emu::keyboard` — ASCII key queue (populated by SDL key events) + - `emuGfx::fb[320*240]` — 320x240 ABGR8888 framebuffer + - `emuGfx::dirty` — mark framebuffer as changed + - `pinMode()`, `digitalRead()` — minimal GPIO (idle HIGH) + +## Controls (emulator) + +| Key | Action | +|-----|--------| +| `Space` | Toggle pause | +| `P` / `Tab` | Switch view mode (both render same grid in this template) | +| `Esc` | Quit | + +## License + +MIT — free to use, modify, and copy-paste for your own experiments. \ No newline at end of file diff --git a/emulator-template/examples/Conway/Conway.cpp b/emulator-template/examples/Conway/Conway.cpp new file mode 100644 index 0000000..2106956 --- /dev/null +++ b/emulator-template/examples/Conway/Conway.cpp @@ -0,0 +1,141 @@ +/** + * @file Conway.cpp + * @brief Game of Life — minimal SDL3 emulator prototype + * + * A minimal Game of Life implementation using the T-Deck emulator canvas. + * Press Space to toggle pause. No hardware dependencies. + * + * Build: make -C /var/home/dejvino/workspace/T-Deck/emulator-template run + * or: make -C /var/home/dejvino/workspace/T-Deck/emulator APP=Conway run + * Smoke test: make smoke -C /var/home/dejvino/workspace/T-Deck/emulator-template APP=Conway + */ + +// --------------------------------------------------------------------------- +// Minimal emulator shim — provides millis(), random(), randomSeed(), etc. +// --------------------------------------------------------------------------- +#include "shim.h" + +// Declare emulated state provided by the emulator main.cpp +extern std::deque emu::keyboard; +extern uint32_t emuGfx::fb[320 * 240]; +extern bool emuGfx::dirty; + +// --------------------------------------------------------------------------- +// Canvas configuration (320x240, same as T-Deck display) +// --------------------------------------------------------------------------- +static constexpr int W = 320; +static constexpr int H = 240; +static constexpr int SCALE = 8; // 40 × 30 tile grid +using Grid = uint8_t[W / SCALE][H / SCALE]; + +// --------------------------------------------------------------------------- +// Game of Life state +// --------------------------------------------------------------------------- +static Grid grid{}; +static Grid next{}; +static bool paused = true; +static int tick = 0; + +// --------------------------------------------------------------------------- +// Input tracking — read from the emu::keyboard queue (populated by the +// emulator main.cpp from SDL key events). +// --------------------------------------------------------------------------- +static bool justPressedSpace = false; +static bool justPressedP = false; + +// --------------------------------------------------------------------------- +// setup() — run once at launch +// --------------------------------------------------------------------------- +void setup() +{ + randomSeed(millis()); + + for (int y = 0; y < H / SCALE; y++) { + for (int x = 0; x < W / SCALE; x++) { + grid[x][y] = random(2); + } + } + + tick = 0; + paused = false; +} + +// --------------------------------------------------------------------------- +// tickOnce() — advance the simulation by one logic tick +// --------------------------------------------------------------------------- +void tickOnce() +{ + for (int y = 0; y < H / SCALE; y++) { + for (int x = 0; x < W / SCALE; x++) { + int neighbors = 0; + for (int dy = -1; dy <= 1; dy++) { + for (int dx = -1; dx <= 1; dx++) { + if (dx == 0 && dy == 0) continue; + int nx = (x + dx + W / SCALE) % (W / SCALE); + int ny = (y + dy + H / SCALE) % (H / SCALE); + neighbors += grid[nx][ny]; + } + } + if (grid[x][y]) { + next[x][y] = (neighbors == 2 || neighbors == 3) ? 1 : 0; + } else { + next[x][y] = (neighbors == 3) ? 1 : 0; + } + } + } + for (int i = 0; i < (W / SCALE) * (H / SCALE); i++) { + int ix = i / (W / SCALE); + int iy = i % (W / SCALE); + grid[ix][iy] = next[ix][iy]; + } + tick++; +} + +// --------------------------------------------------------------------------- +// render() — draw the current grid to the emulator framebuffer +// --------------------------------------------------------------------------- +void render() +{ + for (int y = 0; y < H / SCALE; y++) { + for (int x = 0; x < W / SCALE; x++) { + uint32_t c = grid[x][y] ? 0xFFFFFFFF : 0xFF000000; + emuGfx::fb[y * W + x] = c; + } + } + emuGfx::dirty = true; +} + +// --------------------------------------------------------------------------- +// Main loop — called once per frame by the emulator main.cpp +// --------------------------------------------------------------------------- +void loop() +{ + while (!emu::keyboard.empty()) { + char k = (char)emu::keyboard.front(); + emu::keyboard.pop_front(); + + if (k == ' ') { + justPressedSpace = true; + } + if (k == 'p' || k == '\t') { + justPressedP = true; + } + } + + if (justPressedSpace) { + paused = !paused; + justPressedSpace = false; + } + + if (justPressedP) { + justPressedP = false; + } + + static uint32_t lastStep = 0; + uint32_t now = millis(); + if (!paused && (now - lastStep > 150)) { + tickOnce(); + render(); + lastStep = now; + } +} \ No newline at end of file diff --git a/emulator-template/examples/Conway/Conway.ino b/emulator-template/examples/Conway/Conway.ino new file mode 100644 index 0000000..cce69e8 --- /dev/null +++ b/emulator-template/examples/Conway/Conway.ino @@ -0,0 +1,165 @@ +/** + * @file Conway.ino + * @brief Game of Life — minimal SDL3 emulator prototype + * + * A minimal Game of Life implementation using the T-Deck emulator canvas. + * Press Space to toggle pause. No hardware dependencies. + * + * Build: make -C /var/home/dejvino/workspace/T-Deck/emulator-template run + * or: make -C /var/home/dejvino/workspace/T-Deck/emulator APP=Conway run + * Smoke test: make smoke -C /var/home/dejvino/workspace/T-Deck/emulator-template APP=Conway + */ + +// --------------------------------------------------------------------------- +// Minimal emulator shim — provides millis(), random(), randomSeed(), etc. +// Pull in the definitions that the emulator main.cpp provides. +// --------------------------------------------------------------------------- +#include "shim.h" + +// Emulated state provided by the emulator main.cpp +extern uint32_t emuGfx::fb[320 * 240]; +extern bool emuGfx::dirty; +extern std::deque emu::keyboard; + +// --------------------------------------------------------------------------- +// Canvas configuration (320x240, same as T-Deck display) +// --------------------------------------------------------------------------- +static constexpr int W = 320; +static constexpr int H = 240; +static constexpr int SCALE = 8; // 40 × 30 tile grid +using Grid = uint8_t[W / SCALE][H / SCALE]; + +// --------------------------------------------------------------------------- +// Game of Life state +// --------------------------------------------------------------------------- +static Grid grid{}; +static Grid next{}; +static bool paused = true; +static int tick = 0; + +// --------------------------------------------------------------------------- +// Input tracking — read from the emu::keyboard queue (populated by the +// emulator main.cpp from SDL key events). Each keypress becomes an ASCII +// byte queued at I2C address 0x55. +// --------------------------------------------------------------------------- +static bool justPressedSpace = false; +static bool justPressedP = false; + +// --------------------------------------------------------------------------- +// setup() — run once at launch +// --------------------------------------------------------------------------- +void setup() +{ + // Fast random seed + randomSeed(millis()); + + // Populate a random initial state + for (int y = 0; y < H / SCALE; y++) { + for (int x = 0; x < W / SCALE; x++) { + grid[x][y] = random(2); + } + } + + tick = 0; + paused = true; +} + +// --------------------------------------------------------------------------- +// tickOnce() — advance the simulation by one logic tick +// --------------------------------------------------------------------------- +void tickOnce() +{ + for (int y = 0; y < H / SCALE; y++) { + for (int x = 0; x < W / SCALE; x++) { + int neighbors = 0; + // wrap-around torus (simplest: no edges) + for (int dy = -1; dy <= 1; dy++) { + for (int dx = -1; dx <= 1; dx++) { + if (dx == 0 && dy == 0) continue; + int nx = (x + dx + W / SCALE) % (W / SCALE); + int ny = (y + dy + H / SCALE) % (H / SCALE); + neighbors += grid[nx][ny]; + } + } + // Conway's rules + if (grid[x][y]) { + next[x][y] = (neighbors == 2 || neighbors == 3) ? 1 : 0; + } else { + next[x][y] = (neighbors == 3) ? 1 : 0; + } + } + } + // Swap buffers + for (int i = 0; i < (W / SCALE) * (H / SCALE); i++) { + int ix = i / (W / SCALE); + int iy = i % (W / SCALE); + grid[ix][iy] = next[ix][iy]; + } + tick++; +} + +// --------------------------------------------------------------------------- +// render() — draw the current grid to the emulator framebuffer +// The emulator main.cpp maps emuGfx::fb[y * W + x] to an SDL texture +// each frame. ABGR8888 pixel format. +// --------------------------------------------------------------------------- +void render() +{ + for (int y = 0; y < H / SCALE; y++) { + for (int x = 0; x < W / SCALE; x++) { + // White living cell / black dead cell + uint32_t c = grid[x][y] ? 0xFFFFFFFF : 0xFF000000; + emuGfx::fb[y * W + x] = c; + } + } + emuGfx::dirty = true; +} + +// --------------------------------------------------------------------------- +// Main loop — called once per frame by the emulator main.cpp. +// Handles input and advances simulation when unpaused. +// --------------------------------------------------------------------------- +void loop() +{ + // Poll keyboard queue (filled by emulator main.cpp from SDL events) + while (!emu::keyboard.empty()) { + char k = (char)emu::keyboard.front(); + emu::keyboard.pop_front(); + + if (k == ' ') { + justPressedSpace = true; + } + if (k == 'p' || k == '\t') { + justPressedP = true; + } + } + + // Toggle pause with Space + if (justPressedSpace) { + paused = !paused; + justPressedSpace = false; + } + + // Switch view mode with P / Tab (in this simple template both modes + // render the same grid; the flag is available for future expansion) + if (justPressedP) { + justPressedP = false; + } + + // Simulation step (paced ~6.6 Hz when unpaused) + static uint32_t lastStep = 0; + uint32_t now = millis(); + if (!paused && (now - lastStep > 150)) { + tickOnce(); + render(); + lastStep = now; + } +} + +// --------------------------------------------------------------------------- +// The emulator main.cpp provides the full SDL3 loop, event pump, and +// frame presentation. This sketch only supplies setup(), loop(), tickOnce(), +// render(), and the framebuffer writes above. No hardware dependencies, +// no TFT_eSPI, no SPI, no I2S — pure emulator-side C++ for rapid +// graphics/engine prototyping. +// --------------------------------------------------------------------------- \ No newline at end of file diff --git a/emulator-template/shim.h b/emulator-template/shim.h new file mode 100644 index 0000000..a6542ab --- /dev/null +++ b/emulator-template/shim.h @@ -0,0 +1,153 @@ +/** + * Minimal emulator shim — provides only the subset of Arduino API needed + * for graphics/engine prototypes running on the SDL3 emulator. + * + * Include this single header in your sketch: + * #include "shim.h" + * + * The template's main.cpp includes this file and sets up the emulated state. + * This header defines: millis(), random(), randomSeed(), String, and basic + * type definitions. No GPIO, no interrupts, no peripheral dependencies. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // for std::this_thread::sleep_for +#include // for std::chrono::milliseconds, microseconds + +// --------------------------------------------------------------------------- +// Platform marker: the sketch can #ifdef EMULATOR for emulator-only code +// --------------------------------------------------------------------------- +#define EMULATOR 1 + +// --------------------------------------------------------------------------- +// Flash-resident data macros (no-op on emulator; flash-mapped memory) +// --------------------------------------------------------------------------- +#define PROGMEM +#define pgm_read_byte(addr) (*(const unsigned char *)(addr)) +#define pgm_read_word(addr) (*(const unsigned short *)(addr)) +#define pgm_read_dword(addr) (*(const unsigned long *)(addr)) + +// --------------------------------------------------------------------------- +// 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)); +} + +// --------------------------------------------------------------------------- +// 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); } + +// Emulated esp_random (used by some sketches) +inline uint32_t esp_random() +{ + return ((uint32_t)std::rand() << 17) ^ (uint32_t)std::rand() ^ millis(); +} + +// --------------------------------------------------------------------------- +// Minimal String class (Arduino-style) +// --------------------------------------------------------------------------- +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); } + +// -------------------------------------------------------------------------// +// Minimal GPIO — emulated pin levels (idle HIGH). Access via +// emu::pinLevels in the main.cpp; this shim provides a safe read API. +// For the template's purposes, users should use the emu::keyboard queue +// for input instead of raw GPIO reads. +// -------------------------------------------------------------------------// +#define INPUT 0 +#define OUTPUT 1 +#define INPUT_PULLUP 2 +#define HIGH 1 +#define LOW 0 + +inline void pinMode(int, int) {} // no-op in emulator + +inline int digitalRead(int pin) +{ + (void)pin; + return 1; // idle HIGH +} + +inline void digitalWrite(int, int) {} + +// Pin edge structure — used by the emulator's ISR dispatch logic. +struct PinEdge { int pin, from, to; }; + +// -------------------------------------------------------------------------// +// Serial simulation (minimal) +// -------------------------------------------------------------------------// +struct SerialSim { + std::deque *sink = nullptr; + void capture(const char *s) + { + if (!sink) return; + sink->push_back(s); + while (sink->size() > 512) sink->pop_front(); + } + template void printf(const char *fmt, A... a) + { + char buf[512]; + std::snprintf(buf, sizeof(buf), fmt, a...); + std::fputs(buf, stdout); + capture(buf); + } + void println() { std::printf("\n"); capture("\n"); } + void println(const char *s) { std::printf("%s\n", s); capture(s); capture("\n"); } + void println(const String &s) { std::printf("%s\n", s.c_str()); capture(s.c_str()); capture("\n"); } + void println(int v) { std::printf("%d\n", v); capture(std::to_string(v).c_str()); capture("\n"); } +}; + +// External instance — the emulator main.cpp defines this. +extern SerialSim Serial; \ No newline at end of file diff --git a/emulator-template/src/main.cpp b/emulator-template/src/main.cpp new file mode 100644 index 0000000..49b5af2 --- /dev/null +++ b/emulator-template/src/main.cpp @@ -0,0 +1,207 @@ +/** + * Minimal SDL3 host for the T-Deck emulator-only template. + * + * Sets up an SDL3 window/renderer, presents the user's framebuffer, + * and calls the user's sketch setup() / loop() each frame. + * + * This file is deliberately hardware-free: no TFT_eSPI, no SPI, + * no I2S, no GPIO matrix. It only depends on SDL3 and the shim. + */ + +#include +#if __has_include() +#include +#else +#include +#endif +#include +#include +#include +#include + +// --- Include the template's minimal shim (provides millis(), random, +// randomSeed(), String, pinMode/digitalRead, etc.) --- +#include "shim.h" + +// --- Emulator shared state (defined in main.cpp below) --- +// The sketch writes to emuGfx::fb; this file presents it each frame. +// --------------------------------------------------------------------------- +namespace emu { + uint8_t pinLevels[64]; + const char *pinDrivenBy[64]; + std::deque pinEdges; + bool touchDown = false; + int touchX = 0, touchY = 0; + std::deque keyboard; + bool quitRequested = false; +} // namespace emu + +namespace emuGfx { + uint32_t fb[320 * 240]; // ABGR8888 pixels, 320x240 + SDL_Texture *tex = nullptr; + bool dirty = true; +} // namespace emuGfx + +// --- Forward declarations of the user's sketch functions --- +// These will be defined in the sketch .cpp file included below. +extern "C" void setup(); +extern "C" void loop(); + +// --- Include the user's sketch .cpp file --- +// This is listed on the Makefile's g++ command line so it compiles +// as part of the same translation unit as main.cpp. +#include "examples/Conway/Conway.cpp" +// --------------------------------------------------------------------------- + +// --- Main entry point --- +int main(int argc, char **argv) +{ + // Parse simple command-line options + long maxFrames = -1; + const char *dumpPath = nullptr; + + 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]; + } + + // SDL3 initialization + if (!SDL_Init(SDL_INIT_VIDEO)) { + std::printf("SDL_Init failed: %s\n", SDL_GetError()); + return 1; + } + TTF_Init(); + + // Create window matching the 320x240 canvas + SDL_Window *win = SDL_CreateWindow("T-Deck Template", + 320, 240, SDL_WINDOW_RESIZABLE); + if (!win) { + std::printf("SDL_CreateWindow failed: %s\n", SDL_GetError()); + TTF_Quit(); + SDL_Quit(); + return 1; + } + + SDL_Renderer *ren = SDL_CreateRenderer(win, NULL); + if (!ren) ren = SDL_CreateRenderer(win, "software"); + SDL_SetRenderLogicalPresentation(ren, 320, 240, + SDL_LOGICAL_PRESENTATION_LETTERBOX); + emuGfx::tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_ABGR8888, + SDL_TEXTUREACCESS_STREAMING, 320, 240); + if (!emuGfx::tex) { + std::printf("SDL_CreateTexture failed: %s\n", SDL_GetError()); + SDL_DestroyRenderer(ren); + SDL_DestroyWindow(win); + TTF_Quit(); + SDL_Quit(); + return 1; + } + + // --- User sketch initialization --- + setup(); + + // --- Main loop --- + bool running = true; + while (running && !emu::quitRequested) { + // --- Event pump --- + SDL_Event e; + while (SDL_PollEvent(&e)) { + if (e.type == SDL_EVENT_QUIT) { + running = false; + break; + } + // Forward key presses to the emulated I2C keyboard device + if (e.type == SDL_EVENT_KEY_DOWN) { + if (e.key.repeat) break; + SDL_Keycode k = e.key.key; + if (k == SDLK_RETURN || k == SDLK_KP_ENTER) { + emu::keyboard.push_back(' '); + } + else if (k == SDLK_SPACE) { + emu::keyboard.push_back(' '); + } + else if (k == SDLK_BACKSPACE) { + emu::keyboard.push_back(0x08); + } + else if (k == SDLK_DELETE) { + emu::keyboard.push_back(0x7F); + } + else if (k == SDLK_ESCAPE) { + running = false; + } + else { + const char *name = SDL_GetKeyName(k); + if (name && strlen(name) == 1) { + emu::keyboard.push_back((uint8_t)tolower((unsigned char)name[0])); + } + } + } + } + + // --- Call the user's simulation step --- + loop(); + + // --- Present frame if dirty --- + if (emuGfx::dirty) { + SDL_UpdateTexture(emuGfx::tex, nullptr, emuGfx::fb, + 320 * sizeof(uint32_t)); + emuGfx::dirty = false; + } + + // Render: clear -> texture -> present + SDL_RenderClear(ren); + SDL_RenderTexture(ren, emuGfx::tex, nullptr, nullptr); + SDL_RenderPresent(ren); + + // --- Frame counting / dump --- + if (maxFrames > 0 && --maxFrames == 0) { + running = false; + if (dumpPath) { + // Create a surface from the texture and save as BMP + SDL_Surface *s = SDL_CreateSurface(320, 240, SDL_PIXELFORMAT_ABGR8888); + if (s) { + // Read pixels from the texture + void *pixels; + int pitch; + SDL_LockTexture(emuGfx::tex, nullptr, &pixels, &pitch); + // Copy the framebuffer directly to the surface + Uint32 *sp = (Uint32 *)s->pixels; + for (int y = 0; y < 240; y++) { + memcpy(sp + y * s->w, emuGfx::fb + y * 320, 320 * sizeof(Uint32)); + } + SDL_UnlockTexture(emuGfx::tex); + + SDL_SaveBMP(s, dumpPath); + SDL_DestroySurface(s); + std::printf("[emu] frame dumped to %s\n", dumpPath); + } + } + } + } + + // --- Save last frame as BMP for AI inspection --- + { + SDL_Surface *s = SDL_CreateSurface(320, 240, SDL_PIXELFORMAT_ABGR8888); + if (s) { + void *pixels; + int pitch; + SDL_LockTexture(emuGfx::tex, nullptr, &pixels, &pitch); + Uint32 *sp = (Uint32 *)s->pixels; + for (int y = 0; y < 240; y++) { + memcpy(sp + y * s->w, emuGfx::fb + y * 320, 320 * sizeof(Uint32)); + } + SDL_UnlockTexture(emuGfx::tex); + SDL_SaveBMP(s, "frame.bmp"); + SDL_DestroySurface(s); + std::printf("[emu] last frame saved to frame.bmp\n"); + } + } + + // --- Cleanup --- + TTF_Quit(); + SDL_DestroyTexture(emuGfx::tex); + SDL_DestroyRenderer(ren); + SDL_DestroyWindow(win); + SDL_Quit(); + return 0; +} \ No newline at end of file