From 89e235cafe6e3edbc8c824d07a89193e19b43d54 Mon Sep 17 00:00:00 2001 From: Dejvino Date: Mon, 16 Nov 2026 20:49:20 +0100 Subject: [PATCH] cyberspace-demo: Add flythrough demo built on the emulator template Copy of emulator-template with the Cyberflythrough sketch (pseudo-3D grid flight with tracing entities). Host includes the 60 fps pacing and delta-time Demo sample; APP defaults to Cyberflythrough. --- cyberspace-demo/.gitignore | 6 + cyberspace-demo/Makefile | 57 ++ cyberspace-demo/README.md | 87 ++ .../Cyberflythrough/Cyberflythrough.cpp | 846 ++++++++++++++++++ cyberspace-demo/examples/Demo/Demo.cpp | 73 ++ cyberspace-demo/shim.h | 153 ++++ cyberspace-demo/src/main.cpp | 240 +++++ 7 files changed, 1462 insertions(+) create mode 100644 cyberspace-demo/.gitignore create mode 100644 cyberspace-demo/Makefile create mode 100644 cyberspace-demo/README.md create mode 100644 cyberspace-demo/examples/Cyberflythrough/Cyberflythrough.cpp create mode 100644 cyberspace-demo/examples/Demo/Demo.cpp create mode 100644 cyberspace-demo/shim.h create mode 100644 cyberspace-demo/src/main.cpp diff --git a/cyberspace-demo/.gitignore b/cyberspace-demo/.gitignore new file mode 100644 index 0000000..39b39ce --- /dev/null +++ b/cyberspace-demo/.gitignore @@ -0,0 +1,6 @@ +# Build artifacts +*-emu + +# Captured frames +*.bmp +*.png diff --git a/cyberspace-demo/Makefile b/cyberspace-demo/Makefile new file mode 100644 index 0000000..540acea --- /dev/null +++ b/cyberspace-demo/Makefile @@ -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 ?= Cyberflythrough +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 \ No newline at end of file diff --git a/cyberspace-demo/README.md b/cyberspace-demo/README.md new file mode 100644 index 0000000..b4c8ad8 --- /dev/null +++ b/cyberspace-demo/README.md @@ -0,0 +1,87 @@ +# T-Deck Cyberspace Demo + +A wireframe 3D fly-through demo inspired by [System Shock's Cyberspace](https://shodan.fandom.com/wiki/Cyberspace) +from the Shodan Fandom wiki. Renders a rotating wireframe cube that appears to fly +through a tunnel, evoking the cyberspace aesthetic from the System Shock games. + +## Overview + +This demo demonstrates a wireframe 3D rendering engine capable of: +- Rotating cube geometry with X/Y/Z axis spin +- Perspective projection for depth perception +- Color-coded edges (SHODAN green for vertical, cyber teal for horizontal) +- Pulsing central "SHODAN core" visual effect + +The visual style draws from the System Shock cyberspace environment: a +wireframe 3D space where the player moves weightlessly, collecting data +and facing SHODAN's security programs. + +## Controls + +- Default: auto-rotating fly-through +- Press **SPACE** to toggle between auto-spin and manual rotation +- Press **ESCAPE** or **Q** to quit + +## Building & Running + +```bash +# Build and run the cyberflythrough demo +make run + +# Build with different APP name +make run APP=Cyberflythrough + +# Headless smoke test (240 frames, dump BMP) +make smoke + +# Clean built binary +make clean +``` + +## Key Features + +| Feature | Description | +|---------|-------------| +| **Wireframe cube** | 8 vertices, 12 edges rotating in 3D | +| **Perspective projection** | Objects get smaller with "depth" | +| **SHODAN aesthetic** | Green vertical edges, teal horizontal edges | +| **Pulsing core** | Central green eye pulses rhythmically | +| **320x240 resolution** | Optimized for T-Deck screen | + +## File Structure + +``` +cyberspace-demo/ +├── README.md # This file +├── Makefile # Build configuration +├── shim.h # Arduino API shim (millis, random, etc.) +├── src/ +│ └── main.cpp # SDL3 host loop — window, framebuffer, setup()/loop() +└── examples/ + └── Cyberflythrough/ + └── Cyberflythrough.cpp # Wireframe 3D demo sketch +``` + +## How It Works + +The sketch implements the standard emulator contract: +- `setup()` — called once at launch, initializes rotation angles +- `loop()` — called once per frame (~60 fps) + - Clears framebuffer to black + - Increments rotation angles for continuous spin + - Projects 8 cube vertices through rotation + perspective + - Draws all 12 cube edges using Bresenham's line algorithm + - Draws a pulsing "SHODAN core" in the center + - Sets `emuGfx::dirty = true` to present the frame + +The wireframe rendering uses fixed-function transformation: +1. Rotate vertices around X, Y, and Z axes +2. Project 3D coordinates to 2D using perspective division +3. Draw connecting edges between cube vertices + +Edge colors are differentiated: vertical edges (connecting front/back faces) +are rendered in SHODAN green (0xFF00FF00), while horizontal edges are +cyber teal (0xFF00AAFF), helping convey the 3D structure. + +The central "eye" effect is a pulsing circle that rhythmically expands +and contracts, evoking SHODAN's omnipresent observation within cyberspace. \ No newline at end of file diff --git a/cyberspace-demo/examples/Cyberflythrough/Cyberflythrough.cpp b/cyberspace-demo/examples/Cyberflythrough/Cyberflythrough.cpp new file mode 100644 index 0000000..8c5b891 --- /dev/null +++ b/cyberspace-demo/examples/Cyberflythrough/Cyberflythrough.cpp @@ -0,0 +1,846 @@ +/** + * Cyberflythrough — a first-person fly-through of Cyberspace, inspired by + * System Shock's Cyberspace (shodan.fandom.com/wiki/Cyberspace): + * + * "important programs manifest as floating geometric shapes in immense + * rooms of glowing wireframe. Hallways between rooms represent rivers + * of data between nodes, which drag the user along in digital currents." + * + * The camera is dragged along a data current: a wireframe tunnel of + * octagonal rings that swells into immense rooms, populated with the + * classic Cyberspace objects — data cubes, data fragments, infonodes, + * security mines, integrity restoratives, ICE growths — with SHODAN's + * core looming once per loop. + * + * 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 (~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) + * + * Controls: + * SPACE — freeze / resume the current (NetDeck convention) + * f / s — faster / slower current + * h — toggle HUD + */ + +#include "shim.h" + +// Emulator state provided by the host +extern uint32_t emuGfx::fb[320 * 240]; +extern bool emuGfx::dirty; +extern std::deque emu::keyboard; + +static constexpr int W = 320; +static constexpr int H = 240; +static constexpr float PI_F = 3.14159265f; + +// --------------------------------------------------------------------------- +// Colors (framebuffer pixel = 0xAABBGGRR: byte0 = R, byte1 = G, byte2 = B) +// --------------------------------------------------------------------------- +static inline uint32_t rgb(int r, int g, int b) +{ + return 0xFF000000u | ((uint32_t)b << 16) | ((uint32_t)g << 8) | (uint32_t)r; +} +// Scale a color's brightness by m/256. +static inline uint32_t dimc(uint32_t c, int m) +{ + uint32_t r = c & 0xFF, g = (c >> 8) & 0xFF, b = (c >> 16) & 0xFF; + if (m > 256) m = 256; + return 0xFF000000u | ((((b * m) >> 8) & 0xFF) << 16) | + ((((g * m) >> 8) & 0xFF) << 8) | (((r * m) >> 8) & 0xFF); +} + +static const uint32_t COL_RING = rgb(0, 170, 255); // tunnel rings +static const uint32_t COL_RIB = rgb(0, 100, 170); // longitudinal ribs +static const uint32_t COL_STREAK = rgb(190, 230, 255); // data streaks +static const uint32_t COL_STAR = rgb(80, 100, 130); // void stars +static const uint32_t COL_CUBE = rgb(200, 70, 255); // data object (purple cube) +static const uint32_t COL_FRAG = rgb(255, 230, 0); // data fragment (yellow) +static const uint32_t COL_FRAG2 = rgb(255, 140, 0); // ...its orange diamonds +static const uint32_t COL_INFO = rgb(0, 255, 130); // infonode (green signpost) +static const uint32_t COL_MINE = rgb(70, 130, 255); // security mine (blue) +static const uint32_t COL_CROSS = rgb(255, 45, 45); // integrity restorative (red) +static const uint32_t COL_ICE = rgb(255, 60, 190); // ICE growth (magenta) +static const uint32_t COL_SHODAN = rgb(70, 255, 90); // SHODAN core (green) +static const uint32_t COL_HUD = rgb(0, 220, 255); // HUD chrome +static const uint32_t COL_WARN = rgb(255, 150, 0); // trace / warnings + +// --------------------------------------------------------------------------- +// Tiny 3x5 bitmap font (rows top->bottom, 3 bits per row, bit2 = left col) +// --------------------------------------------------------------------------- +#define F3x5(a, b, c, d, e) \ + ((uint16_t)(((a) << 12) | ((b) << 9) | ((c) << 6) | ((d) << 3) | (e))) + +static uint16_t glyph(char ch) +{ + switch (ch) { + case 'A': return F3x5(7, 5, 7, 5, 5); + case 'B': return F3x5(6, 5, 6, 5, 6); + case 'C': return F3x5(7, 4, 4, 4, 7); + case 'D': return F3x5(6, 5, 5, 5, 6); + case 'E': return F3x5(7, 4, 7, 4, 7); + case 'F': return F3x5(7, 4, 7, 4, 4); + case 'G': return F3x5(7, 4, 5, 5, 7); + case 'H': return F3x5(5, 5, 7, 5, 5); + case 'I': return F3x5(7, 2, 2, 2, 7); + case 'J': return F3x5(1, 1, 1, 5, 7); + case 'K': return F3x5(5, 5, 6, 5, 5); + case 'L': return F3x5(4, 4, 4, 4, 7); + case 'M': return F3x5(5, 7, 7, 5, 5); + case 'N': return F3x5(6, 5, 5, 5, 5); + case 'O': return F3x5(7, 5, 5, 5, 7); + case 'P': return F3x5(7, 5, 7, 4, 4); + case 'Q': return F3x5(7, 5, 5, 7, 1); + case 'R': return F3x5(7, 5, 6, 5, 5); + case 'S': return F3x5(7, 4, 7, 1, 7); + case 'T': return F3x5(7, 2, 2, 2, 2); + case 'U': return F3x5(5, 5, 5, 5, 7); + case 'V': return F3x5(5, 5, 5, 5, 2); + case 'W': return F3x5(5, 5, 7, 7, 5); + case 'X': return F3x5(5, 5, 2, 5, 5); + case 'Y': return F3x5(5, 5, 2, 2, 2); + case 'Z': return F3x5(7, 1, 2, 4, 7); + case '0': return F3x5(7, 5, 5, 5, 7); + case '1': return F3x5(2, 6, 2, 2, 7); + case '2': return F3x5(7, 1, 7, 4, 7); + case '3': return F3x5(7, 1, 7, 1, 7); + case '4': return F3x5(5, 5, 7, 1, 1); + case '5': return F3x5(7, 4, 7, 1, 7); + case '6': return F3x5(4, 4, 7, 5, 7); + case '7': return F3x5(7, 1, 1, 2, 2); + case '8': return F3x5(7, 5, 7, 5, 7); + case '9': return F3x5(7, 5, 7, 1, 7); + case '/': return F3x5(1, 1, 2, 4, 4); + case '-': return F3x5(0, 0, 7, 0, 0); + case ':': return F3x5(0, 2, 0, 2, 0); + case '.': return F3x5(0, 0, 0, 0, 2); + case '%': return F3x5(5, 1, 2, 4, 5); + case '<': return F3x5(1, 2, 4, 2, 1); + case '>': return F3x5(4, 2, 1, 2, 4); + default: return 0; + } +} + +static void pset(int x, int y, uint32_t c) +{ + if (x >= 0 && x < W && y >= 0 && y < H) emuGfx::fb[y * W + x] = c; +} + +static void drawChar(int x, int y, char ch, uint32_t c) +{ + uint16_t g = glyph(ch); + for (int r = 0; r < 5; r++) { + int bits = (g >> (12 - 3 * r)) & 7; + for (int col = 0; col < 3; col++) { + if (bits & (4 >> col)) pset(x + col, y + r, c); + } + } +} + +static void drawText(int x, int y, const char *s, uint32_t c, int scale = 1) +{ + while (*s) { + if (*s != ' ') { + if (scale == 1) { + drawChar(x, y, *s, c); + } else { + uint16_t g = glyph(*s); + for (int r = 0; r < 5; r++) { + int bits = (g >> (12 - 3 * r)) & 7; + for (int col = 0; col < 3; col++) { + if (!(bits & (4 >> col))) continue; + for (int py = 0; py < scale; py++) + for (int px = 0; px < scale; px++) + pset(x + col * scale + px, y + r * scale + py, c); + } + } + } + } + x += 4 * scale; + s++; + } +} + +static int textW(const char *s, int scale) +{ + return (int)strlen(s) * 4 * scale - scale; +} + +// Bresenham line, clipped to the screen bounds. +static void drawLine(int x0, int y0, int x1, int y1, uint32_t c) +{ + 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 (;;) { + pset(x0, y0, c); + 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 drawBar(int x, int y, int w, int hgt, float frac, uint32_t c) +{ + for (int i = 0; i <= w; i++) { pset(x + i, y, c); pset(x + i, y + hgt, c); } + for (int j = 0; j <= hgt; j++) { pset(x, y + j, c); pset(x + w, y + j, c); } + int fill = (int)(frac * (w - 1)); + for (int i = 1; i <= fill && fill > 0; i++) + for (int j = 1; j < hgt; j++) + pset(x + i, y + j, c); +} + +// --------------------------------------------------------------------------- +// Camera + data-current path +// --------------------------------------------------------------------------- +// The current flows along +Z; its center drifts like a slow river. +static float pathX(float z) { return 6.0f * sinf(z * 0.045f) + 3.0f * sinf(z * 0.013f + 1.7f); } +static float pathY(float z) { return 4.0f * sinf(z * 0.031f + 4.0f) + 2.0f * sinf(z * 0.08f); } +static float pathXdz(float z) { return 6.0f * 0.045f * cosf(z * 0.045f) + 3.0f * 0.013f * cosf(z * 0.013f + 1.7f); } +static float pathYdz(float z) { return 4.0f * 0.031f * cosf(z * 0.031f + 4.0f) + 2.0f * 0.08f * cosf(z * 0.08f); } + +// Zones: alternate narrow hallways and immense rooms (wiki: "immense rooms +// of glowing wireframe" connected by rivers of data). +static constexpr float ZLEN = 64.0f; +static const int NZONE = 4; +static const float zoneR[NZONE] = { 2.8f, 9.0f, 3.2f, 6.5f }; +static const char *zoneName[NZONE] = { + "MILITARY SPUR", "RESEARCH GROTTO", "DATA CISTERN", "SECURITY GRID" +}; + +static float zoneSizeIdx(int i) +{ + i = ((i % NZONE) + NZONE) % NZONE; + return zoneR[i]; +} + +// Tunnel radius at z, blending smoothly across zone boundaries. +static float tunnelR(float z) +{ + int idx = (int)floorf(z / ZLEN); + float local = z - idx * ZLEN; + float r0 = zoneSizeIdx(idx), r1 = zoneSizeIdx(idx + 1); + const float BLEND = 10.0f; + if (local > ZLEN - BLEND) { + float t = (local - (ZLEN - BLEND)) / BLEND; + t = t * t * (3 - 2 * t); // smoothstep + return r0 + (r1 - r0) * t; + } + return r0; +} + +static float camDist = 0.0f; +static float camRoll = 0.0f; +static float speed = 12.0f; +static bool paused = false, hudOn = true; +static float tGlobal = 0.0f; + +static const float NEARZ = 0.3f; +static const float FARZ = 110.0f; +static const float FL = 230.0f; // focal length in pixels + +// --------------------------------------------------------------------------- +// View transform: world -> view space. Built once per frame. +// M = Rz(roll) * Rx(pitch) * Ry(-yaw), with pitch/yaw from the path tangent. +// --------------------------------------------------------------------------- +static float m11, m12, m13, m21, m22, m23, m31, m32, m33; +static float camX, camY, camZ; + +static void buildView() +{ + camX = pathX(camDist); + camY = pathY(camDist) + 0.3f * sinf(tGlobal * 0.9f); // weightless bob + camZ = camDist; + + // Orientation follows the current's tangent (+z dominant). + float fx = pathXdz(camDist), fy = pathYdz(camDist); + float yaw = atan2f(fx, 1.0f); + float n = sqrtf(fx * fx + 1.0f); + float pitch = atan2f(fy, n); + + // Bank into curves, like drifting weightlessly through the current. + static float prevYaw = 0.0f; + float yawRate = yaw - prevYaw; + if (yawRate > PI_F) yawRate -= 2 * PI_F; + if (yawRate < -PI_F) yawRate += 2 * PI_F; + prevYaw = yaw; + float targetRoll = yawRate * 55.0f; + if (targetRoll > 0.45f) targetRoll = 0.45f; + if (targetRoll < -0.45f) targetRoll = -0.45f; + camRoll += (targetRoll - camRoll) * 0.08f; + + float cy = cosf(yaw), sy = sinf(yaw); + float cp = cosf(pitch), sp = sinf(pitch); + float cr = cosf(camRoll), sr = sinf(camRoll); + + // T = Rz * Rx (rows computed from both matrices) + // Rx(p) rows: [1,0,0],[0,cp,-sp],[0,sp,cp]; Rz(r) rows: [cr,-sr,0],[sr,cr,0],[0,0,1] + float t11 = cr, t12 = -sr * cp, t13 = sr * sp; + float t21 = sr, t22 = cr * cp, t23 = -cr * sp; + float t31 = 0.0f, t32 = sp, t33 = cp; + // M = T * Ry(-yaw), where Ry(-yaw) = [cy,0,-sy],[0,1,0],[sy,0,cy] + m11 = t11 * cy + t13 * sy; + m12 = t12; + m13 = t11 * -sy + t13 * cy; + m21 = t21 * cy + t23 * sy; + m22 = t22; + m23 = t21 * -sy + t23 * cy; + m31 = t31 * cy + t33 * sy; + m32 = t32; + m33 = t31 * -sy + t33 * cy; +} + +// World point -> view space. Returns false if behind the near plane. +static inline bool projView(float wx, float wy, float wz, + float *vx, float *vy, float *vz) +{ + float x = wx - camX, y = wy - camY, z = wz - camZ; + *vx = m11 * x + m12 * y + m13 * z; + *vy = m21 * x + m22 * y + m23 * z; + *vz = m31 * x + m32 * y + m33 * z; + return *vz >= NEARZ; +} + +// Draw a view-space segment clamped to the far plane, with depth fade. +static void drawSegV(float vax, float vay, float vaz, + float vbx, float vby, float vbz, + uint32_t col, int bright) +{ + if (vaz > FARZ && vbz > FARZ) return; + float zmid = 0.5f * (vaz + vbz); + if (zmid > FARZ) return; + int fade = (int)(256.0f * (1.0f - 0.85f * zmid / FARZ)); + if (fade < 12) fade = 12; + int b = (bright * fade) >> 8; + if (b <= 0) return; + float sxa = 160.0f + vax * FL / vaz; + float sya = 120.0f - vay * FL / vaz; + float sxb = 160.0f + vbx * FL / vbz; + float syb = 120.0f - vby * FL / vbz; + drawLine((int)sxa, (int)sya, (int)sxb, (int)syb, dimc(col, b)); +} + +// World-space segment with near-plane clipping + depth fade. +static void drawSegW(float ax, float ay, float az, + float bx, float by, float bz, + uint32_t col, int bright = 256) +{ + float vax, vay, vaz, vbx, vby, vbz; + projView(ax, ay, az, &vax, &vay, &vaz); + projView(bx, by, bz, &vbx, &vby, &vbz); + if (vaz < NEARZ && vbz < NEARZ) return; + if (vaz < NEARZ || vbz < NEARZ) { + float k = (NEARZ - vaz) / (vbz - vaz); + if (k < 0.0f || k > 1.0f) return; + if (vaz < NEARZ) { + vax += (vbx - vax) * k; vay += (vby - vay) * k; vaz = NEARZ; + } else { + vbx += (vax - vbx) * k; vby += (vay - vby) * k; vbz = NEARZ; + } + } + drawSegV(vax, vay, vaz, vbx, vby, vbz, col, bright); +} + +// World-space single point. +static void drawPointW(float wx, float wy, float wz, uint32_t col, int bright) +{ + float vx, vy, vz; + if (!projView(wx, wy, wz, &vx, &vy, &vz)) return; + if (vz > FARZ) return; + int fade = (int)(256.0f * (1.0f - 0.85f * vz / FARZ)); + if (fade < 12) fade = 12; + int b = (bright * fade) >> 8; + if (b <= 0) return; + pset((int)(160.0f + vx * FL / vz), (int)(120.0f - vy * FL / vz), dimc(col, b)); +} + +// Screen-space wire circle (billboards: mines). +static void drawCircleScreen(float cx, float cy, float r, uint32_t col) +{ + const int SEG = 14; + float px0 = cx + r, py0 = cy; + for (int i = 1; i <= SEG; i++) { + float a = i * 2 * PI_F / SEG; + float px = cx + r * cosf(a), py = cy + r * sinf(a); + drawLine((int)px0, (int)py0, (int)px, (int)py, col); + px0 = px; py0 = py; + } +} + +// --------------------------------------------------------------------------- +// World content +// --------------------------------------------------------------------------- +static constexpr int NSTREAK = 26; +static float streakA[NSTREAK], streakR[NSTREAK], streakZ[NSTREAK]; + +static constexpr int NOBJ = 15; +static const uint8_t objType[NOBJ] = { + 0, 1, 2, 4, 0, 3, 5, 1, 0, 1, 2, 3, 5, 1, 0 + // 0 data cube, 1 data fragment, 2 infonode, 3 security mine, + // 4 integrity restorative, 5 ICE growth +}; +static float objZ[NOBJ], objAng[NOBJ], objRF[NOBJ], objSpin[NOBJ]; +static int objPassCount = 0; + +static constexpr float LOOP = 256.0f; +static constexpr float SHODAN_Z = 224.0f; // once per loop, deep in the grid + +// Void stars: fixed directions, rotate with the camera (no translation). +static constexpr int NSTARS = 70; +static float starX[NSTARS], starY[NSTARS], starZ[NSTARS]; + +// HUD state +static float traceTimer = 90.0f; +static float bannerTimer = 0.0f; +static char bannerText[48] = ""; +static uint32_t bannerCol = COL_HUD; +static int curZone = -1; + +static void showBanner(const char *s, uint32_t c, float t) +{ + snprintf(bannerText, sizeof(bannerText), "%s", s); + bannerCol = c; + bannerTimer = t; +} + +static void randomizeStreak(int i, float z) +{ + streakA[i] = (random(360) / 360.0f) * 2 * PI_F; + streakR[i] = 0.35f + random(100) / 100.0f * 0.6f; + streakZ[i] = z; +} + +static void randomizeObj(int i, float z, bool reseed) +{ + objZ[i] = z; + if (reseed) { + objAng[i] = (random(360) / 360.0f) * 2 * PI_F; + objRF[i] = 0.3f + random(100) / 100.0f * 0.45f; + objSpin[i] = random(100) / 100.0f * 1.5f + 0.4f; + } +} + +void setup() +{ + randomSeed(1337); + for (int i = 0; i < NSTREAK; i++) randomizeStreak(i, random(200) + 5.0f); + for (int i = 0; i < NOBJ; i++) randomizeObj(i, (i + 1) * (LOOP / NOBJ), true); + for (int i = 0; i < NSTARS; i++) { + float u = random(200) / 200.0f * 2 - 1; + float a = random(360) / 360.0f * 2 * PI_F; + float r = sqrtf(1 - u * u); + starX[i] = r * cosf(a) * 400; + starY[i] = u * 400; + starZ[i] = r * sinf(a) * 400; + } + showBanner("JACKING IN...", COL_HUD, 3.0f); +} + +// --------------------------------------------------------------------------- +// Object renderers — wireframe geometry around a world-space center +// --------------------------------------------------------------------------- +static void drawWireBox(float cx, float cy, float cz, + float hx, float hy, float hz, + float ry, float rx, float yOff, + uint32_t col, int bright) +{ + float vx[8], vy[8], vz[8]; + const float sx[8] = { -1, 1, 1, -1, -1, 1, 1, -1 }; + const float sy[8] = { -1, -1, 1, 1, -1, -1, 1, 1 }; + const float sz[8] = { -1, -1, -1, -1, 1, 1, 1, 1 }; + float cyy = cosf(ry), syy = sinf(ry); + float cxr = cosf(rx), sxr = sinf(rx); + for (int i = 0; i < 8; i++) { + float lx = sx[i] * hx, ly = sy[i] * hy + yOff, lz = sz[i] * hz; + float x1 = lx * cyy + lz * syy; + float z1 = -lx * syy + lz * cyy; + float y1 = ly * cxr - z1 * sxr; + float z2 = ly * sxr + z1 * cxr; + vx[i] = cx + x1; vy[i] = cy + y1; vz[i] = cz + z2; + } + static const int ed[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 i = 0; i < 12; i++) + drawSegW(vx[ed[i][0]], vy[ed[i][0]], vz[ed[i][0]], + vx[ed[i][1]], vy[ed[i][1]], vz[ed[i][1]], col, bright); +} + +static void drawOcta(float cx, float cy, float cz, float r, uint32_t col, int bright) +{ + const float v[6][3] = { + { 0, 1, 0 }, { 0, -1, 0 }, + { 1, 0, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, 0, -1 } + }; + static const int ed[12][2] = { + { 0, 2 }, { 0, 3 }, { 0, 4 }, { 0, 5 }, + { 1, 2 }, { 1, 3 }, { 1, 4 }, { 1, 5 }, + { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 2 } + }; + for (int i = 0; i < 12; i++) + drawSegW(cx + v[ed[i][0]][0] * r, cy + v[ed[i][0]][1] * r, cz + v[ed[i][0]][2] * r, + cx + v[ed[i][1]][0] * r, cy + v[ed[i][1]][1] * r, cz + v[ed[i][1]][2] * r, + col, bright); +} + +static void drawPyramid(float cx, float cy, float cz, float s, uint32_t col, int bright) +{ + float b[4][2] = { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } }; + for (int i = 0; i < 4; i++) { + int j = (i + 1) & 3; + drawSegW(cx + b[i][0] * s, cy, cz + b[i][1] * s, + cx + b[j][0] * s, cy, cz + b[j][1] * s, col, bright); + drawSegW(cx + b[i][0] * s, cy, cz + b[i][1] * s, + cx, cy + 2.2f * s, cz, col, bright); + } +} + +// Data Object: spinning purple cube (wiki: "Appears as a spinning purple cube") +static void drawObjCube(float cx, float cy, float cz, float s, float spin, uint32_t col) +{ + drawWireBox(cx, cy, cz, s, s, s, spin, spin * 0.7f, 0, col, 256); + drawWireBox(cx, cy, cz, s * 0.55f, s * 0.55f, s * 0.55f, -spin * 1.3f, spin, 0, + dimc(col, 160), 200); +} + +// Data Fragment: yellow square + four orange diamonds +static void drawObjFragment(float cx, float cy, float cz, float s, float spin) +{ + float c = cosf(spin), si = sinf(spin); + // central yellow square, spinning in the XY plane + float q[4][2] = { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } }; + float px[4], py[4]; + for (int i = 0; i < 4; i++) { + px[i] = cx + (q[i][0] * c - q[i][1] * si) * s; + py[i] = cy + (q[i][0] * si + q[i][1] * c) * s; + } + for (int i = 0; i < 4; i++) { + int j = (i + 1) & 3; + drawSegW(px[i], py[i], cz, px[j], py[j], cz, COL_FRAG, 256); + } + // four small orange octahedra at the diagonals + for (int k = 0; k < 4; k++) { + float a = spin * 0.6f + k * PI_F / 2.0f + PI_F / 4.0f; + float dx = 2.1f * s * cosf(a), dy = 2.1f * s * sinf(a); + drawOcta(cx + dx, cy + dy, cz, s * 0.35f, COL_FRAG2, 256); + } +} + +// Infonode: green geometric signpost +static void drawObjInfonode(float cx, float cy, float cz, float s, float spin) +{ + drawSegW(cx, cy - 2.0f * s, cz, cx, cy + 0.4f * s, cz, dimc(COL_INFO, 150), 220); + drawOcta(cx, cy + 0.9f * s, cz, s * 0.8f, COL_INFO, 256); + // orbiting spark + float a = spin * 2.0f; + drawPointW(cx + 1.6f * s * cosf(a), cy + 0.9f * s, cz + 1.6f * s * sinf(a), + COL_INFO, 256); +} + +// Security Mine: blue sphere (billboard circles, pulsing) +static void drawObjMine(float cx, float cy, float cz, float s, float vx, float vy, float vz) +{ + float pulse = 1.0f + 0.15f * sinf(tGlobal * 3.0f + cx); + int fade = (int)(256.0f * (1.0f - 0.85f * vz / FARZ)); + if (fade < 12) fade = 12; + float r = s * FL / vz * pulse; + float sx = vx, sy = vy; + drawCircleScreen(sx, sy, r, dimc(COL_MINE, (200 * fade) >> 8)); + drawCircleScreen(sx, sy, r * 0.55f, dimc(COL_MINE, (230 * fade) >> 8)); + pset((int)sx, (int)sy, dimc(COL_MINE, fade)); + // priming blink + if (fmodf(tGlobal * 1.5f + cx, 1.0f) < 0.15f) + drawCircleScreen(sx, sy, r * 1.25f, dimc(COL_WARN, (170 * fade) >> 8)); +} + +// Integrity Restorative: red cross (three overlapping boxes) +static void drawObjCross(float cx, float cy, float cz, float s) +{ + drawWireBox(cx, cy, cz, 1.4f * s, 0.35f * s, 0.35f * s, 0, 0, 0, COL_CROSS, 256); + drawWireBox(cx, cy, cz, 0.35f * s, 1.4f * s, 0.35f * s, 0, 0, 0, COL_CROSS, 256); + drawWireBox(cx, cy, cz, 0.35f * s, 0.35f * s, 1.4f * s, 0, 0, 0, COL_CROSS, 180); +} + +// ICE growth: cluster of magenta pyramids +static void drawObjIce(float cx, float cy, float cz, float s) +{ + int shim = ((int)(tGlobal * 3.0f)) & 1; + drawPyramid(cx - 1.3f * s, cy, cz, 0.9f * s, COL_ICE, 256); + drawPyramid(cx + 1.2f * s, cy, cz + 0.4f * s, 0.7f * s, COL_ICE, shim ? 256 : 150); + drawPyramid(cx, cy, cz - 1.1f * s, 0.5f * s, COL_ICE, 200); +} + +// SHODAN's core: inverted diamond with four curved tentacles, in a +// rotating shield ring. (Wiki: "a large vertical diamond, with the upper +// part instead ending in four curved tentacles") +static void drawShodan(float wx, float wy, float wz) +{ + float pulse = 0.65f + 0.35f * sinf(tGlobal * 2.4f); + int bright = (int)(150 + 106 * pulse); + float rot = tGlobal * 0.35f; + float c = cosf(rot), si = sinf(rot); + + // rotate ring/tentacle anchor points around Y + const int NR = 8; + float rvx[NR], rvy[NR], rvz[NR]; + for (int i = 0; i < NR; i++) { + float a = rot + i * PI_F / 4.0f; + float lx = 2.6f * cosf(a), lz = 2.6f * sinf(a); + rvx[i] = wx + lx; rvy[i] = wy + 1.2f; rvz[i] = wz + lz; + } + // top vertex, bottom vertex + float tx = wx, ty = wy - 4.6f, tz = wz; + float hx = wx, hy = wy + 4.2f, hz = wz; // top spike (tentacle mount plane) + // diamond edges: bottom -> ring, ring cycle, ring -> top spike vertex + for (int i = 0; i < NR; i++) { + int j = (i + 1) & 7; + drawSegW(tx, ty, tz, rvx[i], rvy[i], rvz[i], COL_SHODAN, bright); + drawSegW(rvx[i], rvy[i], rvz[i], rvx[j], rvy[j], rvz[j], COL_SHODAN, bright); + drawSegW(rvx[i], rvy[i], rvz[i], hx, hy, hz, dimc(COL_SHODAN, 200), bright); + } + // four curved tentacles rising from the ring diagonals + for (int k = 0; k < 4; k++) { + float a = rot + PI_F / 4.0f + k * PI_F / 2.0f; + float ox = cosf(a), oz = sinf(a); + float sway = 0.8f * sinf(tGlobal * 1.7f + k * 1.57f); + float p0x = wx + ox * 2.6f, p0y = wy + 1.9f, p0z = wz + oz * 2.6f; + float p1x = wx + ox * 4.6f, p1y = wy + 3.8f, p1z = wz + oz * 4.6f; + float p2x = wx + ox * 2.6f + sway, p2y = wy + 6.4f + sway, p2z = wz + oz * 2.6f; + float lx = p0x, ly = p0y, lz = p0z; + for (int i = 1; i <= 6; i++) { + float u = i / 6.0f; + float iu = 1 - u; + float bx = iu * iu * p0x + 2 * iu * u * p1x + u * u * p2x; + float by = iu * iu * p0y + 2 * iu * u * p1y + u * u * p2y; + float bz = iu * iu * p0z + 2 * iu * u * p1z + u * u * p2z; + drawSegW(lx, ly, lz, bx, by, bz, COL_SHODAN, bright); + lx = bx; ly = by; lz = bz; + } + } + // shield ring at radius 8, offset rotation, dim green + float ringR = 8.0f; + for (int i = 0; i < NR; i++) { + float a = -rot * 0.6f + i * PI_F / 4.0f; + float ax = wx + ringR * cosf(a), az = wz + ringR * sinf(a); + float b = -rot * 0.6f + ((i + 1) & 7) * PI_F / 4.0f; + float bx = wx + ringR * cosf(b), bz = wz + ringR * sinf(b); + drawSegW(ax, wy, az, bx, wy, bz, dimc(COL_SHODAN, 110), 220); + } + // central eye + drawPointW(wx, wy + 0.4f, wz, rgb(180, 255, 190), 256); +} + +// --------------------------------------------------------------------------- +// HUD (NetDeck chrome: crosshair, LNK/TRACE bars, zone banner, readouts) +// --------------------------------------------------------------------------- +static void drawHud() +{ + // crosshair + drawLine(152, 120, 148, 120, COL_HUD); + drawLine(168, 120, 172, 120, COL_HUD); + drawLine(160, 112, 160, 108, COL_HUD); + drawLine(160, 128, 160, 132, COL_HUD); + pset(160, 120, COL_HUD); + + char buf[40]; + + // top-left: net label + drawText(4, 4, "C-SPACE // CITADEL", COL_HUD); + + // top-right: link integrity + trace + drawText(232, 4, "LNK", COL_HUD); + drawBar(252, 3, 40, 6, 0.87f, COL_HUD); + drawText(295, 4, "87%", COL_HUD); + + bool blink = fmodf(tGlobal * 4.0f, 2.0f) < 1.0f; + uint32_t traceCol = (traceTimer < 15.0f && blink) ? COL_CROSS : COL_WARN; + drawText(214, 12, "TRACE", traceCol); + drawBar(246, 11, 46, 6, traceTimer / 120.0f, traceCol); + + // bottom-left: distance traveled + snprintf(buf, sizeof(buf), "DIST %04dM", (int)fmodf(camDist, 9999.0f)); + drawText(4, 231, buf, COL_HUD); + + // bottom-center: velocity + snprintf(buf, sizeof(buf), "VEL %02d U/S", (int)speed); + drawText(130, 231, buf, dimc(COL_HUD, 170)); + + // bottom-right: data nodes scanned + snprintf(buf, sizeof(buf), "NODE %02d", objPassCount % 100); + drawText(272, 231, buf, COL_HUD); + + // banner + if (bannerTimer > 0.0f) { + int tw = textW(bannerText, 2); + int bx = 160 - tw / 2; + int by = 26; + drawText(bx - 14, by, ">", bannerCol, 2); + drawText(bx + tw + 6, by, "<", bannerCol, 2); + drawText(bx, by, bannerText, bannerCol, 2); + for (int i = -14; i < tw + 20; i += 4) { + pset(bx + i, by - 5, dimc(bannerCol, 150)); + pset(bx + i, by + 13, dimc(bannerCol, 150)); + } + } + + if (paused && fmodf(tGlobal * 2.0f, 1.0f) < 0.6f) + drawText(132, 140, "SIM PAUSED", COL_WARN, 1); +} + +// --------------------------------------------------------------------------- +// Frame +// --------------------------------------------------------------------------- +void loop() +{ + // --- timing --- + static unsigned long lastMs = 0; + unsigned long now = millis(); + float dt = (now - lastMs) / 1000.0f; + lastMs = now; + if (dt > 0.05f) dt = 0.05f; + + // --- input --- + while (!emu::keyboard.empty()) { + uint8_t k = emu::keyboard.front(); + emu::keyboard.pop_front(); + if (k == ' ') paused = !paused; + else if (k == 'f') { speed *= 1.25f; if (speed > 36) speed = 36; } + else if (k == 's') { speed /= 1.25f; if (speed < 4) speed = 4; } + else if (k == 'h') hudOn = !hudOn; + } + + // --- simulation --- + if (!paused) { + tGlobal += dt; + camDist += speed * dt; + + traceTimer -= dt; + if (traceTimer <= 0.0f) { + showBanner("TRACE LOST - REROUTING", COL_WARN, 2.5f); + traceTimer = 110.0f + random(40); + } + + // zone banners + int zc = ((int)floorf(camDist / ZLEN) % NZONE + NZONE) % NZONE; + if (zc != curZone) { + curZone = zc; + if (camDist > 10.0f) + showBanner(zoneName[zc], COL_HUD, 2.2f); + } + + // data streaks rush past (a bit faster than the current itself) + for (int i = 0; i < NSTREAK; i++) { + streakZ[i] += speed * 1.8f * dt; + if (streakZ[i] > camDist + FARZ) + randomizeStreak(i, camDist + 4.0f); + } + + // recycle passed objects around the loop + for (int i = 0; i < NOBJ; i++) { + if (objZ[i] - camDist < -8.0f) { + objZ[i] += LOOP; + randomizeObj(i, objZ[i], true); + objPassCount++; + } + } + if (bannerTimer > 0.0f) bannerTimer -= dt; + } + + // --- render --- + for (int i = 0; i < W * H; i++) emuGfx::fb[i] = 0xFF000000; + + buildView(); + + // void stars (direction-only: rotate with the camera) + for (int i = 0; i < NSTARS; i++) { + float vx = m11 * starX[i] + m12 * starY[i] + m13 * starZ[i]; + float vy = m21 * starX[i] + m22 * starY[i] + m23 * starZ[i]; + float vz = m31 * starX[i] + m32 * starY[i] + m33 * starZ[i]; + if (vz < 2.0f) continue; + int b = (int)(64.0f * (vz / 400.0f) + 40); + pset((int)(160 + vx * FL / vz), (int)(120 - vy * FL / vz), dimc(COL_STAR, b)); + } + + // tunnel rings + longitudinal ribs + const float RSTEP = 4.0f; + float z0 = ceilf((camDist + 1.5f) / RSTEP) * RSTEP; + float pxc[8], pyc[8], pzc[8]; + bool prevValid = false; + for (float z = z0; z <= camDist + FARZ; z += RSTEP) { + float r = tunnelR(z); + float cx = pathX(z), cy = pathY(z); + float vx[8], vy[8], vz2[8]; + bool ok = true; + for (int i = 0; i < 8; i++) { + float a = i * PI_F / 4.0f; + ok &= projView(cx + r * cosf(a), cy + r * sinf(a), z, + &vx[i], &vy[i], &vz2[i]); + } + int brightRing = ((int)(z / RSTEP) % 4 == 0) ? 256 : 190; + if (ok) { + for (int i = 0; i < 8; i++) { + int j = (i + 1) & 7; + drawSegV(vx[i], vy[i], vz2[i], vx[j], vy[j], vz2[j], + COL_RING, brightRing); + } + } + if (prevValid && ok) { + for (int i = 0; i < 8; i++) + drawSegV(pxc[i], pyc[i], pzc[i], vx[i], vy[i], vz2[i], + COL_RIB, 170); + } + for (int i = 0; i < 8; i++) { pxc[i] = vx[i]; pyc[i] = vy[i]; pzc[i] = vz2[i]; } + prevValid = ok; + } + + // data streaks + for (int i = 0; i < NSTREAK; i++) { + float z = streakZ[i]; + float r = tunnelR(z) * streakR[i]; + float cx = pathX(z) + r * cosf(streakA[i]); + float cy = pathY(z) + r * sinf(streakA[i]); + drawSegW(cx, cy, z, cx, cy, z + 2.2f, COL_STREAK, 220); + } + + // SHODAN's core, once per loop + float dsh = SHODAN_Z - fmodf(camDist, LOOP); + if (dsh < -LOOP / 2) dsh += LOOP; + float coreZ = camDist + dsh; + if (dsh > -10.0f && dsh < FARZ) + drawShodan(pathX(coreZ), pathY(coreZ), coreZ); + + // cyberspace objects + for (int i = 0; i < NOBJ; i++) { + float z = objZ[i]; + float dz = z - camDist; + if (dz < 0.5f || dz > FARZ) continue; + float r = tunnelR(z) * objRF[i]; + float cx = pathX(z) + r * cosf(objAng[i]); + float cy = pathY(z) + r * sinf(objAng[i]); + float vx, vy, vz; + bool vis = projView(cx, cy, z, &vx, &vy, &vz); + float s = 0.9f; + switch (objType[i]) { + case 0: drawObjCube(cx, cy, z, s, tGlobal * objSpin[i], COL_CUBE); break; + case 1: drawObjFragment(cx, cy, z, s, tGlobal * objSpin[i] * 0.8f); break; + case 2: drawObjInfonode(cx, cy, z, s, tGlobal * objSpin[i]); break; + case 3: + if (vis) drawObjMine(cx, cy, z, s * 0.9f, + 160.0f + vx * FL / vz, 120.0f - vy * FL / vz, vz); + break; + case 4: drawObjCross(cx, cy, z, s * 0.8f); break; + case 5: drawObjIce(cx, cy, z, s); break; + } + } + + if (hudOn) drawHud(); + + emuGfx::dirty = true; +} diff --git a/cyberspace-demo/examples/Demo/Demo.cpp b/cyberspace-demo/examples/Demo/Demo.cpp new file mode 100644 index 0000000..1f5d056 --- /dev/null +++ b/cyberspace-demo/examples/Demo/Demo.cpp @@ -0,0 +1,73 @@ +/** + * Demo sketch — replace this file with your own experiment. + * + * Contract with the emulator host: + * - 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) + * + * Update state with DELTA TIME, not per-frame constants: measure the real + * seconds since the previous loop() call (see loop() below) and scale all + * speeds in "units per second" by it. Then the sketch runs at the same + * speed no matter what fps the host (or the real hardware) manages. + * + * This sample just bounces a colored box around — enough to prove the + * pipeline works. Delete everything and start from the structure below. + */ + +#include "shim.h" + +// Emulator state provided by the host +extern uint32_t emuGfx::fb[320 * 240]; +extern bool emuGfx::dirty; +extern std::deque emu::keyboard; + +static constexpr int W = 320; +static constexpr int H = 240; + +// --- Demo state ----------------------------------------------------------- +static float boxX = 40, boxY = 30; +static float velX = 100.0f, velY = 70.0f; // pixels per second +static unsigned long lastMs = 0; +static constexpr float BOX = 24.0f; + +void setup() +{ + randomSeed(millis()); + velX = 60.0f + random(100) * 1.2f; // 60..180 px/s + velY = 60.0f + random(100) * 1.2f; +} + +void loop() +{ + // 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) + + // Move and bounce + boxX += velX * dt; + boxY += velY * dt; + if (boxX < 0 || boxX + BOX > W) { velX = -velX; boxX += velX * dt; } + if (boxY < 0 || boxY + BOX > H) { velY = -velY; boxY += velY * dt; } + + // Clear the framebuffer (opaque black, alpha = 0xFF) + for (int i = 0; i < W * H; i++) emuGfx::fb[i] = 0xFF000000; + + // Draw a filled box with a color that drifts over time + uint8_t r = (uint8_t)(128 + 127 * sinf(millis() / 900.0f)); + uint32_t color = 0xFF000000u | ((uint32_t)r << 16) | 0x0000CC66u; + for (int y = (int)boxY; y < (int)(boxY + BOX); y++) { + if (y < 0 || y >= H) continue; + for (int x = (int)boxX; x < (int)(boxX + BOX); x++) { + if (x < 0 || x >= W) continue; + emuGfx::fb[y * W + x] = color; + } + } + + // Present the frame + emuGfx::dirty = true; +} diff --git a/cyberspace-demo/shim.h b/cyberspace-demo/shim.h new file mode 100644 index 0000000..a6542ab --- /dev/null +++ b/cyberspace-demo/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/cyberspace-demo/src/main.cpp b/cyberspace-demo/src/main.cpp new file mode 100644 index 0000000..27ba6a9 --- /dev/null +++ b/cyberspace-demo/src/main.cpp @@ -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 +#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 --- +// 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; +} \ No newline at end of file