/** * DemoCore — the device-agnostic part of the bundled sample demo. * * This is the recommended structure for template sketches that will also * run on real hardware: * * examples/$(APP)/$(APP)Core.h <- THIS FILE: all rendering + logic. * Device-agnostic: no shim, no SDL, * no Arduino. Renders RGB565 in * panel wire order into a buffer the * owner supplies. * examples/$(APP)/$(APP).cpp <- thin emulator shell (keyboard, dt) * fw/$(APP)HW.ino <- firmware twin (TFT_eSprite + fps report) * * Because the core is shared 1:1, whatever fps the hardware reports is * the fps of exactly this code. * * COLOR CONTRACT: the buffer holds 16-bit RGB565 pixels in PANEL WIRE * ORDER — big-endian, i.e. the byte sequence the ST7789 receives over * SPI. On hardware the buffer IS the TFT_eSprite payload pushed raw. * Store every pixel through wire565() or you will see byte-swapped * colors on the panel while the emulator looks fine. */ #pragma once #include #include #include namespace demo { static constexpr int W = 320; static constexpr int H = 240; static uint16_t *g_fb = nullptr; // --- RGB565 helpers (also in shim.h for shell-side use) ---------------------- static inline uint16_t rgb565(int r, int g, int b) { return (uint16_t)(((r & 31) << 11) | ((g & 63) << 5) | (b & 31)); } // Panel wire order: the ST7789 receives the high byte first, and the // sprite/push path sends buffer bytes raw — so store byteswapped values. static inline uint16_t wire565(uint16_t c) { return (uint16_t)((c << 8) | (c >> 8)); } // --- Demo state -------------------------------------------------------------- static float boxX = 40, boxY = 30; static float velX = 100.0f, velY = 70.0f; // pixels per second static constexpr float BOX = 24.0f; static bool quitRequested = false; // --- Public API --------------------------------------------------------------- static inline void demoInit(uint16_t *fb) { g_fb = fb; velX = 60.0f + (rand() % 100) * 1.2f; velY = 60.0f + (rand() % 100) * 1.2f; } static inline void demoInput(uint8_t k) { if (k == 'q' || k == 0x1b) quitRequested = true; } static inline bool demoQuitRequested() { return quitRequested; } static void demoFrame(float dt, unsigned long nowMs) { // 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 (dark 565 background, stored in wire order) { uint16_t bg = wire565(rgb565(2, 2, 6)); for (int i = 0; i < W * H; i++) g_fb[i] = bg; } // Draw a filled box with a color that drifts over time (5-bit quantized — // the banding is what the real panel shows) uint16_t color = rgb565((int)(16 + 15 * sinf(nowMs / 900.0f)) & 31, 24, 12); uint16_t wcolor = wire565(color); 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; g_fb[y * W + x] = wcolor; } } } } // namespace demo