Add tron-demo: TRON-like scanlines pseudo-3D room
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
# Build artifacts
|
||||
*-emu
|
||||
|
||||
# Captured frames
|
||||
*.bmp
|
||||
@@ -0,0 +1,57 @@
|
||||
# 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.
|
||||
#
|
||||
# The sketch lives in examples/$(APP)/$(APP).cpp and provides setup()/loop().
|
||||
# Default is the bundled sample demo; replace it to make your own.
|
||||
|
||||
APP ?= TronRoom
|
||||
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: app name, .ino filename, and the sketch source
|
||||
# path. main.cpp does `#include APP_SRC`, so switching APP is enough.
|
||||
DEFS += -DAPP_INO='"$(APP).ino"' -DAPP_NAME='"$(APP)"' \
|
||||
-DAPP_SRC='"$(APP_DIR)/$(APP).cpp"'
|
||||
|
||||
# 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/$(APP)/$(APP).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
|
||||
@@ -0,0 +1,87 @@
|
||||
# T-Deck Emulator-Only Template
|
||||
|
||||
A minimal, self-contained SDL3 emulator template for prototyping 320x240
|
||||
graphics/engine experiments without any hardware. No TFT_eSPI, no SPI,
|
||||
no I2S, no GPIO — just SDL3 and a framebuffer.
|
||||
|
||||
## Creating a new demo (the only thing you need to do)
|
||||
|
||||
1. Copy this whole folder and give it your demo's name.
|
||||
2. Replace `examples/Demo/Demo.cpp` with your own sketch (keep the file
|
||||
and folder name `Demo`, or rename both and pass `APP=YourName` to make).
|
||||
3. Your sketch must provide `setup()` and `loop()` and may use:
|
||||
- `millis()`, `delay()`, `random()`, `randomSeed()` — timing/randomness
|
||||
- `emuGfx::fb[320*240]` — 320x240 ABGR8888 framebuffer (`uint32_t` pixels)
|
||||
- `emuGfx::dirty = true` — set this every frame you want presented
|
||||
- `emu::keyboard` — ASCII key queue (`' '`, `'a'`…, `0x08` backspace)
|
||||
- `pinMode()`/`digitalRead()` — stubs, idle HIGH
|
||||
|
||||
That is the whole contract. The bundled `Demo.cpp` shows it with a
|
||||
bouncing box — use it as a starting skeleton or delete everything in it.
|
||||
|
||||
**Do not** edit `src/main.cpp`, `shim.h`, or the Makefile — they are the
|
||||
host and are app-agnostic. Do not leave references to the bundled demo
|
||||
in your sketch.
|
||||
|
||||
## Build & Run
|
||||
|
||||
```bash
|
||||
make run # builds examples/$(APP)/$(APP).cpp and opens a window
|
||||
make run APP=MyDemo # build a differently-named sketch in examples/MyDemo/
|
||||
make smoke # headless: 240 frames, dumps smoke_frame.bmp
|
||||
make clean # removes the built binary
|
||||
```
|
||||
|
||||
## Safety hatch
|
||||
|
||||
By default the emulator **exits automatically after 10 seconds** so a
|
||||
runaway demo can never hang around and eat resources. Flags:
|
||||
|
||||
```bash
|
||||
./Demo-emu --user-run # run indefinitely (interactive play)
|
||||
./Demo-emu --timeout 30000 # different auto-exit time (ms)
|
||||
./Demo-emu --frames 600 # exit after N frames instead
|
||||
```
|
||||
|
||||
## Frame capture
|
||||
|
||||
```bash
|
||||
make smoke # 240 frames -> smoke_frame.bmp
|
||||
./Demo-emu --dump shot.bmp # dump the last frame to a BMP
|
||||
```
|
||||
|
||||
## CLI options
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--user-run` | Disable the 10 s auto-exit (interactive use) |
|
||||
| `--timeout MS` | Auto-exit after MS milliseconds (default 10000) |
|
||||
| `--frames N` | Exit after N frames (overrides the timeout) |
|
||||
| `--dump PATH` | Save the last frame to PATH (BMP) |
|
||||
|
||||
## Folder Structure
|
||||
|
||||
```
|
||||
emulator-template/
|
||||
├── README.md # This file
|
||||
├── shim.h # Minimal Arduino API shim (millis, random, String…)
|
||||
├── src/
|
||||
│ └── main.cpp # SDL3 host loop — window, framebuffer, setup()/loop()
|
||||
├── examples/
|
||||
│ └── Demo/
|
||||
│ └── Demo.cpp # ← your sketch goes here
|
||||
├── Makefile # Self-contained build — just `make run`
|
||||
└── .gitignore # ignores built binaries and captured frames
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
The Makefile's single rule compiles `src/main.cpp` together with
|
||||
`examples/$(APP)/$(APP).cpp` as **one translation unit** (the Makefile
|
||||
passes the path as `-DAPP_SRC=…`, which main.cpp `#include`s). The sketch's
|
||||
`setup()`/`loop()` are called directly; each frame it writes pixels into
|
||||
`emuGfx::fb[]`, and the host presents the framebuffer via SDL3.
|
||||
|
||||
## License
|
||||
|
||||
MIT — free to use, modify, and copy-paste for your own experiments.
|
||||
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* TronRoom — TRON-like scanlines pseudo-3D render of a room
|
||||
* with blocks and entities.
|
||||
*
|
||||
* Target: T-Deck emulator (320x240, ABGR8888 framebuffer).
|
||||
*
|
||||
* Contract with the emulator host (src/main.cpp):
|
||||
* - implement setup() — called once at launch
|
||||
* - implement loop() — called once per frame (host paces at ~60 fps)
|
||||
* - write pixels into emuGfx::fb[] (320x240, ABGR8888 uint32)
|
||||
* - set emuGfx::dirty = true each frame you want presented
|
||||
* - read keys from emu::keyboard (ASCII queue, filled from SDL events)
|
||||
*
|
||||
* All motion is delta-time based (units per second scaled by dt), so the
|
||||
* speed is the same no matter what fps the host actually runs at.
|
||||
*/
|
||||
|
||||
#include "shim.h"
|
||||
|
||||
extern uint32_t emuGfx::fb[320 * 240];
|
||||
extern bool emuGfx::dirty;
|
||||
extern std::deque<uint8_t> emu::keyboard;
|
||||
|
||||
static constexpr int W = 320;
|
||||
static constexpr int H = 240;
|
||||
static constexpr int HORIZON = 70;
|
||||
static constexpr float K = 170.0f; // perspective constant (camera height * focal)
|
||||
static constexpr float FX = 140.0f; // horizontal focal
|
||||
static constexpr float WALL_X = 6.0f;
|
||||
static constexpr float CEIL_H = 2.5f;
|
||||
static constexpr float FAR_Z = 24.0f;
|
||||
static constexpr float NEAR_Z = 1.2f;
|
||||
|
||||
// --- Drawing helpers ---------------------------------------------------------
|
||||
static inline void putPixel(int x, int y, uint32_t c) {
|
||||
if (x < 0 || x >= W || y < 0 || y >= H) return;
|
||||
emuGfx::fb[y * W + x] = c;
|
||||
}
|
||||
|
||||
static void drawLine(int x0, int y0, int x1, int y1, uint32_t color) {
|
||||
int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
|
||||
int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
|
||||
int err = dx + dy, e2;
|
||||
for (;;) {
|
||||
putPixel(x0, y0, color);
|
||||
if (x0 == x1 && y0 == y1) break;
|
||||
e2 = 2 * err;
|
||||
if (e2 >= dy) { err += dy; x0 += sx; }
|
||||
if (e2 <= dx) { err += dx; y0 += sy; }
|
||||
}
|
||||
}
|
||||
|
||||
static void fillCircle(int cx, int cy, int r, uint32_t color) {
|
||||
for (int y = -r; y <= r; y++) {
|
||||
for (int x = -r; x <= r; x++) {
|
||||
if (x * x + y * y <= r * r) putPixel(cx + x, cy + y, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Project a 3D point (X,Y,Z) to screen. Y up. Returns false if behind camera.
|
||||
static bool project(float X, float Y, float Z, int &sx, int &sy) {
|
||||
if (Z < 0.5f) return false;
|
||||
sx = (int)(160.0f + X * FX / Z);
|
||||
sy = (int)(HORIZON + (K - Y * FX) / Z);
|
||||
return true;
|
||||
}
|
||||
|
||||
// --- World state ------------------------------------------------------------
|
||||
struct Block {
|
||||
float x, z; // position on floor (center)
|
||||
float size; // half-extent
|
||||
float rot; // yaw
|
||||
float rotSpeed;
|
||||
uint32_t color;
|
||||
};
|
||||
|
||||
struct Entity {
|
||||
float x, y, z;
|
||||
float vx, vy, vz;
|
||||
uint32_t color;
|
||||
int trailLen;
|
||||
};
|
||||
|
||||
static const int NUM_BLOCKS = 6;
|
||||
static Block blocks[NUM_BLOCKS];
|
||||
static const int NUM_ENTS = 5;
|
||||
static Entity ents[NUM_ENTS];
|
||||
|
||||
static float camSway = 0.0f;
|
||||
static unsigned long lastMs = 0;
|
||||
|
||||
// --- Setup ------------------------------------------------------------------
|
||||
void setup() {
|
||||
randomSeed(millis());
|
||||
for (int i = 0; i < NUM_BLOCKS; i++) {
|
||||
blocks[i].x = (random(200) / 100.0f - 1.0f) * 4.0f;
|
||||
blocks[i].z = 3.0f + (float)(i) * 3.5f + random(100) / 50.0f;
|
||||
if (blocks[i].z > FAR_Z - 2) blocks[i].z = FAR_Z - 2;
|
||||
blocks[i].size = 0.4f + random(60) / 100.0f;
|
||||
blocks[i].rot = random(628) / 100.0f;
|
||||
blocks[i].rotSpeed = (random(200) - 100) * 0.012f; // rad/s (-1.2..1.2)
|
||||
uint32_t cols[3] = { 0xFFFF00FF, 0xFFFFFF00, 0xFF00FFFF }; // magenta/yellow/cyan
|
||||
blocks[i].color = cols[i % 3];
|
||||
}
|
||||
for (int i = 0; i < NUM_ENTS; i++) {
|
||||
ents[i].x = (random(200) / 100.0f - 1.0f) * 3.0f;
|
||||
ents[i].y = 0.3f + random(80) / 100.0f;
|
||||
ents[i].z = 4.0f + random(100) / 25.0f;
|
||||
ents[i].vx = (random(200) - 100) * 0.03f; // units/s (-3..3)
|
||||
ents[i].vy = (random(100) - 50) * 0.012f; // units/s
|
||||
ents[i].vz = -0.72f - random(20) * 0.03f; // units/s toward camera
|
||||
uint32_t cols[2] = { 0xFF00FFFF, 0xFFFFFF00 };
|
||||
ents[i].color = cols[i % 2];
|
||||
ents[i].trailLen = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers to draw a cube (wireframe) ------------------------------------
|
||||
static void drawCube(float cx, float cy, float cz, float s, float rot, uint32_t color) {
|
||||
// 8 corners in local space, then rotate around Y, translate
|
||||
float c = cosf(rot), sn = sinf(rot);
|
||||
float corners[8][3] = {
|
||||
{-s,-s,-s},{s,-s,-s},{s,s,-s},{-s,s,-s},
|
||||
{-s,-s,s},{s,-s,s},{s,s,s},{-s,s,s}
|
||||
};
|
||||
int sx[8], sy[8]; bool vis[8];
|
||||
for (int i = 0; i < 8; i++) {
|
||||
float lx = corners[i][0], ly = corners[i][1], lz = corners[i][2];
|
||||
// rotate around Y
|
||||
float rx = lx * c + lz * sn;
|
||||
float rz = -lx * sn + lz * c;
|
||||
float wx = cx + rx;
|
||||
float wy = cy + ly;
|
||||
float wz = cz + rz;
|
||||
vis[i] = project(wx, wy, wz, sx[i], sy[i]);
|
||||
}
|
||||
static const int edges[12][2] = {
|
||||
{0,1},{1,2},{2,3},{3,0},
|
||||
{4,5},{5,6},{6,7},{7,4},
|
||||
{0,4},{1,5},{2,6},{3,7}
|
||||
};
|
||||
for (int e = 0; e < 12; e++) {
|
||||
int a = edges[e][0], b = edges[e][1];
|
||||
if (vis[a] && vis[b]) drawLine(sx[a], sy[a], sx[b], sy[b], color);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Loop -------------------------------------------------------------------
|
||||
void loop() {
|
||||
// Input
|
||||
while (!emu::keyboard.empty()) {
|
||||
uint8_t k = emu::keyboard.front();
|
||||
emu::keyboard.pop_front();
|
||||
if (k == 'q' || k == 0x1b) emu::quitRequested = true;
|
||||
}
|
||||
|
||||
// Delta time: seconds since the previous frame.
|
||||
unsigned long now = millis();
|
||||
float dt = lastMs ? (now - lastMs) / 1000.0f : 1.0f / 60.0f;
|
||||
lastMs = now;
|
||||
if (dt > 0.1f) dt = 0.1f; // clamp after stalls (drag, breakpoint)
|
||||
|
||||
// Update (all speeds are in units per second)
|
||||
camSway += 0.09f * dt;
|
||||
for (int i = 0; i < NUM_BLOCKS; i++) {
|
||||
blocks[i].rot += blocks[i].rotSpeed * dt;
|
||||
}
|
||||
for (int i = 0; i < NUM_ENTS; i++) {
|
||||
ents[i].x += ents[i].vx * dt;
|
||||
ents[i].y += ents[i].vy * dt;
|
||||
ents[i].z += ents[i].vz * dt;
|
||||
if (ents[i].y < 0.2f || ents[i].y > 1.2f) ents[i].vy = -ents[i].vy;
|
||||
if (ents[i].x < -4.5f || ents[i].x > 4.5f) ents[i].vx = -ents[i].vx;
|
||||
if (ents[i].z < NEAR_Z) {
|
||||
// respawn at far
|
||||
ents[i].x = (random(200) / 100.0f - 1.0f) * 3.0f;
|
||||
ents[i].y = 0.3f + random(80) / 100.0f;
|
||||
ents[i].z = FAR_Z - 1.0f;
|
||||
ents[i].vz = -0.72f - random(20) * 0.03f; // units/s toward camera
|
||||
}
|
||||
}
|
||||
|
||||
// Clear framebuffer to deep blue-black
|
||||
for (int i = 0; i < W * H; i++) emuGfx::fb[i] = 0xFF080018;
|
||||
|
||||
// --- Floor scanlines (cyan grid on dark) ---
|
||||
for (int y = HORIZON + 1; y < H; y++) {
|
||||
float z = K / (float)(y - HORIZON);
|
||||
if (z > FAR_Z) z = FAR_Z;
|
||||
float fade = 1.0f - (float)(y - HORIZON) / (float)(H - HORIZON);
|
||||
if (fade < 0.15f) fade = 0.15f;
|
||||
int v = (int)(220 * fade);
|
||||
if (v > 255) v = 255;
|
||||
for (int x = 0; x < W; x++) {
|
||||
float wx = (x - 160) * z / FX;
|
||||
float fx = fabsf(wx - floorf(wx + 0.5f));
|
||||
float fzfrac = fabsf(z - floorf(z + 0.5f));
|
||||
bool onGrid = (fx < 0.06f) || (fzfrac < 0.06f);
|
||||
uint32_t col;
|
||||
if (onGrid) {
|
||||
// cyan in ABGR = 0xFFFFFF00
|
||||
col = (0xFFu << 24) | ((uint32_t)v << 8) | ((uint32_t)v << 16);
|
||||
} else {
|
||||
col = 0xFF000010u;
|
||||
}
|
||||
emuGfx::fb[y * W + x] = col;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Ceiling scanlines (magenta grid) ---
|
||||
for (int y = 0; y < HORIZON; y++) {
|
||||
float dy = (float)(HORIZON - y);
|
||||
if (dy < 1) dy = 1;
|
||||
float z = K / dy;
|
||||
if (z > FAR_Z) z = FAR_Z;
|
||||
for (int x = 0; x < W; x++) {
|
||||
float wx = (x - 160) * z / FX;
|
||||
float fx = fabsf(wx - floorf(wx + 0.5f));
|
||||
float fzfrac = fabsf(z - floorf(z + 0.5f));
|
||||
bool onGrid = (fx < 0.06f) || (fzfrac < 0.06f);
|
||||
if (!onGrid) {
|
||||
emuGfx::fb[y * W + x] = 0xFF040008;
|
||||
continue;
|
||||
}
|
||||
float fade = 1.0f - (float)(HORIZON - y) / (float)HORIZON;
|
||||
if (fade < 0.15f) fade = 0.15f;
|
||||
int v = (int)(180 * fade);
|
||||
if (v > 255) v = 255;
|
||||
// magenta in ABGR = 0xFFFF00FF
|
||||
uint32_t col = (0xFFu << 24) | ((uint32_t)v << 16) | ((uint32_t)v << 0); // B?
|
||||
// magenta = R+B: 0xFF00FF => ABGR 0xFFFF00FF
|
||||
col = (0xFFu << 24) | ((uint32_t)v << 0) | ((uint32_t)v << 16);
|
||||
emuGfx::fb[y * W + x] = col;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Walls (left/right/back) as wireframe grids ---
|
||||
// Vertical side edges
|
||||
// Draw grid lines along z for left/right walls
|
||||
int prevLX=0, prevLYf=0, prevLYc=0, prevRX=0, prevRYf=0, prevRYc=0;
|
||||
bool first = true;
|
||||
for (float z = NEAR_Z; z <= FAR_Z; z += 0.5f) {
|
||||
int lx, lyf, lyc, rx, ryf, ryc;
|
||||
if (!project(-WALL_X, 0, z, lx, lyf)) continue;
|
||||
if (!project(-WALL_X, CEIL_H, z, lx, lyc)) lyc = lyf;
|
||||
if (!project( WALL_X, 0, z, rx, ryf)) continue;
|
||||
if (!project( WALL_X, CEIL_H, z, rx, ryc)) ryc = ryf;
|
||||
// verticals
|
||||
drawLine(lx, lyf, lx, lyc, 0xFF4040FF); // blue-ish? use cyan dim
|
||||
drawLine(rx, ryf, rx, ryc, 0xFF4040FF);
|
||||
// connect along z
|
||||
if (!first) {
|
||||
drawLine(prevLX, prevLYf, lx, lyf, 0xFF303080);
|
||||
drawLine(prevLX, prevLYc, lx, lyc, 0xFF303080);
|
||||
drawLine(prevRX, prevRYf, rx, ryf, 0xFF303080);
|
||||
drawLine(prevRX, prevRYc, rx, ryc, 0xFF303080);
|
||||
}
|
||||
prevLX=lx; prevLYf=lyf; prevLYc=lyc;
|
||||
prevRX=rx; prevRYf=ryf; prevRYc=ryc;
|
||||
first=false;
|
||||
}
|
||||
// back wall
|
||||
{
|
||||
int x0,y0,x1,y1;
|
||||
if (project(-WALL_X,0,FAR_Z,x0,y0) && project(WALL_X,0,FAR_Z,x1,y1)) drawLine(x0,y0,x1,y1,0xFF303080);
|
||||
if (project(-WALL_X,CEIL_H,FAR_Z,x0,y0) && project(WALL_X,CEIL_H,FAR_Z,x1,y1)) drawLine(x0,y0,x1,y1,0xFF303080);
|
||||
if (project(-WALL_X,0,FAR_Z,x0,y0) && project(-WALL_X,CEIL_H,FAR_Z,x1,y1)) drawLine(x0,y0,x1,y1,0xFF303080);
|
||||
if (project(WALL_X,0,FAR_Z,x0,y0) && project(WALL_X,CEIL_H,FAR_Z,x1,y1)) drawLine(x0,y0,x1,y1,0xFF303080);
|
||||
}
|
||||
|
||||
// --- Horizon line ---
|
||||
for (int x = 0; x < W; x++) emuGfx::fb[HORIZON * W + x] = 0xFF404040;
|
||||
|
||||
// --- Blocks ---
|
||||
for (int i = 0; i < NUM_BLOCKS; i++) {
|
||||
drawCube(blocks[i].x, blocks[i].size, blocks[i].z, blocks[i].size, blocks[i].rot, blocks[i].color);
|
||||
}
|
||||
|
||||
// --- Entities with glow ---
|
||||
for (int i = 0; i < NUM_ENTS; i++) {
|
||||
int sx, sy;
|
||||
if (!project(ents[i].x, ents[i].y, ents[i].z, sx, sy)) continue;
|
||||
int r = (int)(6.0f + 2.0f * (FAR_Z - ents[i].z));
|
||||
if (r < 2) r = 2;
|
||||
if (r > 12) r = 12;
|
||||
// glow
|
||||
fillCircle(sx, sy, r + 2, (ents[i].color & 0x00FFFFFF) | 0x40000000);
|
||||
fillCircle(sx, sy, r, ents[i].color);
|
||||
// trail line downward to floor
|
||||
int fx, fy;
|
||||
if (project(ents[i].x, 0, ents[i].z, fx, fy)) {
|
||||
drawLine(sx, sy, fx, fy, (ents[i].color & 0x00FFFFFF) | 0x60000000);
|
||||
}
|
||||
}
|
||||
|
||||
emuGfx::dirty = true;
|
||||
}
|
||||
@@ -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 <cstdint>
|
||||
#include <cstddef>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cmath>
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
#include <deque>
|
||||
#include <thread> // for std::this_thread::sleep_for
|
||||
#include <chrono> // 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<milliseconds>(steady_clock::now() - start).count();
|
||||
}
|
||||
|
||||
inline unsigned long micros()
|
||||
{
|
||||
using namespace std::chrono;
|
||||
static const auto start = steady_clock::now();
|
||||
return (unsigned long)duration_cast<microseconds>(steady_clock::now() - start).count();
|
||||
}
|
||||
|
||||
inline void delay(unsigned long ms)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
|
||||
}
|
||||
|
||||
inline void delayMicroseconds(unsigned int us)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(us));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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<std::string> *sink = nullptr;
|
||||
void capture(const char *s)
|
||||
{
|
||||
if (!sink) return;
|
||||
sink->push_back(s);
|
||||
while (sink->size() > 512) sink->pop_front();
|
||||
}
|
||||
template <typename... A> 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;
|
||||
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* 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 <SDL3/SDL.h>
|
||||
#if __has_include(<SDL3/SDL_ttf.h>)
|
||||
#include <SDL3/SDL_ttf.h>
|
||||
#else
|
||||
#include <SDL3_ttf/SDL_ttf.h>
|
||||
#endif
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cmath>
|
||||
#include <cctype>
|
||||
|
||||
// --- 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<PinEdge> pinEdges;
|
||||
bool touchDown = false;
|
||||
int touchX = 0, touchY = 0;
|
||||
std::deque<uint8_t> 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 ---
|
||||
// The path comes from the Makefile: -DAPP_SRC='"examples/$(APP)/$(APP).cpp"'.
|
||||
// Change APP (or replace examples/Demo/Demo.cpp) to run your own sketch.
|
||||
#ifndef APP_SRC
|
||||
#define APP_SRC "examples/Demo/Demo.cpp"
|
||||
#endif
|
||||
#include APP_SRC
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// --- Main entry point ---
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
// Parse simple command-line options
|
||||
long maxFrames = -1; // --frames N: run exactly N frames then exit
|
||||
const char *dumpPath = nullptr;
|
||||
bool userRun = false; // --user-run: disable the safety-hatch timeout
|
||||
long timeoutMs = 10000; // safety hatch: auto-exit after 10 s by default
|
||||
|
||||
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], "--user-run")) userRun = true;
|
||||
else if (!strcmp(argv[i], "--timeout") && i + 1 < argc) timeoutMs = atol(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: " APP_NAME,
|
||||
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;
|
||||
// Frame pacing: the sketch contract is "loop() called once per frame
|
||||
// (~60 fps)". Without pacing this loop busy-spins at hundreds/thousands
|
||||
// of fps on a desktop and every frame-based animation runs too fast,
|
||||
// so we delay until the next 60 Hz tick before starting the next frame.
|
||||
const Uint64 FRAME_MS = 1000 / 60; // ~16.7 ms per frame
|
||||
Uint64 nextFrame = SDL_GetTicks() + FRAME_MS;
|
||||
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]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Safety hatch: auto-exit unless the user asked to play ---
|
||||
if (!userRun && timeoutMs > 0 && millis() >= (unsigned long)timeoutMs) {
|
||||
std::printf("[emu] safety hatch: exiting after %ld ms "
|
||||
"(pass --user-run to run indefinitely)\n", timeoutMs);
|
||||
running = false;
|
||||
break;
|
||||
}
|
||||
|
||||
// --- 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Frame pacing: sleep until the next 60 Hz tick ---
|
||||
Uint64 nowMs = SDL_GetTicks();
|
||||
if (nowMs >= nextFrame) {
|
||||
// Behind schedule (a slow frame or a stall): resync instead of
|
||||
// burst-catching-up, so animation never runs fast to "make up"
|
||||
// lost frames.
|
||||
nextFrame = nowMs;
|
||||
} else {
|
||||
SDL_Delay((Uint32)(nextFrame - nowMs));
|
||||
}
|
||||
nextFrame += FRAME_MS;
|
||||
}
|
||||
|
||||
// --- 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;
|
||||
}
|
||||
Reference in New Issue
Block a user