Files
Dejvino 80d931b875 tron-demo: Add pseudo-3D Tron room flythrough demo
Copy of emulator-template with a TronRoom sketch demonstrating the 3D
toolkit: camera transform (forward fly + sway + bob), 1/z perspective
projection, solid shaded cubes with painter's-algorithm depth sorting,
1/z-scaled billboard entities, depth fog, and world-space scrolling
grids. Respawn margin keeps objects from straddling the camera near
plane. Includes the 60 fps pacing and Makefile sketch-dependency fix.
2026-11-16 21:01:03 +01:00

456 lines
17 KiB
C++

/**
* TronRoom — TRON-like pseudo-3D flythrough 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.
*
* 3D techniques on display (all software, no GPU):
* - full camera transform: forward flight + lateral sway + height bob,
* everything projected with true perspective (divide by depth)
* - solid shaded cubes: rotated face normals lit from above, faces
* depth-sorted with the painter's algorithm, bright wireframe on top
* - billboard entities whose radius scales with 1/z (true perspective)
* - depth fog on every piece of world geometry
* - floor/ceiling grids computed in world space so they stream past
*
* Keys: W/S = fly faster/slower, Q/ESC = quit.
*/
#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;
// --- Camera ------------------------------------------------------------------
// The camera flies forward along +Z; the whole world is drawn relative to it.
static float camX = 0.0f; // lateral sway position
static float camY = 0.0f; // height bob
static float camZ = 0.0f; // forward position (units)
static float flySpeed = 2.0f; // forward speed, units/s (W/S adjusts)
static float swayT = 0.0f; // sway phase
static float bobT = 0.0f; // bob phase
// --- 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);
}
}
}
// Scale an ABGR color's RGB channels by f (depth fog / shading).
static inline uint32_t dimColor(uint32_t c, float f) {
if (f < 0) f = 0;
if (f > 1) f = 1;
uint32_t r = (uint32_t)((c & 0xFF) * f);
uint32_t g = (uint32_t)(((c >> 8) & 0xFF) * f);
uint32_t b = (uint32_t)(((c >> 16) & 0xFF) * f);
return 0xFF000000u | (b << 16) | (g << 8) | r;
}
// Horizontal span with clipping.
static inline void hline(int y, int xa, int xb, uint32_t c) {
if (y < 0 || y >= H) return;
if (xa > xb) { int t = xa; xa = xb; xb = t; }
if (xb < 0 || xa >= W) return;
if (xa < 0) xa = 0;
if (xb >= W) xb = W - 1;
for (int x = xa; x <= xb; x++) emuGfx::fb[y * W + x] = c;
}
// Scanline triangle fill (float vertices, clips to screen).
static void fillTri(float x0, float y0, float x1, float y1, float x2, float y2, uint32_t c) {
if (y1 < y0) { float t; t = x0; x0 = x1; x1 = t; t = y0; y0 = y1; y1 = t; }
if (y2 < y0) { float t; t = x0; x0 = x2; x2 = t; t = y0; y0 = y2; y2 = t; }
if (y2 < y1) { float t; t = x1; x1 = x2; x2 = t; t = y1; y1 = y2; y2 = t; }
if (y2 - y0 < 0.5f) return;
int yA = (int)ceilf(y0), yB = (int)y2;
if (yA < 0) yA = 0;
if (yB > H - 1) yB = H - 1;
for (int y = yA; y <= yB; y++) {
float yc = (float)y + 0.5f;
// long edge p0 -> p2
float t = (yc - y0) / (y2 - y0);
if (t < 0) t = 0;
if (t > 1) t = 1;
float xa = x0 + (x2 - x0) * t;
float xb;
if (yc < y1) {
float t2 = (y1 - y0 < 0.5f) ? 1.0f : (yc - y0) / (y1 - y0);
if (t2 < 0) t2 = 0;
if (t2 > 1) t2 = 1;
xb = x0 + (x1 - x0) * t2;
} else {
float t2 = (y2 - y1 < 0.5f) ? 0.0f : (yc - y1) / (y2 - y1);
if (t2 < 0) t2 = 0;
if (t2 > 1) t2 = 1;
xb = x1 + (x2 - x1) * t2;
}
hline(y, (int)floorf(xa), (int)ceilf(xb), c);
}
}
static void fillQuad(float x0, float y0, float x1, float y1,
float x2, float y2, float x3, float y3, uint32_t c) {
fillTri(x0, y0, x1, y1, x2, y2, c);
fillTri(x0, y0, x2, y2, x3, y3, c);
}
// Project a 3D WORLD point to screen, relative to the camera. Y up.
// Returns false if behind the near plane.
static bool project(float X, float Y, float Z, int &sx, int &sy) {
float rx = X - camX;
float ry = Y - camY;
float rz = Z - camZ;
if (rz < 0.5f) return false;
sx = (int)(160.0f + rx * FX / rz);
sy = (int)(HORIZON + (K - ry * FX) / rz);
return true;
}
// --- World state ------------------------------------------------------------
struct Block {
float x, z; // position on floor (center)
float size; // half-extent
float rot; // yaw
float rotSpeed; // rad/s
uint32_t color;
};
struct Entity {
float x, y, z;
float vx, vy, vz; // units/s
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];
// --- Setup ------------------------------------------------------------------
static void respawnBlock(Block &b, float zNear, float zFar) {
b.x = (random(200) / 100.0f - 1.0f) * 4.0f;
b.z = zNear + (zFar - zNear) * (random(100) / 100.0f);
b.size = 0.4f + random(60) / 100.0f;
b.rot = random(628) / 100.0f;
b.rotSpeed = (random(200) - 100) * 0.012f; // rad/s (-1.2..1.2)
uint32_t cols[3] = { 0xFFFF00FF, 0xFFFFFF00, 0xFF00FFFF }; // magenta/cyan/yellow
b.color = cols[random(3)];
}
static void respawnEntity(Entity &e, float zNear, float zFar) {
e.x = (random(200) / 100.0f - 1.0f) * 3.0f;
e.y = 0.3f + random(80) / 100.0f;
e.z = zNear + (zFar - zNear) * (random(100) / 100.0f);
e.vx = (random(200) - 100) * 0.03f; // units/s (-3..3)
e.vy = (random(100) - 50) * 0.012f; // units/s
e.vz = -0.72f - random(20) * 0.03f; // units/s toward camera
e.trailLen = 0;
}
void setup() {
randomSeed(millis());
for (int i = 0; i < NUM_BLOCKS; i++) {
respawnBlock(blocks[i], 3.0f + i * 3.5f, FAR_Z);
if (blocks[i].z > FAR_Z - 2) blocks[i].z = FAR_Z - 2;
}
for (int i = 0; i < NUM_ENTS; i++) {
respawnEntity(ents[i], 4.0f, FAR_Z);
}
}
// --- Solid shaded cube (painter's algorithm) --------------------------------
static void drawCube(const Block &b) {
float relz = b.z - camZ;
float fog = 1.0f - relz / FAR_Z;
float c = cosf(b.rot), sn = sinf(b.rot);
float corners[8][3] = {
{-1,-1,-1},{1,-1,-1},{1,1,-1},{-1,1,-1},
{-1,-1, 1},{1,-1, 1},{1,1, 1},{-1,1, 1}
};
int sx[8], sy[8]; bool vis[8]; float wz[8];
for (int i = 0; i < 8; i++) {
float lx = corners[i][0] * b.size, ly = corners[i][1] * b.size, lz = corners[i][2] * b.size;
float rx = lx * c + lz * sn; // rotate around Y
float rz = -lx * sn + lz * c;
float X = b.x + rx, Y = ly, Z = b.z + rz;
wz[i] = Z - camZ;
vis[i] = project(X, Y, Z, sx[i], sy[i]);
}
// Faces as quads of corner indices + local normals
static const int faces[6][4] = {
{0,1,2,3}, // -Z
{4,5,6,7}, // +Z
{0,3,7,4}, // -X
{1,2,6,5}, // +X
{0,1,5,4}, // -Y
{2,3,7,6}, // +Y
};
static const float normals[6][3] = {
{0,0,-1},{0,0,1},{-1,0,0},{1,0,0},{0,-1,0},{0,1,0}
};
// Light from above and slightly toward -Z
const float LX = -0.4f, LY = 0.85f, LZ = -0.35f;
// Depth-sort faces far -> near by average camera-space z
float fz[6]; int order[6];
for (int f = 0; f < 6; f++) {
fz[f] = 0;
for (int k = 0; k < 4; k++) fz[f] += wz[faces[f][k]];
fz[f] /= 4.0f;
order[f] = f;
}
for (int a = 1; a < 6; a++) { // insertion sort, descending
int v = order[a], j = a - 1;
while (j >= 0 && fz[order[j]] < fz[v]) { order[j + 1] = order[j]; j--; }
order[j + 1] = v;
}
for (int oi = 0; oi < 6; oi++) {
int f = order[oi];
bool ok = true;
for (int k = 0; k < 4; k++) if (!vis[faces[f][k]]) { ok = false; break; }
if (!ok) continue;
// rotate the face normal around Y for lighting
float nx = normals[f][0] * c + normals[f][2] * sn;
float nz = -normals[f][0] * sn + normals[f][2] * c;
float ndl = nx * LX + normals[f][1] * LY + nz * LZ;
if (ndl < 0.25f) ndl = 0.25f;
uint32_t col = dimColor(b.color, ndl * fog);
const int *q = faces[f];
fillQuad((float)sx[q[0]], (float)sy[q[0]],
(float)sx[q[1]], (float)sy[q[1]],
(float)sx[q[2]], (float)sy[q[2]],
(float)sx[q[3]], (float)sy[q[3]], col);
}
// Bright TRON wireframe on top of the filled faces
uint32_t edge = dimColor(b.color, 0.4f + 0.6f * fog);
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], bb = edges[e][1];
if (vis[a] && vis[bb]) drawLine(sx[a], sy[a], sx[bb], sy[bb], edge);
}
}
// --- Billboard entity: glow sphere scaled by true perspective ---------------
static void drawEntity(const Entity &e) {
float relz = e.z - camZ;
if (relz < NEAR_Z) return;
float fog = 1.0f - relz / FAR_Z;
if (fog < 0.25f) fog = 0.25f; // don't pop in as black blobs at the far plane
int sx, sy;
if (!project(e.x, e.y, e.z, sx, sy)) return;
// world radius 0.28 -> screen radius = 0.28 * FX / relz
int r = (int)(0.28f * FX / relz);
if (r < 2) r = 2;
if (r > 28) r = 28;
uint32_t core = dimColor(e.color, fog);
// glow (semi-transparent halo against the cleared background)
fillCircle(sx, sy, r + 2 + r / 4, (dimColor(e.color, 0.5f * fog) & 0x00FFFFFF) | 0x40000000);
fillCircle(sx, sy, r, core);
// trail line down to the floor
int fx, fy;
if (project(e.x, 0, e.z, fx, fy)) {
drawLine(sx, sy, fx, fy, (core & 0x00FFFFFF) | 0x60000000);
}
}
// --- 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;
if (k == 'w') { flySpeed += 0.5f; if (flySpeed > 6.0f) flySpeed = 6.0f; }
if (k == 's') { flySpeed -= 0.5f; if (flySpeed < 0.5f) flySpeed = 0.5f; }
}
// Delta time: seconds since the previous frame.
static unsigned long lastMs = 0;
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)
// Camera: forward flight + gentle sway + height bob
swayT += dt * 0.4f;
bobT += dt * 1.3f;
camZ += flySpeed * dt;
camX = sinf(swayT) * 1.2f;
camY = 0.12f * sinf(bobT);
// Update world (all speeds in units per second)
for (int i = 0; i < NUM_BLOCKS; i++) {
blocks[i].rot += blocks[i].rotSpeed * dt;
// Respawn with a margin >= max block half-extent, so a cube can
// never straddle the camera near plane (its near corners would
// project behind the camera and its faces would vanish).
if (blocks[i].z - camZ < NEAR_Z + 1.2f) {
respawnBlock(blocks[i], FAR_Z - 2.0f, FAR_Z);
}
}
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 + flySpeed) * dt; // world drift + camera approach
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 - camZ < NEAR_Z) {
respawnEntity(ents[i], FAR_Z - 1.0f, FAR_Z);
}
}
// Clear framebuffer to deep blue-black
for (int i = 0; i < W * H; i++) emuGfx::fb[i] = 0xFF080018;
// --- Floor scanlines (cyan grid on dark), scrolled in world space ---
for (int y = HORIZON + 1; y < H; y++) {
float d = K / (float)(y - HORIZON);
if (d > FAR_Z) d = FAR_Z;
float worldZ = camZ + d;
float fzfrac = fabsf(worldZ - floorf(worldZ + 0.5f));
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;
uint32_t gridCol = (0xFFu << 24) | ((uint32_t)v << 8) | ((uint32_t)v << 16);
uint32_t bgCol = 0xFF000010u;
for (int x = 0; x < W; x++) {
float wx = (x - 160) * d / FX + camX;
float fx = fabsf(wx - floorf(wx + 0.5f));
bool onGrid = (fx < 0.06f) || (fzfrac < 0.06f);
emuGfx::fb[y * W + x] = onGrid ? gridCol : bgCol;
}
}
// --- Ceiling scanlines (magenta grid), scrolled in world space ---
for (int y = 0; y < HORIZON; y++) {
float dy = (float)(HORIZON - y);
if (dy < 1) dy = 1;
float d = K / dy;
if (d > FAR_Z) d = FAR_Z;
float worldZ = camZ + d;
float fzfrac = fabsf(worldZ - floorf(worldZ + 0.5f));
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;
uint32_t gridCol = (0xFFu << 24) | ((uint32_t)v << 0) | ((uint32_t)v << 16);
uint32_t bgCol = 0xFF040008;
for (int x = 0; x < W; x++) {
float wx = (x - 160) * d / FX + camX;
float fx = fabsf(wx - floorf(wx + 0.5f));
bool onGrid = (fx < 0.06f) || (fzfrac < 0.06f);
emuGfx::fb[y * W + x] = onGrid ? gridCol : bgCol;
}
}
// --- Walls (left/right/back) as wireframe grids, camera-relative ---
int prevLX=0, prevLYf=0, prevLYc=0, prevRX=0, prevRYf=0, prevRYc=0;
bool first = true;
for (float z = camZ + NEAR_Z; z <= camZ + 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;
drawLine(lx, lyf, lx, lyc, 0xFF4040FF);
drawLine(rx, ryf, rx, ryc, 0xFF4040FF);
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
{
float z = camZ + FAR_Z;
int x0,y0,x1,y1;
if (project(-WALL_X,0,z,x0,y0) && project(WALL_X,0,z,x1,y1)) drawLine(x0,y0,x1,y1,0xFF303080);
if (project(-WALL_X,CEIL_H,z,x0,y0) && project(WALL_X,CEIL_H,z,x1,y1)) drawLine(x0,y0,x1,y1,0xFF303080);
if (project(-WALL_X,0,z,x0,y0) && project(-WALL_X,CEIL_H,z,x1,y1)) drawLine(x0,y0,x1,y1,0xFF303080);
if (project(WALL_X,0,z,x0,y0) && project(WALL_X,CEIL_H,z,x1,y1)) drawLine(x0,y0,x1,y1,0xFF303080);
}
// --- Horizon line ---
for (int x = 0; x < W; x++) emuGfx::fb[HORIZON * W + x] = 0xFF404040;
// --- Depth-sorted renderables: far blocks and entities first ---
struct RenderItem { float relz; bool isEnt; int idx; };
static RenderItem items[NUM_BLOCKS + NUM_ENTS];
int n = 0;
for (int i = 0; i < NUM_BLOCKS; i++) {
float rz = blocks[i].z - camZ;
if (rz < NEAR_Z || rz > FAR_Z) continue;
items[n++] = { rz, false, i };
}
for (int i = 0; i < NUM_ENTS; i++) {
float rz = ents[i].z - camZ;
if (rz < NEAR_Z || rz > FAR_Z) continue;
items[n++] = { rz, true, i };
}
for (int a = 1; a < n; a++) { // insertion sort, descending depth
RenderItem v = items[a]; int j = a - 1;
while (j >= 0 && items[j].relz < v.relz) { items[j + 1] = items[j]; j--; }
items[j + 1] = v;
}
for (int i = 0; i < n; i++) {
if (items[i].isEnt) drawEntity(ents[items[i].idx]);
else drawCube(blocks[items[i].idx]);
}
emuGfx::dirty = true;
}