Rename Lotus3 to MiataDrive; original-graphics title screen
- examples/Lotus3 -> examples/MiataDrive, sketch MiataDrive.ino, emulator target APP=MiataDrive, platformio src_dir updated - drop the borrowed photo title background (title_bg.h): the title screen now renders the game's own start line under the arch with the selected car parked on the road; color picker labels sit over the horizon, showcase car doubles as the live preview - add dedicated README (controls, features, sprite pipeline, gallery) - commit in-progress work the game now depends on: sound engine events (engine hum, crash noise) plus the 4-line SDL audio shim in the emulator host
This commit is contained in:
@@ -0,0 +1,975 @@
|
||||
/**
|
||||
* @file MiataDrive.ino
|
||||
* @brief MiataDrive - Lotus Turbo Challenge style pseudo-3D racer for LilyGo T-Deck.
|
||||
*
|
||||
* Classic segment-based pseudo-3D road: track = list of (curve, hill)
|
||||
* segments projected with perspective. Road is drawn near->far with rumble
|
||||
* strips, lane markers and alternating shades that scroll with distance.
|
||||
* Roadside scenery and traffic are depth-scaled sprites drawn far->near,
|
||||
* clipped behind hill crests. Centrifugal force pulls you wide in curves.
|
||||
*
|
||||
* Controls:
|
||||
* Trackball / arrow keys : steer (left/right), gas (up), brake (down)
|
||||
* W / S : gas on / brake pulse A / D : steer
|
||||
* Enter / click : start / restart P : toggle auto-play
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <SPI.h>
|
||||
#include <TFT_eSPI.h>
|
||||
#include <Wire.h>
|
||||
#include <math.h>
|
||||
#include "utilities.h"
|
||||
#include "sprites.h"
|
||||
#include "sound_engine.h"
|
||||
|
||||
TFT_eSPI tft;
|
||||
SoundEngine sound;
|
||||
|
||||
static int scrW, scrH;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tunables
|
||||
// ---------------------------------------------------------------------------
|
||||
static const uint32_t FRAME_MS = 33; // ~30 fps
|
||||
static const int SEG_LEN = 200; // segment length (world units)
|
||||
static const int RUMBLE_SEGS = 3; // segments per rumble stripe
|
||||
static const int DRAW_DIST = 90; // segments drawn ahead
|
||||
static const float ROAD_W = 1000.0f; // road half-width (world units)
|
||||
static const float CAM_H = 1500.0f; // camera height above road
|
||||
static const float CAM_D = 0.84f; // 1/tan(fov/2), fov ~100 deg
|
||||
static const float CENTRIFUGAL = 0.28f;
|
||||
static const float MAX_SPEED = SEG_LEN * 60.0f;
|
||||
static const float ACCEL = MAX_SPEED / 4.5f;
|
||||
static const float BRAKE = -MAX_SPEED * 1.2f;
|
||||
static const float DECEL = -MAX_SPEED / 5.0f;
|
||||
static const float OFF_DECEL = -MAX_SPEED / 1.5f;
|
||||
static const float OFF_LIMIT = MAX_SPEED / 4.0f;
|
||||
static const int LAPS = 3;
|
||||
static const float LAP_TIME = 75.0f;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Track
|
||||
// ---------------------------------------------------------------------------
|
||||
struct Segment {
|
||||
float curve;
|
||||
float y1, y2; // road elevation at segment start / end
|
||||
float clip; // screen y: sprite rows below this are hidden
|
||||
uint8_t spriteType[2];
|
||||
int8_t spriteOff[2]; // lateral offset in 1/8 road-half units
|
||||
uint8_t spriteCount;
|
||||
};
|
||||
|
||||
static const int MAX_SEGS = 1500;
|
||||
static Segment segments[MAX_SEGS];
|
||||
static int segCount = 0;
|
||||
static float trackLen = 0;
|
||||
|
||||
// player views per color: 0 rear, 1 slight-turn, 2 turn, 3 side
|
||||
enum { PV_REAR = 0, PV_SLIGHT, PV_TURN, PV_SIDE };
|
||||
enum { SID_PLAYER_RED = 0, SID_PLAYER_BLUE = 4, SID_PLAYER_WHITE = 8, SID_PLAYER_YELLOW = 12,
|
||||
SID_PALM = 16, SID_PINE, SID_BUSH, SID_BILLBOARD, SID_ARCH, SID_TIRES,
|
||||
SID_CAR_BLUE, SID_CAR_BLUE_T, SID_CAR_WHITE, SID_CAR_WHITE_T,
|
||||
SID_CAR_YELLOW, SID_CAR_YELLOW_T };
|
||||
|
||||
enum PlayerColor { PC_RED = 0, PC_BLUE = 1, PC_WHITE = 2, PC_YELLOW = 3 };
|
||||
static int playerColor = PC_RED;
|
||||
static inline int playerSprite(int view) { return playerColor * 4 + view; }
|
||||
|
||||
static float lastY() { return segCount ? segments[segCount - 1].y2 : 0.0f; }
|
||||
|
||||
static void addSegment(float curve, float y) {
|
||||
if (segCount >= MAX_SEGS) return;
|
||||
Segment &s = segments[segCount];
|
||||
s.curve = curve;
|
||||
s.y1 = lastY();
|
||||
s.y2 = y;
|
||||
s.clip = 0;
|
||||
s.spriteCount = 0;
|
||||
segCount++;
|
||||
}
|
||||
|
||||
static float easeIn(float a, float b, float p) { return a + (b - a) * p * p; }
|
||||
static float easeInOut(float a, float b, float p) { return a + (b - a) * (-cosf(p * 3.14159265f) / 2 + 0.5f); }
|
||||
|
||||
static void addRoad(int enter, int hold, int leave, float curve, float hillY) {
|
||||
float startY = lastY();
|
||||
float endY = startY + hillY * SEG_LEN;
|
||||
int total = enter + hold + leave;
|
||||
for (int i = 0; i < enter; i++)
|
||||
addSegment(easeIn(0, curve, (float)i / enter), easeInOut(startY, endY, (float)i / total));
|
||||
for (int i = 0; i < hold; i++)
|
||||
addSegment(curve, easeInOut(startY, endY, (float)(enter + i) / total));
|
||||
for (int i = 0; i < leave; i++)
|
||||
addSegment(easeInOut(curve, 0, (float)i / leave), easeInOut(startY, endY, (float)(enter + hold + i) / total));
|
||||
}
|
||||
|
||||
static void addSprite(int segIdx, int type, float offRoadHalves) {
|
||||
if (segIdx < 0 || segIdx >= segCount) return;
|
||||
Segment &s = segments[segIdx];
|
||||
if (s.spriteCount >= 2) return;
|
||||
s.spriteType[s.spriteCount] = (uint8_t)type;
|
||||
s.spriteOff[s.spriteCount] = (int8_t)(offRoadHalves * 8);
|
||||
s.spriteCount++;
|
||||
}
|
||||
|
||||
static void addScenery(int segIdx, int type, float side) {
|
||||
float off = side * (1.3f + (float)random(220) / 100.0f);
|
||||
addSprite(segIdx, type, off);
|
||||
}
|
||||
|
||||
static void buildTrack() {
|
||||
segCount = 0;
|
||||
addRoad(40, 40, 40, 0, 0); // start straight
|
||||
addRoad(30, 50, 30, 2, 0); // gentle right
|
||||
addRoad(30, 40, 30, -3, 10); // left, slight rise
|
||||
addRoad(40, 60, 40, 4, -20); // long right, downhill
|
||||
addRoad(30, 30, 30, 0, 30); // climb
|
||||
addRoad(30, 50, 30, -5, 0); // hard left over the crest
|
||||
addRoad(40, 40, 40, 0, -30); // descend
|
||||
addRoad(25, 35, 25, 3, 0); // S bends
|
||||
addRoad(25, 35, 25, -3, 0);
|
||||
addRoad(40, 70, 40, 5, 20); // long right sweeper, uphill
|
||||
addRoad(30, 30, 30, 0, -6); // downhill straight (tuned to close the elevation loop)
|
||||
addRoad(30, 60, 30, -4, 0); // long left
|
||||
addRoad(20, 20, 20, 6, 0); // tight right
|
||||
addRoad(40, 40, 40, 0, 0); // finish straight
|
||||
trackLen = segCount * (float)SEG_LEN;
|
||||
|
||||
addSprite(2, SID_ARCH, 0.0f); // start/finish gantry
|
||||
|
||||
for (int n = 8; n < segCount - 8; n++) {
|
||||
float c = fabsf(segments[n].curve);
|
||||
if (n % 9 == 0) addScenery(n, (random(10) < 5) ? SID_PALM : SID_PINE, -1.0f);
|
||||
if (n % 9 == 4) addScenery(n, (random(10) < 5) ? SID_PINE : SID_PALM, 1.0f);
|
||||
if (n % 17 == 0) addScenery(n, SID_BUSH, (random(2) ? -1.0f : 1.0f));
|
||||
if (n % 53 == 0) addScenery(n, SID_BILLBOARD, (n % 2) ? -1.8f : 1.8f);
|
||||
if (c > 3.5f && n % 14 == 0) addScenery(n, SID_TIRES, (segments[n].curve > 0) ? -1.15f : 1.15f);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Game state
|
||||
// ---------------------------------------------------------------------------
|
||||
enum GameState { ST_TITLE, ST_PLAYING, ST_CRASH, ST_GAMEOVER, ST_WIN, ST_SPRITES };
|
||||
static GameState gameState = ST_TITLE;
|
||||
static uint32_t stateT0 = 0;
|
||||
static uint32_t nextFrame = 0;
|
||||
|
||||
static float position_ = 0;
|
||||
static float playerX = 0;
|
||||
static float speed_ = 0;
|
||||
static float timeLeft = LAP_TIME;
|
||||
static int lap = 0;
|
||||
static int score = 0;
|
||||
static bool autoPlay =
|
||||
#ifdef AUTOPLAY
|
||||
true;
|
||||
#else
|
||||
false;
|
||||
#endif
|
||||
;
|
||||
|
||||
// sound cooldowns
|
||||
static uint32_t sndAccelT = 0;
|
||||
#ifdef EMULATOR
|
||||
extern bool emuAutoplay;
|
||||
#endif
|
||||
static uint32_t sndSkidT = 0;
|
||||
// steering click tracking for skid trigger
|
||||
static uint32_t turnClickT = 0;
|
||||
static int turnClicks = 0;
|
||||
static void registerTurn() {
|
||||
uint32_t now = millis();
|
||||
if (now - turnClickT > 350) turnClicks = 0;
|
||||
turnClicks++;
|
||||
turnClickT = now;
|
||||
}
|
||||
|
||||
// crash / rollover
|
||||
static uint32_t crashT0 = 0;
|
||||
static int crashDir = 1; // slide direction off the road
|
||||
static float crashVel = 0; // sliding speed during the tumble
|
||||
static uint32_t shakeUntil = 0; // camera jolt
|
||||
|
||||
struct TrafficCar { float z, offset, speed; int sprite, spriteTurn; };
|
||||
static const int N_CARS = 8;
|
||||
static TrafficCar cars[N_CARS];
|
||||
|
||||
// manual input state
|
||||
static float steerInput = 0;
|
||||
static int gasLatch = 0; // W = 1
|
||||
static uint32_t brakeUntil = 0;
|
||||
static int gasFrame = 0; // resolved each frame: 1 gas, -1 brake
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Input: trackball
|
||||
// ---------------------------------------------------------------------------
|
||||
static volatile uint32_t tbEdges[4];
|
||||
static volatile uint32_t tbClicks;
|
||||
static void IRAM_ATTR tbIsrRight() { tbEdges[0]++; }
|
||||
static void IRAM_ATTR tbIsrUp() { tbEdges[1]++; }
|
||||
static void IRAM_ATTR tbIsrLeft() { tbEdges[2]++; }
|
||||
static void IRAM_ATTR tbIsrDown() { tbEdges[3]++; }
|
||||
static void IRAM_ATTR tbIsrClick() { tbClicks++; }
|
||||
|
||||
static const int TB_FP = 8;
|
||||
#ifdef EMULATOR
|
||||
static const int TB_IMPULSE = 6;
|
||||
static const int TB_FRICTION = 12;
|
||||
#else
|
||||
static const int TB_IMPULSE = 24;
|
||||
static const int TB_FRICTION = 15;
|
||||
#endif
|
||||
static const int TB_VMAX = 48 << TB_FP;
|
||||
static int32_t tbVelX, tbVelY, tbRemX, tbRemY;
|
||||
|
||||
static void attachTrackball() {
|
||||
const uint8_t tbPins[5] = { BOARD_TBOX_G02, BOARD_TBOX_G01, BOARD_TBOX_G04, BOARD_TBOX_G03, BOARD_BOOT_PIN };
|
||||
for (int i = 0; i < 5; i++) pinMode(tbPins[i], INPUT_PULLUP);
|
||||
attachInterrupt(digitalPinToInterrupt(tbPins[0]), tbIsrRight, FALLING);
|
||||
attachInterrupt(digitalPinToInterrupt(tbPins[1]), tbIsrUp, FALLING);
|
||||
attachInterrupt(digitalPinToInterrupt(tbPins[2]), tbIsrLeft, FALLING);
|
||||
attachInterrupt(digitalPinToInterrupt(tbPins[3]), tbIsrDown, FALLING);
|
||||
attachInterrupt(digitalPinToInterrupt(tbPins[4]), tbIsrClick, FALLING);
|
||||
}
|
||||
|
||||
static void resetTrackball() {
|
||||
for (int i = 0; i < 4; i++) tbEdges[i] = 0;
|
||||
tbClicks = 0; tbVelX = tbVelY = tbRemX = tbRemY = 0;
|
||||
}
|
||||
|
||||
static void applyTrackball(int &pxX, int &pxY, uint32_t &clicks) {
|
||||
uint32_t e[4];
|
||||
for (int i = 0; i < 4; i++) { e[i] = tbEdges[i]; tbEdges[i] = 0; }
|
||||
clicks = tbClicks; tbClicks = 0;
|
||||
tbVelX += ((int32_t)e[0] - (int32_t)e[2]) * TB_IMPULSE;
|
||||
tbVelY += ((int32_t)e[3] - (int32_t)e[1]) * TB_IMPULSE;
|
||||
if (tbVelX > TB_VMAX) tbVelX = TB_VMAX;
|
||||
if (tbVelX < -TB_VMAX) tbVelX = -TB_VMAX;
|
||||
if (tbVelY > TB_VMAX) tbVelY = TB_VMAX;
|
||||
if (tbVelY < -TB_VMAX) tbVelY = -TB_VMAX;
|
||||
tbVelX = tbVelX * TB_FRICTION / 16;
|
||||
tbVelY = tbVelY * TB_FRICTION / 16;
|
||||
tbRemX += tbVelX; tbRemY += tbVelY;
|
||||
pxX = tbRemX / TB_FP; pxY = tbRemY / TB_FP;
|
||||
tbRemX -= pxX * TB_FP; tbRemY -= pxY * TB_FP;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Colors / palette (with distance fog)
|
||||
// ---------------------------------------------------------------------------
|
||||
static uint16_t C(uint8_t r, uint8_t g, uint8_t b) {
|
||||
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
|
||||
}
|
||||
static uint16_t palRoad[2][3], palGrassL[3], palGrassD[3], palRumL[3], palRumD[3], palLane[3];
|
||||
static uint16_t colSkyHi, colSkyLo;
|
||||
|
||||
static void buildPalette() {
|
||||
colSkyHi = C(70, 130, 220); colSkyLo = C(120, 175, 240);
|
||||
// [light band][fog 0..2]
|
||||
palRoad[0][0] = C(102,102,102); palRoad[1][0] = C(96, 96, 96);
|
||||
palRoad[0][1] = C(128,132,130); palRoad[1][1] = C(122,126,124);
|
||||
palRoad[0][2] = C(150,165,190); palRoad[1][2] = C(146,161,186);
|
||||
palGrassL[0] = C(26,148,54); palGrassD[0] = C(18,118,42);
|
||||
palGrassL[1] = C(70,152,96); palGrassD[1] = C(58,132,84);
|
||||
palGrassL[2] = C(115,165,165);palGrassD[2] = C(104,152,152);
|
||||
palRumL[0] = C(255,255,255); palRumD[0] = C(205,40,40);
|
||||
palRumL[1] = C(235,235,235); palRumD[1] = C(205,120,120);
|
||||
palRumL[2] = C(215,220,225); palRumD[2] = C(205,165,165);
|
||||
palLane[0] = C(255,255,255); palLane[1] = C(235,235,235); palLane[2] = C(215,220,225);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Draw primitives
|
||||
// ---------------------------------------------------------------------------
|
||||
static inline int iround(float v) { return (int)(v + (v >= 0 ? 0.5f : -0.5f)); }
|
||||
|
||||
static void fillSpan(int y, float xa, float xb, uint16_t c) {
|
||||
if (y < 0 || y >= scrH) return;
|
||||
int a = iround(xa), b = iround(xb);
|
||||
if (b < a) { int t = a; a = b; b = t; }
|
||||
if (b < 0 || a >= scrW) return;
|
||||
if (a < 0) a = 0;
|
||||
if (b >= scrW) b = scrW - 1;
|
||||
tft.drawFastHLine(a, y, b - a + 1, c);
|
||||
}
|
||||
|
||||
static void fillTrap(float y1, float xa1, float xb1, float y2, float xa2, float xb2, uint16_t c) {
|
||||
if (y1 == y2) { fillSpan(iround(y1), xa1, xb1, c); return; }
|
||||
int yTop = (int)ceilf(y1 < y2 ? y1 : y2);
|
||||
int yBot = (int)floorf(y1 < y2 ? y2 : y1);
|
||||
for (int y = yTop; y <= yBot; y++) {
|
||||
float t = ((float)y - y1) / (y2 - y1);
|
||||
fillSpan(y, xa1 + (xa2 - xa1) * t, xb1 + (xb2 - xb1) * t, c);
|
||||
}
|
||||
}
|
||||
|
||||
// scaled sprite, bottom-center anchor, rows below clipY are cut (hill occlusion)
|
||||
static void drawSprite(int id, int destW, float sx, float bottomY, float clipY, bool flip = false) {
|
||||
const GameSprite &sp = SPRITES[id];
|
||||
if (destW < 1) return;
|
||||
int dw = destW;
|
||||
int dh = (int)(destW * sp.h / sp.w); if (dh < 1) dh = 1;
|
||||
int x0 = iround(sx) - dw / 2;
|
||||
int yBase = iround(bottomY);
|
||||
int clip = iround(clipY);
|
||||
if (x0 >= scrW || x0 + dw <= 0) return;
|
||||
for (int y = 0; y < dh; y++) {
|
||||
int dy = yBase - dh + y; // bottom-up
|
||||
if (dy > clip) continue; // hidden behind nearer geometry / crest
|
||||
if (dy < 0 || dy >= scrH) continue;
|
||||
const uint16_t *row = sp.data + (y * sp.h / dh) * sp.w;
|
||||
int lastC = -2, runStart = 0;
|
||||
for (int x = 0; x <= dw; x++) {
|
||||
uint16_t c = (x < dw) ? row[(flip ? (dw - 1 - x) : x) * sp.w / dw] : (uint16_t)0;
|
||||
bool trans = (x == dw) || (c == SPR_TRANSP);
|
||||
if (!trans) {
|
||||
if (c != lastC) {
|
||||
if (lastC >= 0) {
|
||||
int dx0 = x0 + runStart, wln = x - runStart;
|
||||
if (dx0 < scrW && dx0 + wln > 0) tft.fillRect(dx0, dy, wln, 1, (uint16_t)lastC);
|
||||
}
|
||||
runStart = x; lastC = c;
|
||||
}
|
||||
} else {
|
||||
if (lastC >= 0) {
|
||||
int dx0 = x0 + runStart, wln = x - runStart;
|
||||
if (dx0 < scrW && dx0 + wln > 0) tft.fillRect(dx0, dy, wln, 1, (uint16_t)lastC);
|
||||
}
|
||||
lastC = -2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Projection + road render
|
||||
// ---------------------------------------------------------------------------
|
||||
struct Proj { float x, y, w; };
|
||||
static Proj P1[DRAW_DIST + 2];
|
||||
static Proj P2[DRAW_DIST + 2];
|
||||
static int segIdxN[DRAW_DIST + 2];
|
||||
static bool slotValid[DRAW_DIST + 2];
|
||||
|
||||
static void renderRoad() {
|
||||
// LOW horizon (OutRun-style) -> camera feels planted on the road
|
||||
const float HORIZON_Y = scrH * 0.36f;
|
||||
// sky down to just past the vanishing point
|
||||
int skyBot = (int)HORIZON_Y + 14;
|
||||
for (int y = 0; y < skyBot; y++) {
|
||||
uint16_t c = (y < skyBot * 2 / 5) ? colSkyHi : colSkyLo;
|
||||
tft.drawFastHLine(0, y, scrW, c);
|
||||
}
|
||||
|
||||
float basePercent = fmodf(position_, SEG_LEN) / SEG_LEN;
|
||||
int baseIdx = ((int)(position_ / SEG_LEN)) % segCount;
|
||||
const Segment &bs = segments[baseIdx];
|
||||
float camY = CAM_H + bs.y1 + (bs.y2 - bs.y1) * basePercent;
|
||||
float camX = playerX * ROAD_W;
|
||||
// whiplash camera jolt
|
||||
if ((int32_t)(millis() - shakeUntil) < 0) camX += (float)(random(201) - 100);
|
||||
|
||||
float x = 0;
|
||||
float dx = -(bs.curve * basePercent);
|
||||
float maxY = (float)scrH;
|
||||
|
||||
for (int n = 0; n < DRAW_DIST; n++) {
|
||||
int idx = (baseIdx + n) % segCount;
|
||||
bool looped = idx < baseIdx;
|
||||
float camZ = position_ - (looped ? trackLen : 0);
|
||||
Segment &seg = segments[idx];
|
||||
|
||||
float z1 = idx * (float)SEG_LEN - camZ;
|
||||
float z2 = z1 + SEG_LEN;
|
||||
|
||||
// clamp near plane so the road reaches the bottom of the screen
|
||||
// (avoids a gap where the camera's own segment is skipped)
|
||||
float z1p = z1;
|
||||
float xn = x;
|
||||
const float NEAR_Z = CAM_D * 30.0f;
|
||||
if (z1p < NEAR_Z) {
|
||||
float frac = (NEAR_Z - z1) / SEG_LEN;
|
||||
if (frac > 1.0f) frac = 1.0f;
|
||||
z1p = NEAR_Z;
|
||||
xn = x + dx * frac;
|
||||
}
|
||||
|
||||
// project p1/p2 (curve accumulated into camera x)
|
||||
float s1 = CAM_D / z1p;
|
||||
float s2 = CAM_D / z2;
|
||||
P1[n].x = scrW / 2.0f + s1 * (0 - (camX - xn)) * scrW / 2.0f;
|
||||
P1[n].y = HORIZON_Y - s1 * (seg.y1 + (seg.y2 - seg.y1) * ((z1p - z1) / SEG_LEN) - camY) * scrH / 2.0f;
|
||||
P1[n].w = s1 * ROAD_W * scrW / 2.0f;
|
||||
float x2 = x + dx; // p2 camera x offset (curve)
|
||||
float camX2 = camX - x2;
|
||||
P2[n].x = scrW / 2.0f + s2 * (0 - camX2) * scrW / 2.0f;
|
||||
P2[n].y = HORIZON_Y - s2 * (seg.y2 - camY) * scrH / 2.0f;
|
||||
P2[n].w = s2 * ROAD_W * scrW / 2.0f;
|
||||
|
||||
seg.clip = maxY;
|
||||
segIdxN[n] = idx;
|
||||
slotValid[n] = (z1 > NEAR_Z) && (z1 < DRAW_DIST * SEG_LEN * 2.0f);
|
||||
|
||||
x += dx;
|
||||
dx += seg.curve;
|
||||
|
||||
if (z2 <= NEAR_Z) continue; // fully behind camera
|
||||
if (P2[n].y >= maxY || P2[n].y >= P1[n].y) continue; // hidden or backfacing
|
||||
|
||||
int fog = 0;
|
||||
if (n > DRAW_DIST * 3 / 4) fog = 2;
|
||||
else if (n > DRAW_DIST / 2) fog = 1;
|
||||
bool light = ((idx / RUMBLE_SEGS) % 2) == 0;
|
||||
|
||||
// grass band
|
||||
uint16_t grass = light ? palGrassL[fog] : palGrassD[fog];
|
||||
int yTop = iround(P2[n].y), yBot = iround(P1[n].y) - 1;
|
||||
for (int y = yTop; y <= yBot; y++)
|
||||
if (y < maxY) tft.drawFastHLine(0, y, scrW, grass);
|
||||
|
||||
// rumble strips (wide, for speed sensation)
|
||||
float r1 = P1[n].w / 6.0f, r2 = P2[n].w / 6.0f;
|
||||
uint16_t rumble = light ? palRumL[fog] : palRumD[fog];
|
||||
fillTrap(P1[n].y, P1[n].x - P1[n].w - r1, P1[n].x - P1[n].w,
|
||||
P2[n].y, P2[n].x - P2[n].w - r2, P2[n].x - P2[n].w, rumble);
|
||||
fillTrap(P1[n].y, P1[n].x + P1[n].w + r1, P1[n].x + P1[n].w,
|
||||
P2[n].y, P2[n].x + P2[n].w + r2, P2[n].x + P2[n].w, rumble);
|
||||
|
||||
// road surface
|
||||
fillTrap(P1[n].y, P1[n].x - P1[n].w, P1[n].x + P1[n].w,
|
||||
P2[n].y, P2[n].x - P2[n].w, P2[n].x + P2[n].w, palRoad[light ? 0 : 1][fog]);
|
||||
|
||||
// dashed center line on light bands
|
||||
if (light) {
|
||||
float l1 = P1[n].w / 22.0f, l2 = P2[n].w / 22.0f;
|
||||
fillTrap(P1[n].y, P1[n].x - l1, P1[n].x + l1,
|
||||
P2[n].y, P2[n].x - l2, P2[n].x + l2, palLane[fog]);
|
||||
}
|
||||
|
||||
maxY = P2[n].y;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sprites (far -> near)
|
||||
// ---------------------------------------------------------------------------
|
||||
static void renderSprites() {
|
||||
for (int n = DRAW_DIST - 1; n >= 1; n--) {
|
||||
if (!slotValid[n]) continue;
|
||||
int idx = segIdxN[n];
|
||||
const Proj &pr = P1[n];
|
||||
Segment &seg = segments[idx];
|
||||
|
||||
for (int si = 0; si < seg.spriteCount; si++) {
|
||||
int type = seg.spriteType[si];
|
||||
float off = seg.spriteOff[si] / 8.0f;
|
||||
float worldW;
|
||||
switch (type) {
|
||||
case SID_PALM: worldW = 1.1f; break;
|
||||
case SID_PINE: worldW = 1.0f; break;
|
||||
case SID_BUSH: worldW = 0.45f; break;
|
||||
case SID_BILLBOARD: worldW = 1.5f; break;
|
||||
case SID_ARCH: worldW = 4.6f; break;
|
||||
case SID_TIRES: worldW = 0.5f; break;
|
||||
default: worldW = 1.0f; break;
|
||||
}
|
||||
float sx = pr.x + off * pr.w;
|
||||
drawSprite(type, iround(worldW * pr.w), sx, pr.y, seg.clip);
|
||||
}
|
||||
|
||||
// traffic cars in this segment
|
||||
for (int c = 0; c < N_CARS; c++) {
|
||||
int carSeg = (int)(cars[c].z / SEG_LEN) % segCount;
|
||||
if (carSeg != idx) continue;
|
||||
float percent = fmodf(cars[c].z, SEG_LEN) / SEG_LEN;
|
||||
const Proj &pn = (n + 1 < DRAW_DIST && slotValid[n + 1]) ? P1[n + 1] : pr;
|
||||
float sx = pr.x + (pn.x - pr.x) * percent + cars[c].offset * pr.w;
|
||||
float sy = pr.y + (pn.y - pr.y) * percent;
|
||||
float w = pr.w + (pn.w - pr.w) * percent;
|
||||
// lean into corners: turning 3/4 view, mirrored on right-hand curves
|
||||
float cv = segments[idx].curve;
|
||||
int sid = (fabsf(cv) > 1.5f) ? cars[c].spriteTurn : cars[c].sprite;
|
||||
drawSprite(sid, iround(w * 0.48f), sx, sy, seg.clip, cv > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void drawPlayerCar() {
|
||||
const int CAR_W = 64; // player car width on screen (px)
|
||||
float speedPct = speed_ / MAX_SPEED;
|
||||
float bounce = (float)(random(3) - 1) * speedPct * 1.0f;
|
||||
float cx = scrW / 2.0f + steerInput * 5.0f;
|
||||
int baseY = scrH - 3 + (int)bounce;
|
||||
|
||||
// dirt rushing from the rear wheels while accelerating
|
||||
if (gasFrame > 0 && speed_ > MAX_SPEED * 0.15f) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
int side = (i < 5) ? -1 : 1;
|
||||
int dx0 = iround(cx) + side * (14 + (int)random(6));
|
||||
int dy0 = baseY - 2 - (int)random(14);
|
||||
int r = 1 + (int)random(3);
|
||||
uint8_t g = 110 + (uint8_t)random(60);
|
||||
tft.fillCircle(dx0, dy0, r, C(g, g - 20, g - 40));
|
||||
}
|
||||
// skid-like streaks when launching hard
|
||||
if (speedPct < 0.4f) {
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int side = (i < 2) ? -1 : 1;
|
||||
int x0 = iround(cx) + side * 16;
|
||||
tft.drawFastVLine(x0, baseY - 18, 12, C(150, 140, 120));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// contact shadow -> plants the car on the road
|
||||
for (int dy = 0; dy < 5; dy++) {
|
||||
int wdt = CAR_W - 6 - dy * 7;
|
||||
if (wdt > 0) tft.drawFastHLine(scrW / 2 - wdt / 2, baseY + dy, wdt, C(30, 30, 26));
|
||||
}
|
||||
float ta = fabsf(steerInput);
|
||||
int view = PV_REAR;
|
||||
if (ta > 0.75f) view = PV_TURN;
|
||||
else if (ta > 0.30f) view = PV_SLIGHT;
|
||||
bool flip = steerInput > 0; // sheet views face nose-left; mirror for right turns
|
||||
drawSprite(playerSprite(view), CAR_W, cx, baseY, scrH, flip);
|
||||
}
|
||||
|
||||
// rollover animation: spare car sprites tumbling off the road
|
||||
static void drawCrashCar() {
|
||||
uint32_t t = millis() - crashT0;
|
||||
const float DUR = 2300.0f;
|
||||
float p = t / DUR; if (p > 1) p = 1;
|
||||
// sprite sequence: rear -> slight -> turn -> side (rolling over)
|
||||
int id;
|
||||
if (t < 260) {
|
||||
id = playerSprite(PV_REAR);
|
||||
} else {
|
||||
int f = ((t - 260) / 140) % 3;
|
||||
id = playerSprite(PV_SLIGHT + f);
|
||||
}
|
||||
float cx = scrW / 2.0f + crashDir * p * 46.0f;
|
||||
if (t < 650) cx += (float)(random(7) - 3); // whiplash shake
|
||||
float hop = -sinf(p * 3.14159f) * 16.0f; // airborne arc
|
||||
int baseY = scrH - 3 + (int)hop;
|
||||
int w = 64 + (int)(sinf(p * 3.14159f) * 12.0f); // swells mid-tumble
|
||||
// dust kicked up opposite the slide
|
||||
for (int i = 0; i < 5; i++) {
|
||||
int dx0 = iround(cx) - crashDir * (28 + (int)random(26));
|
||||
int dy0 = baseY - (int)random(10);
|
||||
tft.fillCircle(dx0, dy0, 1 + (int)random(2), C(150, 140, 120));
|
||||
}
|
||||
drawSprite(id, w, cx, baseY, scrH, crashDir > 0);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HUD
|
||||
// ---------------------------------------------------------------------------
|
||||
static void drawHUD() {
|
||||
tft.setTextDatum(TL_DATUM);
|
||||
tft.setTextFont(2);
|
||||
tft.setTextColor(TFT_WHITE, C(15,15,18));
|
||||
char buf[48];
|
||||
snprintf(buf, sizeof(buf), "TIME %d", (int)ceilf(timeLeft));
|
||||
tft.drawString(buf, 6, 4);
|
||||
snprintf(buf, sizeof(buf), "LAP %d/%d", lap + 1 < 1 ? 1 : lap + 1, LAPS);
|
||||
tft.drawString(buf, 6, 22);
|
||||
tft.setTextDatum(TR_DATUM);
|
||||
snprintf(buf, sizeof(buf), "%d km/h", (int)(speed_ / 100.0f));
|
||||
tft.drawString(buf, scrW - 6, 4);
|
||||
tft.setTextDatum(TL_DATUM);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Simulation
|
||||
// ---------------------------------------------------------------------------
|
||||
static void placeTraffic() {
|
||||
const float lane[3] = { -0.66f, 0.0f, 0.66f };
|
||||
for (int i = 0; i < N_CARS; i++) {
|
||||
cars[i].z = (float)random((long)trackLen);
|
||||
cars[i].offset = lane[i % 3];
|
||||
cars[i].speed = MAX_SPEED * (0.25f + (float)random(30) / 100.0f);
|
||||
static const int carSets[3][2] = {
|
||||
{ SID_CAR_BLUE, SID_CAR_BLUE_T },
|
||||
{ SID_CAR_WHITE, SID_CAR_WHITE_T },
|
||||
{ SID_CAR_YELLOW, SID_CAR_YELLOW_T },
|
||||
};
|
||||
cars[i].sprite = carSets[i % 3][0];
|
||||
cars[i].spriteTurn = carSets[i % 3][1];
|
||||
}
|
||||
}
|
||||
|
||||
static void startGame() {
|
||||
position_ = 0; playerX = 0; speed_ = 0;
|
||||
timeLeft = LAP_TIME; lap = 0; score = 0;
|
||||
steerInput = 0; gasLatch = 0; brakeUntil = 0; // manual gas by default (no auto-throttle)
|
||||
placeTraffic();
|
||||
gameState = ST_PLAYING;
|
||||
stateT0 = millis();
|
||||
}
|
||||
|
||||
static float clampf(float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); }
|
||||
|
||||
static void updateGame(float dt) {
|
||||
int baseIdx = ((int)(position_ / SEG_LEN)) % segCount;
|
||||
const Segment &baseSeg = segments[baseIdx];
|
||||
float speedPct = speed_ / MAX_SPEED;
|
||||
|
||||
// --- sound triggers ---
|
||||
uint32_t now = millis();
|
||||
// continuous engine hum: frequency tracks speed (keep queue short for snappy SFX)
|
||||
if (speed_ > 10.0f && sound.pending() < 2 && (int32_t)(now - sndAccelT) >= 100) {
|
||||
sndAccelT = now;
|
||||
int f = 70 + (int)(speedPct * 170.0f);
|
||||
uint16_t amp = gasFrame > 0 ? 7000 : 4500;
|
||||
SndEvent e = { SND_TONE, (uint16_t)f, 0, 120, amp };
|
||||
sound.play(e);
|
||||
}
|
||||
bool skid = (turnClicks >= 3) && (fabsf(steerInput) > 0.55f) && (speedPct > 0.45f);
|
||||
if (skid && (int32_t)(now - sndSkidT) >= 600) {
|
||||
sndSkidT = now;
|
||||
turnClicks = 0;
|
||||
sound.clear();
|
||||
SndEvent e = { SND_SWEEP, 900, 300, 120, 9000 };
|
||||
sound.play(e);
|
||||
}
|
||||
float dx = dt * 2.4f * (speedPct > 0.18f ? speedPct : 0.18f); // steer authority grows with speed (min so steering works at low speed)
|
||||
|
||||
if (autoPlay) {
|
||||
// AI: aim inside of upcoming curve, dodge traffic
|
||||
float aheadCurve = 0;
|
||||
for (int k = 2; k < 22; k++)
|
||||
aheadCurve += segments[(baseIdx + k) % segCount].curve;
|
||||
float target = clampf(-aheadCurve * 0.035f, -0.8f, 0.8f);
|
||||
for (int c = 0; c < N_CARS; c++) {
|
||||
float rel = cars[c].z - position_;
|
||||
if (rel < 0) rel += trackLen;
|
||||
if (rel > 0 && rel < SEG_LEN * 14 && fabsf(cars[c].offset - playerX) < 0.55f)
|
||||
target = clampf(cars[c].offset + (cars[c].offset >= 0 ? -0.9f : 0.9f), -0.85f, 0.85f);
|
||||
}
|
||||
if (target > playerX) playerX += dx;
|
||||
else if (target < playerX) playerX -= dx;
|
||||
float maxA = (fabsf(aheadCurve) > 9.0f) ? 0.6f : 1.0f;
|
||||
speed_ += (speed_ < MAX_SPEED * maxA) ? ACCEL * dt : DECEL * dt;
|
||||
} else {
|
||||
playerX += dx * steerInput * 1.8f;
|
||||
if (gasFrame > 0) speed_ += ACCEL * dt;
|
||||
else if (gasFrame < 0) speed_ += BRAKE * dt;
|
||||
else speed_ += DECEL * dt;
|
||||
}
|
||||
|
||||
// centrifugal force in curves
|
||||
playerX -= dx * speedPct * baseSeg.curve * CENTRIFUGAL;
|
||||
|
||||
// off-road drag
|
||||
if ((playerX < -1.05f || playerX > 1.05f) && speed_ > OFF_LIMIT)
|
||||
speed_ += OFF_DECEL * dt;
|
||||
|
||||
// hard off-road excursion -> rollover crash (any speed above a crawl)
|
||||
if (fabsf(playerX) > 1.65f && speed_ > MAX_SPEED * 0.08f) {
|
||||
crashDir = (playerX > 0) ? 1 : -1;
|
||||
crashVel = speed_ * 0.45f;
|
||||
crashT0 = millis();
|
||||
shakeUntil = crashT0 + 700;
|
||||
score -= 300; if (score < 0) score = 0;
|
||||
speed_ = 0;
|
||||
gameState = ST_CRASH;
|
||||
// crash sound (clear queued hum so it plays immediately)
|
||||
sound.clear();
|
||||
{ SndEvent e = { SND_NOISE, 0, 0, 260, 22000 }; sound.play(e);
|
||||
SndEvent f = { SND_SWEEP, 400, 80, 220, 14000 }; sound.play(f); }
|
||||
return;
|
||||
}
|
||||
|
||||
playerX = clampf(playerX, -2.2f, 2.2f);
|
||||
if (speed_ < 0) speed_ = 0;
|
||||
if (speed_ > MAX_SPEED) speed_ = MAX_SPEED;
|
||||
|
||||
position_ += speed_ * dt;
|
||||
while (position_ >= trackLen) {
|
||||
position_ -= trackLen;
|
||||
lap++;
|
||||
timeLeft += 45.0f;
|
||||
score += 2000;
|
||||
if (lap >= LAPS) { gameState = ST_WIN; stateT0 = millis(); return; }
|
||||
}
|
||||
score += (int)(speed_ * dt * 0.02f);
|
||||
|
||||
for (int c = 0; c < N_CARS; c++) {
|
||||
cars[c].z += cars[c].speed * dt;
|
||||
if (cars[c].z >= trackLen) cars[c].z -= trackLen;
|
||||
float rel = cars[c].z - position_;
|
||||
if (rel < 0) rel += trackLen;
|
||||
if (rel < SEG_LEN * 0.9f && fabsf(cars[c].offset - playerX) < 0.30f) {
|
||||
speed_ = cars[c].speed * 0.6f;
|
||||
position_ = cars[c].z - SEG_LEN * 1.2f;
|
||||
if (position_ < 0) position_ += trackLen;
|
||||
shakeUntil = millis() + 250; // jolt on rear-ending traffic
|
||||
{ SndEvent e = { SND_NOISE, 0, 0, 120, 12000 }; sound.play(e); }
|
||||
}
|
||||
}
|
||||
|
||||
timeLeft -= dt;
|
||||
if (timeLeft <= 0) { timeLeft = 0; gameState = ST_GAMEOVER; stateT0 = millis(); }
|
||||
}
|
||||
|
||||
// rollover: slide, tumble through the spare car sprites, then rejoin
|
||||
static void updateCrash(float dt) {
|
||||
crashVel *= 0.90f;
|
||||
position_ += crashVel * dt;
|
||||
if (position_ >= trackLen) position_ -= trackLen;
|
||||
timeLeft -= dt;
|
||||
if (millis() - crashT0 > 2300) {
|
||||
playerX = crashDir * 0.55f; // recovered, back on the tarmac
|
||||
speed_ = 0;
|
||||
gasLatch = 1;
|
||||
gameState = ST_PLAYING;
|
||||
}
|
||||
if (timeLeft <= 0) { timeLeft = 0; gameState = ST_GAMEOVER; stateT0 = millis(); }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Screens
|
||||
// ---------------------------------------------------------------------------
|
||||
static void drawTitle() {
|
||||
// backdrop is our own scene: the start line under the arch
|
||||
position_ = 0; playerX = 0; speed_ = 0;
|
||||
renderRoad();
|
||||
renderSprites();
|
||||
|
||||
tft.setTextDatum(MC_DATUM);
|
||||
tft.setFreeFont(&FreeSansBold24pt7b);
|
||||
tft.setTextColor(TFT_YELLOW, C(15,15,18));
|
||||
tft.drawString("MIATADRIVE", scrW / 2, 14);
|
||||
tft.setFreeFont(nullptr);
|
||||
tft.setTextFont(2);
|
||||
tft.setTextColor(TFT_WHITE, C(15,15,18));
|
||||
tft.drawString("W gas S brake A/D steer", scrW / 2, 60);
|
||||
tft.drawString("P auto T sprites Press/tap: race", scrW / 2, 78);
|
||||
// car color picker: 1 Red 2 Blue 3 White 4 Yellow
|
||||
static const char* names[4] = { "1 Red", "2 Blue", "3 White", "4 Yellow" };
|
||||
uint16_t pal[4] = { C(220,40,40), C(60,90,220), C(235,235,235), C(240,200,40) };
|
||||
for (int i = 0; i < 4; i++) {
|
||||
tft.setTextColor(i == playerColor ? pal[i] : C(200,200,200), C(15,15,18));
|
||||
tft.setTextDatum(TC_DATUM);
|
||||
tft.drawString(names[i], 46 + i * 76, 102);
|
||||
if (i == playerColor) {
|
||||
tft.setTextColor(TFT_WHITE, C(15,15,18));
|
||||
tft.drawString("^", 46 + i * 76, 118);
|
||||
}
|
||||
}
|
||||
tft.setTextDatum(TL_DATUM);
|
||||
// showcase the selected car, parked on the road below the arch
|
||||
drawSprite(playerSprite(PV_REAR), 110, scrW / 2, scrH - 4, scrH);
|
||||
}
|
||||
|
||||
// sprite test gallery: every SPRITES[] entry at native size on a checkerboard,
|
||||
// bottom-center anchored like in-game, labeled with index + crop size
|
||||
static int spritePage = 0;
|
||||
|
||||
static void drawSpriteTest() {
|
||||
// checker background
|
||||
for (int by = 0; by < scrH; by += 8)
|
||||
for (int bx = 0; bx < scrW; bx += 8) {
|
||||
uint16_t c = (((bx / 8) + (by / 8)) & 1) ? C(70,70,74) : C(135,135,138);
|
||||
tft.fillRect(bx, by, 8, 8, c);
|
||||
}
|
||||
|
||||
// build list of sprite ids for this page
|
||||
int ids[12]; int nids = 0;
|
||||
if (spritePage < 4) {
|
||||
int color = spritePage; // 0..3
|
||||
ids[nids++] = color * 4 + PV_REAR;
|
||||
ids[nids++] = color * 4 + PV_SLIGHT;
|
||||
ids[nids++] = color * 4 + PV_TURN;
|
||||
} else if (spritePage == 4) {
|
||||
int arr[] = { SPR_CAR_BLUE, SPR_CAR_BLUE_T, SPR_CAR_WHITE, SPR_CAR_WHITE_T, SPR_CAR_YELLOW, SPR_CAR_YELLOW_T };
|
||||
for (int i = 0; i < 6; i++) ids[nids++] = arr[i];
|
||||
} else {
|
||||
int arr[] = { SPR_PALM, SPR_PINE, SPR_BUSH, SPR_BILLBOARD, SPR_ARCH, SPR_TIRES };
|
||||
for (int i = 0; i < 6; i++) ids[nids++] = arr[i];
|
||||
}
|
||||
|
||||
const int CELL_W = 96, CELL_H = 96;
|
||||
int cols = 3;
|
||||
for (int i = 0; i < nids; i++) {
|
||||
int col = i % cols, row = i / cols;
|
||||
int cx0 = col * CELL_W + 8, cy0 = row * CELL_H + 24;
|
||||
tft.drawRect(cx0, cy0, CELL_W, CELL_H, C(20,20,24));
|
||||
const GameSprite &sp = SPRITES[ids[i]];
|
||||
int destW = sp.w <= CELL_W - 8 ? sp.w : CELL_W - 8;
|
||||
if (destW * sp.h / sp.w > CELL_H - 16) destW = (CELL_H - 16) * sp.w / sp.h;
|
||||
drawSprite(ids[i], destW, cx0 + CELL_W / 2, cy0 + CELL_H - 8, scrH);
|
||||
tft.fillCircle(cx0 + CELL_W / 2, cy0 + CELL_H - 8, 1, TFT_MAGENTA);
|
||||
char buf[24];
|
||||
snprintf(buf, sizeof(buf), "%d %dx%d", ids[i], sp.w, sp.h);
|
||||
tft.setTextDatum(TL_DATUM);
|
||||
tft.setTextFont(1);
|
||||
tft.setTextColor(TFT_YELLOW, C(20,20,24));
|
||||
tft.drawString(buf, cx0 + 2, cy0 + 2);
|
||||
}
|
||||
tft.setTextFont(2);
|
||||
tft.setTextColor(TFT_WHITE, C(20,20,24));
|
||||
tft.setTextDatum(TC_DATUM);
|
||||
char title[48];
|
||||
const char* names[] = { "Car 1", "Car 2", "Car 3", "Car 4", "Traffic cars", "Props" };
|
||||
snprintf(title, sizeof(title), "Page %d/6: %s (A/D flip, T back)", spritePage + 1, names[spritePage]);
|
||||
tft.drawString(title, scrW / 2, 0);
|
||||
tft.setTextDatum(TL_DATUM);
|
||||
}
|
||||
|
||||
static void drawEndScreen(bool win) {
|
||||
tft.fillScreen(C(10,10,14));
|
||||
tft.setTextDatum(MC_DATUM);
|
||||
tft.setFreeFont(&FreeSansBold24pt7b);
|
||||
tft.setTextColor(win ? TFT_GREEN : TFT_RED, C(10,10,14));
|
||||
tft.drawString(win ? "FINISH!" : "GAME OVER", scrW / 2, 80);
|
||||
tft.setFreeFont(nullptr);
|
||||
tft.setTextFont(2);
|
||||
tft.setTextColor(TFT_WHITE, C(10,10,14));
|
||||
char buf[48];
|
||||
snprintf(buf, sizeof(buf), "Score %d", score);
|
||||
tft.drawString(buf, scrW / 2, 140);
|
||||
tft.setTextColor(TFT_GOLD, C(10,10,14));
|
||||
tft.drawString("Press to restart", scrW / 2, 190);
|
||||
tft.setTextDatum(TL_DATUM);
|
||||
}
|
||||
|
||||
static void render() {
|
||||
switch (gameState) {
|
||||
case ST_TITLE: drawTitle(); break;
|
||||
case ST_SPRITES: drawSpriteTest(); break;
|
||||
case ST_GAMEOVER: drawEndScreen(false); break;
|
||||
case ST_WIN: drawEndScreen(true); break;
|
||||
default:
|
||||
renderRoad();
|
||||
renderSprites();
|
||||
if (gameState == ST_CRASH) drawCrashCar(); else drawPlayerCar();
|
||||
drawHUD();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Keyboard
|
||||
// ---------------------------------------------------------------------------
|
||||
static void pollKeyboard() {
|
||||
static char lastKey = 0;
|
||||
Wire.requestFrom((uint8_t)0x55, (uint8_t)1);
|
||||
if (Wire.available() == 0) { lastKey = 0; return; }
|
||||
char k = (char)Wire.read();
|
||||
if (k == 0) { lastKey = 0; return; }
|
||||
if (k == lastKey) return;
|
||||
lastKey = k;
|
||||
char c = tolower(k);
|
||||
switch (c) {
|
||||
case 'w': gasLatch = 1; break;
|
||||
case 's': brakeUntil = millis() + 500; gasLatch = 0; break;
|
||||
case 'a':
|
||||
if (gameState == ST_SPRITES) { spritePage = (spritePage + 5) % 6; }
|
||||
else { steerInput -= 0.8f; registerTurn(); }
|
||||
break;
|
||||
case 'd':
|
||||
if (gameState == ST_SPRITES) { spritePage = (spritePage + 1) % 6; }
|
||||
else { steerInput += 0.8f; registerTurn(); }
|
||||
break;
|
||||
case 'p': autoPlay = !autoPlay; break;
|
||||
case '1': playerColor = PC_RED; if (gameState == ST_TITLE) drawTitle(); break;
|
||||
case '2': playerColor = PC_BLUE; if (gameState == ST_TITLE) drawTitle(); break;
|
||||
case '3': playerColor = PC_WHITE; if (gameState == ST_TITLE) drawTitle(); break;
|
||||
case '4': playerColor = PC_YELLOW; if (gameState == ST_TITLE) drawTitle(); break;
|
||||
case 't':
|
||||
if (gameState == ST_SPRITES) { gameState = ST_TITLE; stateT0 = millis(); }
|
||||
else gameState = ST_SPRITES;
|
||||
break;
|
||||
case ' ': case 'r':
|
||||
if (gameState == ST_TITLE) startGame();
|
||||
else if (gameState == ST_GAMEOVER || gameState == ST_WIN) { gameState = ST_TITLE; stateT0 = millis(); }
|
||||
break;
|
||||
}
|
||||
steerInput = clampf(steerInput, -1, 1);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hardware
|
||||
// ---------------------------------------------------------------------------
|
||||
static void hardwareInit() {
|
||||
Serial.begin(115200);
|
||||
pinMode(BOARD_POWERON, OUTPUT);
|
||||
digitalWrite(BOARD_POWERON, HIGH);
|
||||
pinMode(BOARD_SDCARD_CS, OUTPUT);
|
||||
pinMode(RADIO_CS_PIN, OUTPUT);
|
||||
pinMode(BOARD_TFT_CS, OUTPUT);
|
||||
digitalWrite(BOARD_SDCARD_CS, HIGH);
|
||||
digitalWrite(RADIO_CS_PIN, HIGH);
|
||||
digitalWrite(BOARD_TFT_CS, HIGH);
|
||||
pinMode(BOARD_SPI_MISO, INPUT_PULLUP);
|
||||
SPI.begin(BOARD_SPI_SCK, BOARD_SPI_MISO, BOARD_SPI_MOSI);
|
||||
tft.begin();
|
||||
tft.setRotation(1);
|
||||
tft.fillScreen(TFT_BLACK);
|
||||
pinMode(BOARD_BL_PIN, OUTPUT);
|
||||
digitalWrite(BOARD_BL_PIN, HIGH);
|
||||
Wire.begin(BOARD_I2C_SDA, BOARD_I2C_SCL);
|
||||
attachTrackball();
|
||||
randomSeed(esp_random());
|
||||
}
|
||||
|
||||
void setup() {
|
||||
hardwareInit();
|
||||
scrW = tft.width();
|
||||
scrH = tft.height();
|
||||
buildPalette();
|
||||
buildTrack();
|
||||
if (!sound.begin()) Serial.println("Sound engine init failed");
|
||||
sound.setVolume(5);
|
||||
#ifdef EMULATOR
|
||||
if (emuAutoplay) autoPlay = true;
|
||||
#endif
|
||||
drawTitle();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
uint32_t now = millis();
|
||||
if (now < 800) { resetTrackball(); delay(1); return; }
|
||||
if ((int32_t)(now - nextFrame) < 0) { delay(1); return; }
|
||||
float dt = (nextFrame == 0) ? 0.033f : (float)(now - (nextFrame - FRAME_MS)) / 1000.0f;
|
||||
if (dt < 0.004f) dt = 0.004f;
|
||||
if (dt > 0.1f) dt = 0.1f;
|
||||
nextFrame = now + FRAME_MS;
|
||||
|
||||
int pxX, pxY; uint32_t clicks;
|
||||
applyTrackball(pxX, pxY, clicks);
|
||||
|
||||
if (clicks) {
|
||||
if (gameState == ST_TITLE) startGame();
|
||||
else if (gameState == ST_GAMEOVER || gameState == ST_WIN) { gameState = ST_TITLE; stateT0 = millis(); }
|
||||
}
|
||||
|
||||
pollKeyboard();
|
||||
|
||||
// resolve manual input for this frame
|
||||
gasFrame = gasLatch;
|
||||
if (pxY < 0) gasFrame = 1;
|
||||
if (pxY > 0) gasFrame = -1;
|
||||
if ((int32_t)(now - brakeUntil) < 0) gasFrame = -1;
|
||||
|
||||
if (gameState == ST_PLAYING && !autoPlay) {
|
||||
if (pxX) { steerInput += (pxX > 0 ? 1 : -1) * 0.15f * (1 + (pxX > 3 ? 1 : 0)); registerTurn(); }
|
||||
else steerInput *= 0.90f; // auto-center only when not steering
|
||||
steerInput = clampf(steerInput, -1, 1);
|
||||
}
|
||||
|
||||
// auto-play driver / demo loop
|
||||
if (autoPlay) {
|
||||
if (gameState == ST_TITLE && now - stateT0 > 1200) startGame();
|
||||
if ((gameState == ST_GAMEOVER || gameState == ST_WIN) && now - stateT0 > 3500) {
|
||||
gameState = ST_TITLE; stateT0 = millis();
|
||||
}
|
||||
}
|
||||
|
||||
if (gameState == ST_PLAYING) updateGame(dt);
|
||||
else if (gameState == ST_CRASH) updateCrash(dt);
|
||||
|
||||
render();
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
# MiataDrive
|
||||
|
||||
A Lotus Turbo Challenge–style pseudo-3D racing game for the LilyGo T-Deck
|
||||
(ESP32-S3, 320×240). Drive a Mazda MX-5 through a 3-lap circuit against
|
||||
traffic before the clock runs out.
|
||||
|
||||

|
||||
|
||||
## Running
|
||||
|
||||
### On your PC (SDL2 emulator)
|
||||
|
||||
```sh
|
||||
cd emulator
|
||||
make run APP=MiataDrive
|
||||
```
|
||||
|
||||
Headless smoke test (N frames, dump the last frame as a BMP):
|
||||
|
||||
```sh
|
||||
make smoke APP=MiataDrive
|
||||
```
|
||||
|
||||
### On the T-Deck
|
||||
|
||||
`platformio.ini` has `src_dir = examples/MiataDrive`; build and flash with
|
||||
PlatformIO as usual.
|
||||
|
||||
## Controls
|
||||
|
||||
| Input | Action |
|
||||
|--------------------------|-----------------------------------------|
|
||||
| Trackball / arrow keys | steer left/right, gas (up), brake (down)|
|
||||
| `W` / `S` | gas on / brake pulse |
|
||||
| `A` / `D` | steer left / right |
|
||||
| `1` `2` `3` `4` (title) | pick car color: red / blue / white / yellow |
|
||||
| Enter / click / tap | start / restart |
|
||||
| `P` | toggle the auto-play demo driver |
|
||||
| `T` | sprite test gallery |
|
||||
|
||||
Manual driving is the default; the demo AI (`P`) steers toward the racing
|
||||
line, dodges traffic and eases off in sharp corners — handy when tuning
|
||||
graphics.
|
||||
|
||||
## Game features
|
||||
|
||||
- **Segment-based pseudo-3D road** (the classic "2.5D" technique): the track
|
||||
is a list of `(curve, hill)` segments projected with perspective. Road,
|
||||
rumble strips and lane dashes are drawn near→far with hill crest clipping;
|
||||
distance fog fades the far road into the sky.
|
||||
- **Centrifugal force** pulls you wide in corners; deep off-road excursions
|
||||
trigger a **rollover crash**: the car slides off, kicks up dust, the camera
|
||||
jolts, and the body tumbles through its sprite views (rear → slight → turn
|
||||
→ side) before you rejoin the tarmac.
|
||||
- **Traffic** (blue / white / yellow cars from the sprite sheet) drive slower
|
||||
lanes; rear-ending one costs speed and jolts the camera. Cars lean into
|
||||
corners with their turning sprite, mirrored on right-hand bends.
|
||||
- **Scoring / laps**: 3 laps, 75 s + 45 s per lap, −300 for a crash.
|
||||
- **Sound**: engine + event blips via `sound_engine.*` (I2S on device).
|
||||
|
||||
All graphics — including the title screen, which renders the start line
|
||||
under the arch with your selected car parked on the road — come from the
|
||||
game's own sprites. There are no external image assets.
|
||||
|
||||
## Sprite pipeline (hand-editable assets)
|
||||
|
||||
All sprites live in **one editable image** — `sprites_sheet.png` — tracked in
|
||||
git. The converter is `sprite_tool.py` (needs Pillow):
|
||||
|
||||
```sh
|
||||
python3 sprite_tool.py export # sprites.h -> sprites_sheet.png
|
||||
# ... edit the PNG by hand (paint magenta = transparent) ...
|
||||
python3 sprite_tool.py import # sprites_sheet.png -> sprites.h
|
||||
```
|
||||
|
||||
Sheet layout (fixed, the cutter never guesses):
|
||||
|
||||
- 1120×560: 7×4 grid of 160×140 cells; the top 14px of each cell is a label
|
||||
strip the cutter ignores; content area is 160×126 (largest sprite: arch,
|
||||
140×109).
|
||||
- Background is pure magenta (255,0,255) = transparent. Pink anti-aliasing
|
||||
fringes are cut (magenta excess > 35) or despilled automatically, so soft
|
||||
edges don't leave a purple halo.
|
||||
- Cell order is fixed and matches the `SpriteId` enum in `sprites.h`:
|
||||
0–15 player cars (red/blue/white/yellow × rear/slight/turn/side),
|
||||
16–21 scenery (palm, pine, bush, billboard, arch, tires),
|
||||
22–27 traffic (blue/white/yellow, rear + turning view).
|
||||
- The sharp-turn views are mirrored at extraction time so rear → slight →
|
||||
turn all face the same way; the game flips sprites for right-hand
|
||||
steering/curves.
|
||||
|
||||
Round-tripping is lossless (565→888 uses bit replication) and each import
|
||||
re-trims crops to content, so stray background pixels at sprite edges get
|
||||
cleaned up automatically.
|
||||
|
||||
## Sprite test gallery
|
||||
|
||||
Press `T` from the title screen: paginated view of every sprite at native
|
||||
size on a checkerboard, labeled with index and crop size. `A`/`D` flips the
|
||||
displayed sprite horizontally (to check turn-view alignment), page keys
|
||||
cycle through car colors / scenery / traffic, `T` returns.
|
||||
|
||||
## Tuning
|
||||
|
||||
Key constants live at the top of `MiataDrive.ino`: segment length/road
|
||||
width/camera (`SEG_LEN`, `ROAD_W`, `CAM_H`, `CAM_D`, `DRAW_DIST`), speeds
|
||||
(`MAX_SPEED`, `ACCEL`, `BRAKE`, `OFF_DECEL`), physics (`CENTRIFUGAL`), and
|
||||
race format (`LAPS`, `LAP_TIME`).
|
||||
|
||||
## Files
|
||||
|
||||
| File | Purpose |
|
||||
|----------------------|------------------------------------------------|
|
||||
| `MiataDrive.ino` | the game |
|
||||
| `sprites.h` | generated sprite data (do not edit by hand) |
|
||||
| `sprites_sheet.png` | editable sprite sheet (source of truth) |
|
||||
| `sprite_tool.py` | sheet ⇄ sprites.h converter |
|
||||
| `sound_engine.*` | I2S sound effects |
|
||||
| `utilities.h` | T-Deck board pins |
|
||||
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* @file sound_engine.cpp
|
||||
* @brief I2S speaker rendering task (8 kHz, 16-bit, mono).
|
||||
*
|
||||
* Based on the wiring used by examples/SimpleTone:
|
||||
* BCK = GPIO7, WS = GPIO5, DOUT = GPIO6.
|
||||
*
|
||||
* Sounds are rendered strictly in queue order; layering is achieved by
|
||||
* queueing several events back to back (e.g. a rumble sweep followed by a
|
||||
* noise tail reads as one big explosion).
|
||||
*/
|
||||
#include "sound_engine.h"
|
||||
#include "utilities.h"
|
||||
#include <driver/i2s.h>
|
||||
|
||||
#define SND_SAMPLE_RATE 8000
|
||||
#define SND_I2S_PORT I2S_NUM_0
|
||||
#define SND_CHUNK 128 // samples per i2s_write call
|
||||
#define SND_FADE_MS 8 // fade in/out to avoid clicks
|
||||
|
||||
bool SoundEngine::begin()
|
||||
{
|
||||
i2s_config_t cfg = {};
|
||||
cfg.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX);
|
||||
cfg.sample_rate = SND_SAMPLE_RATE;
|
||||
cfg.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT;
|
||||
cfg.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;
|
||||
cfg.communication_format = I2S_COMM_FORMAT_STAND_I2S;
|
||||
cfg.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1;
|
||||
cfg.dma_buf_count = 8;
|
||||
cfg.dma_buf_len = 64;
|
||||
|
||||
if (i2s_driver_install(SND_I2S_PORT, &cfg, 0, NULL) != ESP_OK) {
|
||||
return false;
|
||||
}
|
||||
|
||||
i2s_pin_config_t pins = {};
|
||||
pins.bck_io_num = BOARD_I2S_BCK;
|
||||
pins.ws_io_num = BOARD_I2S_WS;
|
||||
pins.data_out_num = BOARD_I2S_DOUT;
|
||||
pins.data_in_num = I2S_PIN_NO_CHANGE;
|
||||
i2s_set_pin(SND_I2S_PORT, &pins);
|
||||
|
||||
q_ = xQueueCreate(12, sizeof(SndEvent));
|
||||
if (q_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Render on core 0; the game loop runs on core 1.
|
||||
return xTaskCreatePinnedToCore(trampoline, "sound", 4096, this, 5, nullptr, 0) == pdTRUE;
|
||||
}
|
||||
|
||||
void SoundEngine::play(const SndEvent &e)
|
||||
{
|
||||
if (q_) {
|
||||
xQueueSend(q_, &e, 0); // drop instead of blocking the game
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t SoundEngine::pending() const
|
||||
{
|
||||
if (!q_) return 0;
|
||||
return (uint8_t)uxQueueMessagesWaiting(q_);
|
||||
}
|
||||
|
||||
void SoundEngine::clear()
|
||||
{
|
||||
if (!q_) return;
|
||||
SndEvent dummy;
|
||||
while (xQueueReceive(q_, &dummy, 0)) { }
|
||||
}
|
||||
|
||||
void SoundEngine::trampoline(void *arg)
|
||||
{
|
||||
static_cast<SoundEngine *>(arg)->task();
|
||||
}
|
||||
|
||||
void SoundEngine::task()
|
||||
{
|
||||
for (;;) {
|
||||
SndEvent e;
|
||||
xQueueReceive(q_, &e, portMAX_DELAY);
|
||||
switch (e.type) {
|
||||
case SND_TONE: renderTone(e.freq, e.dur, e.amp); break;
|
||||
case SND_SWEEP: renderSweep(e.freq, e.freq2, e.dur, e.amp); break;
|
||||
case SND_NOISE: renderNoise(e.dur, e.amp); break;
|
||||
}
|
||||
// After the LAST queued event the I2S TX DMA ring would keep
|
||||
// replaying its remaining ~64 ms of buffer forever — heard as the
|
||||
// sound's tail (rocket sweep, melody tone) repeating endlessly.
|
||||
// Zero the ring once the queue is empty (not between queued events,
|
||||
// which would punch silence-gaps into back-to-back melodies).
|
||||
if (uxQueueMessagesWaiting(q_) == 0) {
|
||||
i2s_zero_dma_buffer(SND_I2S_PORT);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SoundEngine::volumeUp()
|
||||
{
|
||||
if (vol_ < VOL_MAX) vol_++;
|
||||
}
|
||||
|
||||
void SoundEngine::volumeDown()
|
||||
{
|
||||
if (vol_ > 0) vol_--;
|
||||
}
|
||||
|
||||
void SoundEngine::toggleMute()
|
||||
{
|
||||
if (vol_ > 0) {
|
||||
lastVol_ = vol_;
|
||||
vol_ = 0;
|
||||
} else {
|
||||
vol_ = lastVol_ > 0 ? lastVol_ : VOL_MAX / 2;
|
||||
}
|
||||
}
|
||||
|
||||
// Restore a saved volume level (from NVS at boot); 0 keeps the device muted
|
||||
// while lastVol_ stays at its default so unmute still works.
|
||||
void SoundEngine::setVolume(uint8_t v)
|
||||
{
|
||||
if (v > VOL_MAX) v = VOL_MAX;
|
||||
vol_ = v;
|
||||
if (vol_ > 0) lastVol_ = vol_;
|
||||
}
|
||||
|
||||
// scaled peak amplitude for the current volume level
|
||||
static inline uint32_t scaledAmp(uint16_t amp, uint8_t vol)
|
||||
{
|
||||
return ((uint32_t)amp * vol) / SoundEngine::VOL_MAX;
|
||||
}
|
||||
|
||||
// fade envelope over the first/last SND_FADE_MS of the whole event
|
||||
static inline uint32_t envelope(uint32_t pos, uint32_t total, uint32_t fade, uint32_t amp)
|
||||
{
|
||||
if (fade * 2 > total) fade = total / 2;
|
||||
uint32_t s = amp;
|
||||
if (pos < fade) s = s * pos / fade;
|
||||
uint32_t tail = total - pos;
|
||||
if (tail < fade) s = s * tail / fade;
|
||||
return s;
|
||||
}
|
||||
|
||||
void SoundEngine::renderTone(uint16_t freq, uint16_t durMs, uint16_t amp)
|
||||
{
|
||||
static int16_t buf[SND_CHUNK];
|
||||
|
||||
uint32_t a = scaledAmp(amp, vol_);
|
||||
if (a == 0) return;
|
||||
|
||||
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
|
||||
if (total == 0) return;
|
||||
uint32_t half = (freq > 0) ? (SND_SAMPLE_RATE / 2) / freq : 1;
|
||||
if (half == 0) half = 1;
|
||||
uint32_t fade = (uint32_t)SND_SAMPLE_RATE * SND_FADE_MS / 1000;
|
||||
if (fade < 2) fade = 2;
|
||||
|
||||
uint32_t phase = 0;
|
||||
for (uint32_t i = 0; i < total; ) {
|
||||
if (q_ && uxQueueMessagesWaiting(q_) > 0) return; // interrupted by higher-priority sound
|
||||
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
|
||||
for (uint32_t k = 0; k < n; k++) {
|
||||
int32_t s = ((phase / half) & 1) ? (int32_t)a : -(int32_t)a;
|
||||
buf[k] = (int16_t)(s * (int32_t)envelope(i + k, total, fade, 256) / 256);
|
||||
phase++;
|
||||
}
|
||||
size_t bw;
|
||||
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
|
||||
i += n;
|
||||
}
|
||||
}
|
||||
|
||||
// Square wave gliding from freq0 to freq1 (Hz) over the duration.
|
||||
// Phase is carried in a float cycle counter (0..1) so frequency changes
|
||||
// never click.
|
||||
void SoundEngine::renderSweep(uint16_t freq0, uint16_t freq1, uint16_t durMs, uint16_t amp)
|
||||
{
|
||||
static int16_t buf[SND_CHUNK];
|
||||
|
||||
uint32_t a = scaledAmp(amp, vol_);
|
||||
if (a == 0) return;
|
||||
|
||||
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
|
||||
if (total == 0) return;
|
||||
uint32_t fade = (uint32_t)SND_SAMPLE_RATE * SND_FADE_MS / 1000;
|
||||
if (fade < 2) fade = 2;
|
||||
|
||||
float phase = 0.0f;
|
||||
for (uint32_t i = 0; i < total; ) {
|
||||
if (q_ && uxQueueMessagesWaiting(q_) > 0) return; // interrupted by higher-priority sound
|
||||
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
|
||||
for (uint32_t k = 0; k < n; k++) {
|
||||
uint32_t pos = i + k;
|
||||
float f = (float)freq0 +
|
||||
((float)(int16_t)(freq1 - freq0) * (float)pos) / (float)total;
|
||||
if (f < 20.0f) f = 20.0f;
|
||||
phase += f / (float)SND_SAMPLE_RATE;
|
||||
if (phase >= 1.0f) phase -= 1.0f;
|
||||
int32_t s = (phase < 0.5f) ? (int32_t)a : -(int32_t)a;
|
||||
buf[k] = (int16_t)(s * (int32_t)envelope(pos, total, fade, 256) / 256);
|
||||
}
|
||||
size_t bw;
|
||||
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
|
||||
i += n;
|
||||
}
|
||||
}
|
||||
|
||||
void SoundEngine::renderNoise(uint16_t durMs, uint16_t amp)
|
||||
{
|
||||
static int16_t buf[SND_CHUNK];
|
||||
|
||||
uint32_t a = scaledAmp(amp, vol_);
|
||||
if (a == 0) return;
|
||||
|
||||
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
|
||||
if (total == 0) return;
|
||||
|
||||
uint32_t seed = esp_random() | 1;
|
||||
for (uint32_t i = 0; i < total; ) {
|
||||
if (q_ && uxQueueMessagesWaiting(q_) > 0) return; // interrupted by higher-priority sound
|
||||
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
|
||||
for (uint32_t k = 0; k < n; k++) {
|
||||
// xorshift32 for cheap white noise
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
int32_t signedS = (int32_t)(seed & 0xFFFF) - 32768;
|
||||
// linear decay over the burst
|
||||
int32_t s = (int32_t)(((int64_t)signedS * a * (int64_t)(total - i - k)) /
|
||||
((int64_t)32768 * (int64_t)total));
|
||||
buf[k] = (int16_t)s;
|
||||
}
|
||||
size_t bw;
|
||||
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
|
||||
i += n;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* @file sound_engine.h
|
||||
* @brief Tiny non-blocking I2S sound engine for the T-Deck speaker.
|
||||
*
|
||||
* A FreeRTOS task owns the I2S peripheral (speaker, I2S_NUM_0) and renders
|
||||
* queued sound events one after another. The game only ever pushes events,
|
||||
* so it never blocks. Event types:
|
||||
*
|
||||
* SND_TONE fixed square-wave beep
|
||||
* SND_SWEEP square wave gliding from freq down/up to freq2 (sirens, booms)
|
||||
* SND_NOISE white-noise burst with linear decay (explosions)
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
enum SndType : uint8_t {
|
||||
SND_TONE = 0, // fixed square wave
|
||||
SND_SWEEP, // square wave gliding freq -> freq2
|
||||
SND_NOISE, // white noise burst
|
||||
};
|
||||
|
||||
struct SndEvent {
|
||||
SndType type;
|
||||
uint16_t freq; // Hz (tone, or sweep start)
|
||||
uint16_t freq2; // Hz (sweep end; ignored for tone/noise)
|
||||
uint16_t dur; // duration in ms
|
||||
uint16_t amp; // peak amplitude 0..32767
|
||||
};
|
||||
|
||||
class SoundEngine {
|
||||
public:
|
||||
static const uint8_t VOL_MAX = 8;
|
||||
|
||||
bool begin();
|
||||
void play(const SndEvent &e);
|
||||
uint8_t pending() const;
|
||||
void clear();
|
||||
|
||||
// Master volume, applied to every rendered sound
|
||||
void volumeUp();
|
||||
void volumeDown();
|
||||
void toggleMute();
|
||||
void setVolume(uint8_t v); // restore a saved level (0 = muted)
|
||||
uint8_t volume() const { return vol_; }
|
||||
|
||||
private:
|
||||
static void trampoline(void *arg);
|
||||
void task();
|
||||
void renderTone(uint16_t freq, uint16_t durMs, uint16_t amp);
|
||||
void renderSweep(uint16_t freq0, uint16_t freq1, uint16_t durMs, uint16_t amp);
|
||||
void renderNoise(uint16_t durMs, uint16_t amp);
|
||||
|
||||
QueueHandle_t q_ = nullptr;
|
||||
uint8_t vol_ = 5; // default: moderate
|
||||
uint8_t lastVol_ = 5; // remembered for mute toggle
|
||||
};
|
||||
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Lotus3 sprite tool — hand-editing workflow for the game's sprite assets.
|
||||
|
||||
1. python3 sprite_tool.py export -> sprites_sheet.png (editable image)
|
||||
2. edit sprites_sheet.png by hand (paint over magenta = transparent)
|
||||
3. python3 sprite_tool.py import -> sprites.h regenerated from the image
|
||||
|
||||
Sheet layout (fixed, so the cutter never needs to guess):
|
||||
* 7 columns x 4 rows of 160x140 cells (image is 1120x560)
|
||||
* the top 14px of each cell is a label strip (name text); the cutter skips it
|
||||
* content area per cell: 160x126 -- big enough for the largest sprite
|
||||
(arch 140x109). If you draw bigger, it will be clipped.
|
||||
* background is pure magenta (255,0,255) = transparent
|
||||
* pink/magenta anti-aliasing fringes are cut (magenta excess > 35) or
|
||||
despilled (pulled back toward the sprite color)
|
||||
|
||||
Cell order (row-major) is fixed and matches the game's SpriteId enum:
|
||||
0..15 player cars: red/blue/white/yellow x (rear, slight, turn, side)
|
||||
16..21 scenery: palm, pine, bush, billboard, arch, tires
|
||||
22..27 traffic: blue rear/turn, white rear/turn, yellow rear/turn
|
||||
|
||||
Requires Pillow: python3 -m pip install --user pillow
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
import os
|
||||
|
||||
try:
|
||||
from PIL import Image, ImageDraw
|
||||
except ImportError:
|
||||
sys.exit("Pillow required: python3 -m pip install --user pillow")
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
HDR = os.path.join(HERE, "sprites.h")
|
||||
SHEET = os.path.join(HERE, "sprites_sheet.png")
|
||||
|
||||
CELL_W, CELL_H = 160, 140
|
||||
LABEL_H = 14
|
||||
COLS, ROWS = 7, 4
|
||||
MAGENTA = (255, 0, 255)
|
||||
|
||||
NAMES = [
|
||||
"p_red_rear", "p_red_slight", "p_red_turn", "p_red_side",
|
||||
"p_blue_rear", "p_blue_slight", "p_blue_turn", "p_blue_side",
|
||||
"p_white_rear", "p_white_slight", "p_white_turn", "p_white_side",
|
||||
"p_yellow_rear", "p_yellow_slight", "p_yellow_turn", "p_yellow_side",
|
||||
"palm", "pine", "bush", "billboard", "arch", "tires",
|
||||
"car_blue", "car_blue_turn", "car_white", "car_white_turn",
|
||||
"car_yellow", "car_yellow_turn",
|
||||
]
|
||||
assert len(NAMES) == COLS * ROWS
|
||||
|
||||
ENUM = """enum SpriteId {
|
||||
SPR_P_RED, SPR_P_RED_S, SPR_P_RED_T, SPR_P_RED_SIDE,
|
||||
SPR_P_BLUE, SPR_P_BLUE_S, SPR_P_BLUE_T, SPR_P_BLUE_SIDE,
|
||||
SPR_P_WHITE, SPR_P_WHITE_S, SPR_P_WHITE_T, SPR_P_WHITE_SIDE,
|
||||
SPR_P_YELLOW, SPR_P_YELLOW_S, SPR_P_YELLOW_T, SPR_P_YELLOW_SIDE,
|
||||
SPR_PALM, SPR_PINE, SPR_BUSH, SPR_BILLBOARD, SPR_ARCH, SPR_TIRES,
|
||||
SPR_CAR_BLUE, SPR_CAR_BLUE_T, SPR_CAR_WHITE, SPR_CAR_WHITE_T,
|
||||
SPR_CAR_YELLOW, SPR_CAR_YELLOW_T,
|
||||
SPR_COUNT };"""
|
||||
|
||||
|
||||
def is_bg(p):
|
||||
return p[0] > 160 and p[2] > 160 and p[1] < 150
|
||||
|
||||
|
||||
def key_pixel(p):
|
||||
"""magenta key + halo despill -> (keep, r, g, b)"""
|
||||
r, g, b = p[:3]
|
||||
if is_bg(p):
|
||||
return False, 0, 0, 0
|
||||
e = min(r, b) - g # magenta excess
|
||||
if e > 35:
|
||||
return False, 0, 0, 0 # pink halo pixel -> cut
|
||||
if e > 8: # mild fringe -> despill
|
||||
f = min(1.0, (e - 8) / 30.0) * 0.85
|
||||
r = int(r - (r - g) * f)
|
||||
b = int(b - (b - g) * f)
|
||||
return True, r, g, b
|
||||
|
||||
|
||||
def expand565(v):
|
||||
"""RGB565 -> 8-bit with bit replication (exact inverse of the C encoder)."""
|
||||
r = (v >> 11) & 0x1F
|
||||
g = (v >> 5) & 0x3F
|
||||
b = v & 0x1F
|
||||
return (r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2)
|
||||
|
||||
|
||||
def parse_sprites_h(path):
|
||||
"""returns ordered list of (name, w, h, [rgb565 values])"""
|
||||
src = open(path).read()
|
||||
table = re.findall(r'\{\s*\w+,\s*(\d+),\s*(\d+)\s*\}\s*,\s*//\s*(\w+)', src)
|
||||
dims = {name: (int(w), int(h)) for w, h, name in table}
|
||||
order = [name for _, _, name in table]
|
||||
arrays = {}
|
||||
for m in re.finditer(r'static const uint16_t (SPR_\w+)\[(\d+)\] = \{([^}]*)\}', src, re.S):
|
||||
vals = [int(x, 16) for x in re.findall(r'0x([0-9A-Fa-f]{4})', m.group(3))]
|
||||
arrays[m.group(1)] = vals
|
||||
out = []
|
||||
for name in order:
|
||||
w, h = dims[name]
|
||||
arr = arrays.get("SPR_" + name + "_DATA")
|
||||
if arr is None or len(arr) != w * h:
|
||||
sys.exit(f"sprites.h: cannot resolve {name}")
|
||||
out.append((name, w, h, arr))
|
||||
return out
|
||||
|
||||
|
||||
def cmd_export():
|
||||
sprites = parse_sprites_h(HDR)
|
||||
if len(sprites) != len(NAMES):
|
||||
sys.exit(f"sprites.h has {len(sprites)} sprites, tool expects {len(NAMES)}")
|
||||
sheet = Image.new("RGB", (COLS * CELL_W, ROWS * CELL_H), MAGENTA)
|
||||
draw = ImageDraw.Draw(sheet)
|
||||
for i, (cur, w, h, vals) in enumerate(sprites):
|
||||
cx, cy = (i % COLS) * CELL_W, (i // COLS) * CELL_H
|
||||
draw.text((cx + 3, cy + 1), f"{i}:{NAMES[i]}", fill=(0, 0, 0))
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
v = vals[y * w + x]
|
||||
if v == 0x0001:
|
||||
continue # magenta shows through
|
||||
sheet.putpixel((cx + x, cy + LABEL_H + y), expand565(v))
|
||||
sheet.save(SHEET)
|
||||
print(f"wrote {SHEET} ({sheet.size[0]}x{sheet.size[1]}, {len(sprites)} sprites)")
|
||||
|
||||
|
||||
def cmd_import():
|
||||
sheet = Image.open(SHEET).convert("RGB")
|
||||
if sheet.size != (COLS * CELL_W, ROWS * CELL_H):
|
||||
sys.exit(f"{SHEET} is {sheet.size}, expected {(COLS*CELL_W, ROWS*CELL_H)}")
|
||||
parts = []
|
||||
parts.append("""// Auto-generated by sprite_tool.py from sprites_sheet.png — do not edit by hand;
|
||||
// edit the sheet image and re-run: python3 sprite_tool.py import
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
#define SPR_TRANSP 0x0001
|
||||
|
||||
struct GameSprite {
|
||||
const uint16_t* data;
|
||||
int w, h;
|
||||
};
|
||||
|
||||
""")
|
||||
dims = []
|
||||
for i, name in enumerate(NAMES):
|
||||
cx, cy = (i % COLS) * CELL_W, (i // COLS) * CELL_H
|
||||
cell = sheet.crop((cx, cy + LABEL_H, cx + CELL_W, cy + CELL_H))
|
||||
w, h = cell.size
|
||||
minx, miny, maxx, maxy = w, h, -1, -1
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
if not is_bg(cell.getpixel((x, y))):
|
||||
if x < minx: minx = x
|
||||
if x > maxx: maxx = x
|
||||
if y < miny: miny = y
|
||||
if y > maxy: maxy = y
|
||||
if maxx < 0:
|
||||
minx, miny, maxx, maxy = 0, 0, 0, 0
|
||||
sw, sh = maxx - minx + 1, maxy - miny + 1
|
||||
vals = []
|
||||
for y in range(miny, maxy + 1):
|
||||
for x in range(minx, maxx + 1):
|
||||
keep, r, g, b = key_pixel(cell.getpixel((x, y)))
|
||||
vals.append(0x0001 if not keep else ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3))
|
||||
parts.append(f"static const uint16_t SPR_{name}_DATA[{sw*sh}] = {{\n")
|
||||
for k in range(0, len(vals), 16):
|
||||
parts.append(" " + ", ".join(f"0x{v:04X}" for v in vals[k:k+16]) + ",\n")
|
||||
parts.append("};\n\n")
|
||||
dims.append((name, sw, sh))
|
||||
print(f" {i:2d} {name:16s} {sw}x{sh}")
|
||||
parts.append("static const GameSprite SPRITES[] = {\n")
|
||||
for name, sw, sh in dims:
|
||||
parts.append(f" {{ SPR_{name}_DATA, {sw}, {sh} }}, // {name}\n")
|
||||
parts.append("};\n\n")
|
||||
parts.append(ENUM + "\n")
|
||||
open(HDR, "w").write("".join(parts))
|
||||
print(f"wrote {HDR}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
mode = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
if mode == "export":
|
||||
cmd_export()
|
||||
elif mode == "import":
|
||||
cmd_import()
|
||||
else:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 144 KiB |
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* @file utilities.h
|
||||
* @author Lewis He (lewishe@outlook.com)
|
||||
* @license MIT
|
||||
* @copyright Copyright (c) 2023 Shenzhen Xin Yuan Electronic Technology Co., Ltd
|
||||
* @date 2023-04-11
|
||||
*
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
|
||||
|
||||
//! The board peripheral power control pin needs to be set to HIGH when using the peripheral
|
||||
#define BOARD_POWERON 10
|
||||
|
||||
#define BOARD_I2S_WS 5
|
||||
#define BOARD_I2S_BCK 7
|
||||
#define BOARD_I2S_DOUT 6
|
||||
|
||||
#define BOARD_I2C_SDA 18
|
||||
#define BOARD_I2C_SCL 8
|
||||
|
||||
#define BOARD_BAT_ADC 4
|
||||
|
||||
#define BOARD_TOUCH_INT 16
|
||||
#define BOARD_KEYBOARD_INT 46
|
||||
|
||||
#define BOARD_SDCARD_CS 39
|
||||
#define BOARD_TFT_CS 12
|
||||
#define RADIO_CS_PIN 9
|
||||
|
||||
#define BOARD_TFT_DC 11
|
||||
#define BOARD_TFT_BACKLIGHT 42
|
||||
|
||||
#define BOARD_SPI_MOSI 41
|
||||
#define BOARD_SPI_MISO 38
|
||||
#define BOARD_SPI_SCK 40
|
||||
|
||||
#define BOARD_TBOX_G02 2
|
||||
#define BOARD_TBOX_G01 3
|
||||
#define BOARD_TBOX_G04 1
|
||||
#define BOARD_TBOX_G03 15
|
||||
|
||||
#define BOARD_ES7210_MCLK 48
|
||||
#define BOARD_ES7210_LRCK 21
|
||||
#define BOARD_ES7210_SCK 47
|
||||
#define BOARD_ES7210_DIN 14
|
||||
|
||||
#define RADIO_BUSY_PIN 13
|
||||
#define RADIO_RST_PIN 17
|
||||
#define RADIO_DIO1_PIN 45
|
||||
|
||||
#define BOARD_BOOT_PIN 0
|
||||
|
||||
#define BOARD_BL_PIN 42
|
||||
|
||||
|
||||
#define BOARD_GPS_TX_PIN 43
|
||||
#define BOARD_GPS_RX_PIN 44
|
||||
|
||||
|
||||
#ifndef RADIO_FREQ
|
||||
#define RADIO_FREQ 868.0
|
||||
#endif
|
||||
|
||||
#ifndef RADIO_BANDWIDTH
|
||||
#define RADIO_BANDWIDTH 125.0
|
||||
#endif
|
||||
|
||||
#ifndef RADIO_SF
|
||||
#define RADIO_SF 10
|
||||
#endif
|
||||
|
||||
#ifndef RADIO_CR
|
||||
#define RADIO_CR 6
|
||||
#endif
|
||||
|
||||
#ifndef RADIO_TX_POWER
|
||||
#define RADIO_TX_POWER 22
|
||||
#endif
|
||||
|
||||
#define DEFAULT_OPA 100
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user