跑酷

· · 个人记录

/*
 =============================================================================
  ÄÞºçÅÜ¿á 3D  ¡ª  µ¥Îļþ C++ ´¿Èí¼þ¹âÕ¤»¯ 3D ÅÜ¿áÓÎÏ·
 =============================================================================

  ²»Ê¹Óà OpenGL / SDL / SFML / raylib »òÈκÎͼÐο⣬»­ÃæÈ«²¿ÊÖд¹âÕ¤»¯£º

    * ͸ÊÓͶӰ + ¿É¸©ÑöÏà»ú
    * ÖðÏñËØ z-buffer£¨Éî¶È = 1/z£¬Í¸ÊÓÕýÈ·£©
    * Èý½ÇÐÎÖØÐÄ×ø±ê²åÖµ + Gouraud ×ÅÉ«
    * Æ½Ãæ×ÅÉ« 3D ºÐÌ壨ÿºÐ 6 Ãæ / 12 Èý½ÇÐΣ©
    * Öð¶¥µãÖ¸Êý¾àÀëÎí
    * ³ÌÐò»¯ÂäÈÕÌì¿Õ¡¢Ì«Ñô¡¢ÔÆ¡¢ÊÓ²î³ÇÊÐÌì¼ÊÏß
    * ¼Ó·¨»ìºÏ billboard£¨½ð±Ò¡¢»ð»¨¡¢³¾°£¡¢ËÙ¶Èβ¼££©
    * °ë·Ö±æÂÊ bloom£¨ÁÁ²¿ÌáÈ¡ -> ¿É·ÖÀëÄ£ºý -> Ë«ÏßÐÔµþ¼Ó£©
    * °µ½Ç¡¢É¨ÃèÏß¡¢ÊÜÉËÉÁºì¡¢¾µÍ·¶¶¶¯
    * ΨһÊä³ö½éÖÊ£ºANSI 24 Î»Õæ²Ê + ? °ë¿é×Ö·û¹¹³ÉµÄ"×ÓÏñËØ"

  ÿֻ֡×öÒ»´ÎÊä³ö£¨ÄÚ²¿°´ 64KB ·Ö¿éд£©£¬SGR ÑÕÉ«²ÉÓòî·Ö±àÂë¡£½çÃæÎª
  ¼òÌåÖÐÎÄ£¬ÖÐÎİ´Ë«¿í×Ö·û¶ÔÆë£¬ÖÕ¶ËÐèʹÓõȿí CJK ×ÖÌå¡£
  Êä³ö±àÂë»á×Ô¶¯Æ¥Åä¿ØÖÆÌ¨´úÂëÒ³£¨UTF-8 / GBK£©£¬°´ L ¿ÉËæÊ±Çл»¡£

  ±àÒë
    MinGW-w64 : g++ -O2 -std=c++14 neon_runner_3d.cpp -o neon_runner.exe
    MSVC      : cl /O2 /EHsc neon_runner_3d.cpp
    Linux/mac : g++ -O2 -std=c++14 -pthread neon_runner_3d.cpp -o neon_runner

  ÇëÔÚÖ§³Ö 24 λɫµÄÖÕ¶ËÔËÐУ¨Windows Terminal / аæ conhost / iTerm2 /
  kitty / ÉèÖÃÁË COLORTERM=truecolor µÄ xterm£©¡£´°¿ÚÔ½´ó»­ÃæÔ½¾«Ï¸¡£

  Æô¶¯Ç°·Ö±æÂÊÑ¡Ôñ
    ½»»¥ÖÕ¶Ë»áÏȵ¯³öÈ«ÆÁÑ¡ÔñÃæ°å£º×Ô¶¯£¨ÊµÊ±¸úËæ´°¿Ú£©¡¢¾Å¸öÔ¤Éè
    £¨80 x 24 Ò»Ö±µ½ 1200 x 300£©¡¢×Ô¶¨Ò壨·½Ïò¼ü±à¼­Íø¸ñ£©£¬¹² 11 Ïî¡£
    ÁбíÿÆÁÏÔʾ 7 ÏW/S »ò ¡ü¡ý ¹ö¶¯£¬Êý×Ö¼ü 1-7 ¿ìÑ¡µ±Ç°¿É¼ûÏ
    »Ø³µÓ¦Óá£
    ÓÎÏ·ÖÐËæÊ±°´ V ¿ÉÖØ¿ªÃæ°å¡£¹Ì¶¨Íø¸ñ²»Äܳ¬¹ýµ±Ç°´°¿Ú£¬
    Ïë»ñµÃ¸ü¶à¸ñ×ÓÇëÏÈÓÃÏÂÃæµÄÖÕ¶ËËõ·Å¹¦ÄÜ¡£
    stdin/stdout ±»Öض¨Ïò£¨½Å±¾¡¢×¥Ö¡£©»òÉèÖÃÁË
    NR_COLS / NR_ROWS / NR_NORES / NR_PLAY ʱ×Ô¶¯Ìø¹ýÃæ°å¡£

  ÖÕ¶ËËõ·Å£¨³å»÷¸ü¸ß·Ö±æÂÊ£©
    Ãæ°å¿ÉÒÔÖ±½ÓËõСÖÕ¶Ë×ÖÌ壬ÈÃÆÁÄ»ÈÝÄɸü¶à×Ö·û¸ñ£º
      - / +   ËõС / ·Å´óÒ»¼¶×ÖÌå      0   »¹Ô­Ô­Ê¼×ÖÌå
      Z       Á¬ÐøËõС£¬Ö±µ½×î´óÍø¸ñ²¢ÒÔ¡¸×Ô¶¯¡¹¿ª¾Ö
      R       ÊÖ¶¯ Ctrl+- / ¹öÂÖËõ·ÅºóÖØÐ¼ì²â´°¿Ú
    Windows conhost ×ß¿ØÖÆÌ¨×ÖÌå API£»xterm / WezTerm / Konsole ·¢ËÍ
    "CSI 8;rows;cols t" Íø¸ñÇëÇó£¨conhost ²»Ö§³Ö¸ÃÐòÁУ©¡£
    conhost ÔÚ´°¿Úδ×î´ó»¯Ê±»á±£³Ö×Ö·û¸ñÊý²»±ä£¬ÇëÏÈ×î´ó»¯´°¿Ú£¬
    ÔÙËõ·Å»ò°´ R¡£Á½Ìõ·¾¶¶¼²»Ö§³ÖµÄÖÕ¶Ë£¨ÀýÈç Windows Terminal£¬
    ´Ëʱ¾É°æ console API ʧЧ£¬¸ÄÓùâ±êλÖñ¨¸æ CPR ̽²âÍø¸ñ£©ÈÔ¿ÉÓãº
    ÊÖ¶¯ Ctrl+- ËõС×ÖÌåºó°´ R£¬¸ß·Ö±æÂʵµÎ»¼´½âËø¡£
    ¡¸×Ô¶¯¡¹ÊµÊ±¸úËæ´°¿Ú±ä»¯£»Í˳öÓÎϷʱ×Ô¶¯»¹Ô­×ÖÌå¡£

  ÖÐÎÄÏÔʾ / ±àÂ루º¬ Dev-C++ ¼æÈÝ£©
    ½çÃæÎÄ×Ö°´ UTF-8 ±£´æ¡£Èô IDE Óà -fexec-charset=gbk ±àÒ룬»ò°ÑÔ´Âë
    Áí´æÎª ANSI£¬³ÌÐòÆô¶¯Ê±»á̽²â×Ö·û´®×ÖÃæÁ¿µÄÕæÊµ±àÂ룬ÔÙͳһ¾­ UTF-16
    ת³ÉÖÕ¶Ë´úÂëÒ³ ¡ª¡ª ²»»á°Ñ GBK ºº×ÖÎóÅгɷǷ¨ UTF-8 ¶øÊä³öÂúÆÁ '?'¡£
    ´«Í³ conhost£¨Dev-C++ µ¯³öµÄ¿ØÖÆÌ¨£©Ä¬Èϰ´ GBK(936) Êä³ö£¬±Ü¿ª
    conhost ÔÚ CP 65001 ϰѺº×ÖÏÔʾ³É '?' µÄÀÏÎÊÌ⣻Windows Terminal¡¢
    VS Code µÈÏÖ´úÖÕ¶ËÈÔ°´ UTF-8 Êä³ö¡£L ¼ü¿ÉËæÊ±Çл»±àÂë¡£
    GBK ûÓÐ ?£¬¸Ãģʽ¸ÄÓà ¨{ ²¢¶Ôµ÷ǰ¾°/±³¾°É«£¬»­ÃæÍêÈ«µÈ¼Û¡£
    ÁíÒ»¸ö '?' À´Ô´ÊÇ¡¸µãÕó×ÖÌ塹(Raster Fonts)£ºËü¼ÈÎÞÖÐÎÄ×ÖÐÎÒ²ÎÞ
    °ë¿é×ÖÐΡ£³ÌÐòÔÚÕæ conhost Ï»á×Ô¶¯»»³É Consolas / ÐÂËÎÌåµÈ
    TrueType µÈ¿í×ÖÌå²¢ÔÚÍ˳öʱ»¹Ô­£»°´ F ¿ÉÊÖ¶¯ÂÖÁ÷Çл»¡£Èô×ÖÌåÈÔ²»¶Ô£¬
    ÇëÔÚ¿ØÖÆÌ¨´°¿ÚÊôÐÔµÄ×ÖÌåҳѡ Consolas / ÐÂËÎÌå / Microsoft YaHei Mono
    / ¸üÉ´ºÚÌå µÈÖ§³ÖÖÐÎĵĵȿí×ÖÌå¡£
    ¿ÉÓà NR_CP=65001 / NR_CP=936 Ç¿ÖÆ±àÂ룬NR_FONT=0 ¹Ø±Õ×Ô¶¯»»×ÖÌå¡£

  ¹ØÓÚ³¬¸ß·Ö±æÂÊ
    1200 x 300 Ö¸×Ö·ûÍø¸ñ£¬Êµ¼Ê»­ÃæÎª 1200 x 600 ×ÓÏñËØ£¬
    ÐèÒª¼«Ð¡µÄÖÕ¶Ë×ÖÌ壨ÅäºÏËõ·Å¹¦ÄÜ£©ºÍ¸ßÐÔÄÜÖÕ¶Ë¡£
    ÿ֡ÐèÊä³öÉϰÙÍò×Ö½Ú£¬Òò´Ë³¬´óÍø¸ñÏ»á×Ô¶¯½µµÍÄ¿±êÖ¡ÂÊ
    £¨>20000 / >60000 / >150000 ¸ñ·Ö±ð½µÖÁ 30 / 18 / 10 fps£©£¬
    ±ÜÃâѹ¿åÖն˹ܵÀ¡£ÆÕͨ 120 x 40 ÈÔÎȶ¨ 50 fps¡£

  ¿ÉÑ¡»·¾³±äÁ¿
    NR_TRUECOLOR=1  Ç¿ÖÆ 24 λɫ£¨×Ô¶¯¼ì²â²»×¼Ê±Ê¹Óã©
    NR_COLS=120     ¹Ì¶¨ÁÐÊý£¨Ìø¹ýÃæ°å£©
    NR_ROWS=40      ¹Ì¶¨ÐÐÊý£¨Ìø¹ýÃæ°å£©
    NR_NORES=1      Ìø¹ýÆô¶¯·Ö±æÂÊÃæ°å
    NR_PLAY=1       Ìø¹ý±êÌâ»­Ãæ£¨¿ìËÙÑÝʾ£©
    NR_BENCH=1      ÿ 20 Ö¡Ïò stderr Êä³öÖ¡Âʱ¨¸æ
    NR_CP=65001     Ç¿ÖÆ UTF-8 Êä³ö£»NR_CP=936 Ç¿ÖÆ GBK Êä³ö
    NR_FONT=0       ¹Ø±Õ¡¸µãÕó×ÖÌå -> TrueType ×ÖÌ塹µÄ×Ô¶¯Çл»
  ¿ÉÑ¡±àÒëºê£º-DNR_QUANT °ÑÑÕÉ«½µµ½Ã¿Í¨µÀ 6 λ£¬Ê¡Ô¼ 25% ´ø¿í£¨ÂýËÙ SSH£©¡£

  ²Ù×÷
    A / D »ò ¡û / ¡ú   Çл»ÅܵÀ
    ¿Õ¸ñ / W / ¡ü      ÌøÔ¾£¨¿ÕÖÐÔÙ°´Ò»´ÎΪ¶þ¶ÎÌø£©
    S / ¡ý             »¬²ù£¨¿ÕÖбäΪ¿ìËÙÏÂÔÒ£©
    P / ESC           ÔÝÍ£      R ÖØÐ¿ªÊ¼    Q Í˳ö
    V                 ÖØ¿ª·Ö±æÂÊ / Ëõ·ÅÃæ°å
    L                 Çл»ÖÐÎÄÊä³ö±àÂ루UTF-8 <-> GBK£©£¬ÖÐÎÄÂÒÂëʱ°´Ëü
    F                 ÂÖÁ÷Çл»ÖÕ¶Ë×ÖÌ壨µãÕó×ÖÌåµ¼ÖÂÂúÆÁÎʺÅʱ°´Ëü£©
    Ãæ°åÄÚ£º - / + Ëõ·ÅÖÕ¶Ë    0 »¹Ô­×ÖÌå
             Z ×Ô¶¯Ëõ·Åµ½×î´óÍø¸ñ
             R ÊÖ¶¯Ëõ·ÅºóÖØÐ¼ì²â
 =============================================================================
*/

#include <cstdio>
#include <cstdint>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <string>
#include <vector>
#include <algorithm>
#include <chrono>
#include <thread>

#ifdef _WIN32
  #define WIN32_LEAN_AND_MEAN
  #include <windows.h>
  #include <conio.h>
  #include <io.h>
#else
  #include <unistd.h>
  #include <termios.h>
  #include <sys/ioctl.h>
  #include <fcntl.h>
  #include <sys/select.h>
#endif

/* Console font scaling lives in kernel32 on Vista+.  Resolve it at runtime so
   the binary still starts on systems / pseudo-consoles where it is missing. */
#ifdef _WIN32
typedef BOOL (WINAPI *FontGetFn)(HANDLE,BOOL,PCONSOLE_FONT_INFOEX);
typedef BOOL (WINAPI *FontSetFn)(HANDLE,BOOL,PCONSOLE_FONT_INFOEX);
static FontGetFn pGetFont=nullptr;
static FontSetFn pSetFont=nullptr;
static inline void loadFontAPI(){
    HMODULE k=GetModuleHandleA("kernel32.dll");
    if(k){
        pGetFont=(FontGetFn)(void*)GetProcAddress(k,"GetCurrentConsoleFontEx");
        pSetFont=(FontSetFn)(void*)GetProcAddress(k,"SetCurrentConsoleFontEx");
    }
}
#endif
static bool ttyInteractive();   /* defined with the resolution picker */

static const float PI = 3.14159265358979323846f;

/* Hard ceiling for the character grid.  A 1200 x 300 grid is 1200 x 600
   subpixels; reachable only after heavy terminal zoom / a tiny font. */
static const int GRID_MAX_C=1200, GRID_MAX_R=300;

/* ±àÒëÆ÷д½ø×Ö·û´®×ÖÃæÁ¿µÄ±àÂ룺65001=UTF-8£¬936=GBK¡£
   ÔÚ Term::init() Àï̽²â£¬¹©×Ö·û·Ö×éÓëÕû֡תÂë¹²ÓᣱØÐ붨ÒåÔÚËùÓÐ
   Îı¾¹¤¾ßº¯Êý֮ǰ ¡ª¡ª Dev-C++ Óà -fexec-charset=gbk ±àÒëʱ£¬ºº×ÖÊÇ
   Ë«×Ö½Ú GBK£¬Èô°´ UTF-8 Öð×Ö½Ú²å SGR É«Â룬»á°ÑÁ½×ֽڲ𿪱ä³É '?'¡£ */
static unsigned int gSrcCP=65001;

/* ------------------------------------------------------------------ */
/* UTF-8 / GBK helpers - CJK glyphs occupy TWO terminal columns        */
/* ------------------------------------------------------------------ */
/* Byte count of the next character; 1 for ASCII or a broken sequence. */
static inline int u8Step(const unsigned char* p){
    unsigned char c=p[0];
    if(gSrcCP==936){
        if(c>=0x81 && c<=0xFE && p[1]>=0x40 && p[1]<=0xFE && p[1]!=0x7F)
            return 2;                       /* one GBK double-byte character */
        return 1;
    }
    int n=(c<0x80)?1:(c&0xE0)==0xC0?2:(c&0xF0)==0xE0?3:(c&0xF8)==0xF0?4:1;
    if(n>1){
        for(int i=1;i<n;i++)
            if((p[i]&0xC0)!=0x80) return 1;   /* also catches a truncated tail */
    }
    return n;
}
static inline unsigned int u8Code(const unsigned char* p,int n){
    if(n==2) return ((p[0]&0x1Fu)<<6)|(p[1]&0x3Fu);
    if(n==3) return ((p[0]&0x0Fu)<<12)|((p[1]&0x3Fu)<<6)|(p[2]&0x3Fu);
    if(n==4) return ((p[0]&0x07u)<<18)|((p[1]&0x3Fu)<<12)|((p[2]&0x3Fu)<<6)|(p[3]&0x3Fu);
    return p[0];
}
/* East-Asian width, simplified for the glyphs this UI actually uses:
   Latin-1 punctuation, arrows, geometric shapes and hearts are ONE column;
   CJK ideographs, CJK punctuation and fullwidth forms are TWO columns. */
static inline int u8Width(const unsigned char* p,int n){
    if(n==1) return 1;
    if(gSrcCP==936) return 2;               /* GBK Ë«×Ö½Ú×Ö·û = 2 ÁÐ */
    unsigned int cp=u8Code(p,n);
    if(cp<0x1100) return 1;
    if(cp>=0x2190&&cp<=0x21FF) return 1;   /* arrows */
    if(cp>=0x2300&&cp<=0x23FF) return 1;   /* misc technical */
    if(cp>=0x2500&&cp<=0x27BF) return 1;   /* box drawing, shapes, dingbats */
    return 2;                               /* CJK + fullwidth */
}
/* Display width in terminal columns - use this everywhere instead of strlen. */
static int dispWidth(const char* s){
    int w=0;
    for(const unsigned char* p=(const unsigned char*)s;*p;){
        int n=u8Step(p);
        w+=u8Width(p,n);
        p+=n;
    }
    return w;
}

/* ------------------------------------------------------------------ */
/* small math helpers                                                  */
/* ------------------------------------------------------------------ */
static inline float clampf(float v, float a, float b){ return v<a?a:(v>b?b:v); }
static inline int    imin(int a,int b){ return a<b?a:b; }
static inline int    imax(int a,int b){ return a>b?a:b; }
static inline float  lerpf(float a,float b,float t){ return a+(b-a)*t; }

typedef uint32_t u32;
static inline int  cl(int v){ return v<0?0:(v>255?255:v); }
static inline int  cR(u32 c){ return (int)((c>>16)&255); }
static inline int  cG(u32 c){ return (int)((c>>8)&255); }
static inline int  cB(u32 c){ return (int)(c&255); }
static inline u32  PK(int r,int g,int b){ return ((u32)cl(r)<<16)|((u32)cl(g)<<8)|(u32)cl(b); }
static inline u32  PKF(int r,int g,int b){ return ((u32)r<<16)|((u32)g<<8)|(u32)b; }
static inline u32  scaleCol(u32 c,float k){ return PK((int)(cR(c)*k),(int)(cG(c)*k),(int)(cB(c)*k)); }
static inline u32  mixCol(u32 a,u32 b,float t){
    t=clampf(t,0.0f,1.0f);
    return PK((int)(cR(a)+(cR(b)-cR(a))*t),
              (int)(cG(a)+(cG(b)-cG(a))*t),
              (int)(cB(a)+(cB(b)-cB(a))*t));
}
static inline u32  addCol(u32 a,u32 b){ return PK(cR(a)+cR(b),cG(a)+cG(b),cB(a)+cB(b)); }

static inline float hash01(int n){
    unsigned x=(unsigned)n*374761393u+668265263u;
    x=(x^(x>>13))*1274126177u;
    x=x^(x>>16);
    return (float)(x&0xffff)/65535.0f;
}

struct Vec3 {
    float x,y,z;
    Vec3(float a=0,float b=0,float c=0):x(a),y(b),z(c){}
};
static inline Vec3 V(float x,float y,float z){ return Vec3(x,y,z); }

/* deterministic RNG -------------------------------------------------- */
static uint32_t rngState=2463534242u;
static inline uint32_t rndU(){ rngState=rngState*1664525u+1013904223u; return rngState>>8; }
static inline float    rndf(){ return (float)(rndU()&0xffffff)/16777216.0f; }
static inline int      rndi(int n){ return (int)(rndU()%(unsigned)n); }

/* ------------------------------------------------------------------ */
/* terminal                                                            */
/* ------------------------------------------------------------------ */
static bool gFontChanged=false;  /* we changed the console font -> restore on exit */
static int  gScaleSteps=0;      /* net ANSI grid-resize requests sent            */
static int  gFontSteps=0;       /* net console-font shrink steps (Windows)       */
static int  gPreZoomC=0,gPreZoomR=0;  /* real grid before the first zoom        */
static int  gWinC=0,gWinR=0;    /* last detected REAL window grid              */
static bool gZoomWorks=false;   /* a programmatic zoom actually changed it      */
static std::string gZoomMsg;    /* one-line zoom status shown in the picker     */
static void restoreTermScale(); /* defined after the Term object                */
static void ensureCJKFont();    /* ditto: replace raster fonts that show '?'     */

/* ------------------------------------------------------------------ */
/* ÖÐÎÄÊä³ö±àÂë                                                        */
/* ------------------------------------------------------------------ */
/* gEnc: 0 = UTF-8 (65001)£¬1 = GBK (936)¡£°´Öն˵Äʵ¼Ê´úÂëÒ³Êä³ö£¬L ¼üÇл»¡£
   gSrcCP ÊÇ¡¸±àÒëÆ÷д½ø×Ö·û´®×ÖÃæÁ¿µÄ±àÂ롹¡£Dev-C++ ³£ÔÚ±àÒëÑ¡ÏîÀï´ø
   -fexec-charset=gbk£¬»ò°Ñ UTF-8 Ô´ÂëÁí´æ³É ANSI ¡ª¡ª ´ËʱÖÐÎÄÃæÁ¿¾ÍÊÇ GBK
   ×Ö½Ú¡£ÈôÈÔ°ÑÕûÖ¡°´ UTF-8 Ó²½âÂ룬ÿ¸öºº×Ö¶¼±ä³É U+FFFD£¬±àÂë³öÈ¥¾ÍÊÇ
   ÂúÆÁ '?'£¨ÕâÕýÊÇ Dev-C++ ¿ØÖÆÌ¨È«ÎʺŵÄÔ­Òò£©¡£ÔËÐÐʱ̽²âÒ»´Î¼´¿Éͬʱ
   ¼æÈÝ UTF-8 Óë GBK Á½ÖÖ±àÒë½á¹û¡£
   Ö¡ÄÚ°ë¿é×Ö·ûÏÈÓà ASCII ռλ·û HALF_MARK ±íʾ£¬Êä³öǰÔÙÕ¹¿ª³ÉÄ¿±ê±àÂëµÄ
   ? / ¨{£¬±£Ö¤ÕûÖ¡Ö»ÓÐÒ»ÖÖÔ´±àÂ룬תÂë¾ø²»»á²úÉúÆçÒå¡£ */
static int  gEnc=0;
static bool gConsole=false;
static const char HALF_MARK='\x01';    /* Ö¡ÄÚ°ë¿é×Ö·ûռλ·û */
static const char* encName(){ return gEnc?"GBK":"UTF-8"; }
static void applyEnc(){
#ifdef _WIN32
    if(gConsole) SetConsoleOutputCP(gEnc?936u:65001u);
#endif
}
static void toggleEnc(){ gEnc=gEnc?0:1; applyEnc(); }

/* °Ñռλ·ûÕ¹¿ª³É UTF-8 µÄ ? / ¨{£¨GBK ģʽÓà ¨{£¬Óë encode µÄÑÕÉ«¶Ôµ÷Ò»Ö£©¡£ */
static std::string expandHalf(const char* p,size_t n){
    const char* blk=gEnc?"\xE2\x96\x84":"\xE2\x96\x80";
    std::string o; o.reserve(n+n/4+4096);
    const char* cur=p,*end=p+n;
    while(cur<end){
        const char* q=(const char*)memchr(cur,HALF_MARK,(size_t)(end-cur));
        if(!q){ o.append(cur,(size_t)(end-cur)); break; }
        o.append(cur,(size_t)(q-cur));
        o+=blk;
        cur=q+1;
    }
    return o;
}
#ifdef _WIN32
#ifndef MB_ERR_INVALID_CHARS
#define MB_ERR_INVALID_CHARS 0x00000008
#endif
static unsigned int detectSourceCP(){
    /* ¸Ã×ÖÃæÁ¿ÓɱàÒëÆ÷°´Ö´ÐÐ×Ö·û¼¯Éú³É£ºUTF-8 »ò GBK¡£ */
    static const char probe[]="ÖÐÎÄ";
    return MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,probe,-1,nullptr,0)>0
           ? 65001u : 936u;
}
/* Ò»Ö¡ -> Ä¿±ê´úÂëÒ³×Ö½ÚÁ÷¡£ÄÚ²¿Í³Ò»¾­ UTF-16£¬ºº×ÖÓÀÔ¶²»»á±»»»³É '?'¡£ */
static std::string frameBytes(const char* p,size_t n){
    const UINT outCP=(UINT)(gEnc?936:65001);
    if(gSrcCP==65001 && outCP==65001) return expandHalf(p,n);
    const wchar_t half=gEnc?(wchar_t)0x2584:(wchar_t)0x2580;
    int wn=MultiByteToWideChar((UINT)gSrcCP,0,p,(int)n,nullptr,0);
    if(wn<=0) return std::string(p,n);
    std::wstring w((size_t)wn,L'\0');
    if(MultiByteToWideChar((UINT)gSrcCP,0,p,(int)n,&w[0],wn)<=0)
        return std::string(p,n);
    for(size_t i=0;i<w.size();i++)
        if(w[i]==(wchar_t)HALF_MARK) w[i]=half;
    int mb=WideCharToMultiByte(outCP,0,w.c_str(),wn,nullptr,0,nullptr,nullptr);
    if(mb<=0) return std::string(p,n);
    std::string o((size_t)mb,'\0');
    if(WideCharToMultiByte(outCP,0,w.c_str(),wn,&o[0],mb,nullptr,nullptr)<=0)
        return std::string(p,n);
    return o;
}
#endif

struct Term {
    int cols=100, rows=34;
    int origCols=100, origRows=34;
    bool tc=true;
#ifdef _WIN32
    HANDLE h=nullptr; DWORD oldMode=0; UINT oldCP=0;
    CONSOLE_FONT_INFOEX oldFont; bool fontSaved=false;
#else
    struct termios oldt; bool rawSet=false; int oldFlags=-1; std::string pend;
#endif
#ifdef _WIN32
    /* ConPTY (Windows Terminal) refuses GetConsoleScreenBufferInfo.  Park the
       cursor in the far corner and read the Cursor Position Report that comes
       back through the input queue: ESC [ row ; col R.  Bounded to 260 ms so a
       terminal that ignores the request cannot hang the picker. */
    bool cprSize(int& outC,int& outR){
        raw("\x1b[999;999H\x1b[6n");
        int st=0,row=0,col=0;
        auto t0=std::chrono::steady_clock::now();
        for(;;){
            if(_kbhit()){
                int ch=_getch()&0xff;
                if(st==0){ if(ch==27) st=1; }
                else if(st==1){ st=(ch=='[')?2:0; }
                else if(st==2){
                    if(ch>='0'&&ch<='9') row=row*10+(ch-'0');
                    else if(ch==';') st=3;
                    else { st=0; row=0; col=0; }
                }else if(st==3){
                    if(ch>='0'&&ch<='9') col=col*10+(ch-'0');
                    else if(ch=='R'){
                        if(row>0&&col>0){ outC=col; outR=row; return true; }
                        st=0; row=0; col=0;
                    }else { st=0; row=0; col=0; }
                }
                if(row>9999||col>9999) return false;
            }else{
                float ms=std::chrono::duration<float,std::milli>(
                    std::chrono::steady_clock::now()-t0).count();
                if(ms>260.0f) return false;
                std::this_thread::sleep_for(std::chrono::milliseconds(4));
            }
        }
    }
#endif
    /* real=true ignores NR_COLS / NR_ROWS and probes the physical window;
       used after a zoom so the newly available cells become selectable. */
    void querySize(bool real=false){
#ifdef _WIN32
        CONSOLE_SCREEN_BUFFER_INFO ci;
        if(GetConsoleScreenBufferInfo(h,&ci)){
            cols=ci.srWindow.Right-ci.srWindow.Left+1;
            rows=ci.srWindow.Bottom-ci.srWindow.Top+1;
        }else if(real && ttyInteractive()){
            int c=0,r=0;
            if(cprSize(c,r)){ cols=c; rows=r; }
        }
#else
        struct winsize ws;
        if(ioctl(STDOUT_FILENO,TIOCGWINSZ,&ws)==0 && ws.ws_col>0){ cols=ws.ws_col; rows=ws.ws_row; }
#endif
        if(!real){
            const char* ec=getenv("NR_COLS"); if(ec) cols=atoi(ec);
            const char* er=getenv("NR_ROWS"); if(er) rows=atoi(er);
        }
        cols=imax(42,imin(GRID_MAX_C,cols));
        rows=imax(18,imin(GRID_MAX_R,rows));
    }
    void init(){
#ifdef _WIN32
        h=GetStdHandle(STD_OUTPUT_HANDLE);
        oldCP=GetConsoleOutputCP();
        gConsole=(GetConsoleMode(h,&oldMode)!=0);
        gSrcCP=detectSourceCP();          /* ¼æÈÝ -fexec-charset=gbk µÄ±àÒë½á¹û */
        {
            /* ÏÖ´úÖÕ¶Ë£¨Windows Terminal / VS Code / ConEmu / mintty£©×ß UTF-8£»
               ´«Í³ conhost£¨Dev-C++ µ¯³öµÄ¿ØÖÆÌ¨£©Ò»ÂÉÓÅÏÈ GBK£¬±Ü¿ª
               CP 65001 ÔÚ conhost ÉϰѺº×ÖÏÔʾ³É '?' µÄÀÏÎÊÌâ¡£ */
            const bool modern=getenv("WT_SESSION")||getenv("TERM_PROGRAM")||
                              getenv("VSCODE_INJECTION")||getenv("ConEmuANSI");
            const char* cp=getenv("NR_CP");
            if(cp)                     gEnc=(atoi(cp)==936)?1:0;
            else if(!gConsole||modern) gEnc=0;
            else                       gEnc=IsValidCodePage(936)?1:0;
        }
        applyEnc();
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
        if(gConsole){
            DWORD m=oldMode|ENABLE_VIRTUAL_TERMINAL_PROCESSING;
            tc = SetConsoleMode(h,m)!=0;
            if(!tc) SetConsoleMode(h,oldMode);
        }else tc=false;
#else
        tcgetattr(STDIN_FILENO,&oldt);
        struct termios t=oldt;
        t.c_lflag &= ~(ICANON|ECHO);
        t.c_cc[VMIN]=0; t.c_cc[VTIME]=0;
        tcsetattr(STDIN_FILENO,TCSANOW,&t); rawSet=true;
        oldFlags=fcntl(STDIN_FILENO,F_GETFL,0);
        fcntl(STDIN_FILENO,F_SETFL,oldFlags|O_NONBLOCK);
        const char* ct=getenv("COLORTERM");
        tc = (ct && (strstr(ct,"truecolor")||strstr(ct,"24bit")));
        if(!tc){ const char* tp=getenv("TERM"); if(tp && (strstr(tp,"kitty")||strstr(tp,"iterm"))) tc=true; }
        pend.clear();
#endif
        /* NR_TRUECOLOR=1 forces 24-bit color if auto-detection got it wrong */
        const char* f=getenv("NR_TRUECOLOR");
        if(f && atoi(f)) tc=true;
        querySize();
        origCols=cols; origRows=rows;
        gWinC=cols;    gWinR=rows;
#ifdef _WIN32
        loadFontAPI();
        memset(&oldFont,0,sizeof(oldFont));
        oldFont.cbSize=sizeof(oldFont);
        if(pGetFont && pGetFont(h,FALSE,&oldFont) && oldFont.dwFontSize.Y>0)
            fontSaved=true;                       /* we can restore it on exit */
        ensureCJKFont();                          /* µãÕó×ÖÌå -> TrueType£¬½â¾öÂúÆÁ '?' */
        if(gFontChanged){                         /* ×ÖÌå±äÁË£¬×Ö·ûÍø¸ñ¿ÉÄÜËæÖ®±ä»¯ */
            querySize();
            origCols=cols; origRows=rows;
            gWinC=cols;    gWinR=rows;
        }
#endif
        raw("\x1b[?1049h\x1b[?7l\x1b[?25l\x1b[2J\x1b[H");
    }
    void restore(const char* finalMsg=nullptr){
        restoreTermScale();
        raw("\x1b[0m\x1b[?7h\x1b[?25h\x1b[?1049l\n");
        if(finalMsg) raw(finalMsg);          /* ÈÔÔÚÓÎÏ·ËùÓñàÂëÏÂÊä³ö */
#ifdef _WIN32
        if(gConsole){ SetConsoleMode(h,oldMode); SetConsoleOutputCP(oldCP); }
#else
        if(rawSet) tcsetattr(STDIN_FILENO,TCSANOW,&oldt);
        if(oldFlags>=0) fcntl(STDIN_FILENO,F_SETFL,oldFlags);
#endif
    }
    void raw(const std::string& s){ write(s.data(),s.size()); }
    void write(const char* p,size_t n){
#ifdef _WIN32
        /* È«²¿Êä³ö¶¼¾­¹ý frameBytes£ºÏȰ´Ô´Âë×Ö·û¼¯½âÂ룬ÔÙ°´¿ØÖÆÌ¨
           ´úÂëÒ³±àÂ룬ÖÐÎIJ»»áÒò±àÂë´íÅä±ä³É '?'¡£ */
        std::string conv=frameBytes(p,n);
        const char* q=conv.empty()?p:conv.data();
        size_t m=conv.empty()?n:conv.size();
        size_t off=0;
        while(off<m){
            size_t chunk=m-off; if(chunk>65536) chunk=65536;
            DWORD w=0;
            if(!WriteFile(h,q+off,(DWORD)chunk,&w,nullptr) || w==0) break;
            off+=w;
        }
#else
        std::string conv=expandHalf(p,n);
        ssize_t r=::write(STDOUT_FILENO,conv.data(),conv.size()); (void)r;
#endif
    }
    /* key codes: ASCII, or 1000+arrow-scancode (1072 up,1080 down,1075 left,1077 right) */
    bool poll(int& k){
#ifdef _WIN32
        if(!_kbhit()) return false;
        int c=_getch();
        if(c==0||c==224){ if(_kbhit()) k=1000+_getch(); else k=c; }
        else k=c;
        return true;
#else
        unsigned char tmp[64]; ssize_t n;
        while((n=::read(STDIN_FILENO,tmp,sizeof(tmp)))>0) pend.append((char*)tmp,(size_t)n);
        if(pend.empty()) return false;
        unsigned char c=(unsigned char)pend[0];
        if(c==27 && pend.size()>=3 && pend[1]=='['){
            char d=pend[2]; pend.erase(0,3);
            k = d=='A'?1072 : d=='B'?1080 : d=='C'?1077 : d=='D'?1075 : 27;
            return true;
        }
        pend.erase(0,1); k=(int)c; return true;
#endif
    }
} term;

/* Íø¸ñÔ½´ó£¬¹âÕ¤»¯ÏñËØÓëÿ֡ ANSI ×Ö½ÚÊý¶¼°´Ãæ»ýÔö³¤¡£³¬´óÍø¸ñ×Ô¶¯½µµÍ
   Ä¿±êÖ¡ÂÊ£¬±ÜÃâÉϰÙÍò×Ö½ÚµÄÖ¡°ÑÖն˹ܵÀѹ¿å£»120 x 40 ÈÔ±£³Ö 50 Ö¡/Ãë¡£ */
static float targetFPS(){
    int area=term.cols*term.rows;
    if(area>150000) return 10.0f;
    if(area> 60000) return 18.0f;
    if(area> 20000) return 30.0f;
    return 50.0f;
}

/* ------------------------------------------------------------------ */
/* terminal zoom : shrink the font, gain character cells, unlock the    */
/*                 higher resolution presets                           */
/* ------------------------------------------------------------------ */

/* Re-read the PHYSICAL window without disturbing the render grid. */
static void detectWindow(){
    int pc=term.cols, pr=term.rows;
    term.querySize(true);
    gWinC=term.cols; gWinR=term.rows;
    term.cols=pc;    term.rows=pr;
}

/* Undo everything we did to the terminal before leaving the alternate
   screen.  Called from Term::restore(). */
/* Dev-C++ / ´«Í³ conhost ³£Ä¬ÈÏʹÓḵãÕó×ÖÌ塹(Raster Fonts)£ºËü¼ÈûÓÐ
   ÖÐÎÄ×ÖÐÎҲûÓÐ ? / ¨{ ×ÖÐΣ¬ºº×ÖºÍÕûÆÁ°ë¿é¶¼»á±»»­³É '?'¡£Çе½ TrueType
   µÈ¿í×ÖÌå¼´¿É£»±£³ÖÔ­×ֺţ¬Ö»»»×ÖÌåÃû¡£Í˳öʱÓÉ restoreTermScale »¹Ô­¡£ */
#ifndef TMPF_TRUETYPE
#define TMPF_TRUETYPE 0x04
#endif
static const wchar_t* kFontFaces[]={
    L"Consolas", L"\u65B0\u5B8B\u4F53", L"Microsoft YaHei Mono", L"Lucida Console"
};
static const char* kFontNames[]={"Consolas","NSimSun","YaHei Mono","Lucida Console"};
static int gFontIdx=0;
static const char* fontLabel(){ return kFontNames[gFontIdx]; }
static bool applyFont(int idx){
#ifdef _WIN32
    if(!pGetFont||!pSetFont||!term.fontSaved) return false;
    CONSOLE_FONT_INFOEX f;
    memset(&f,0,sizeof(f)); f.cbSize=sizeof(f);
    if(!pGetFont(term.h,FALSE,&f)||f.dwFontSize.Y<=0) return false;
    f.FontFamily=TMPF_TRUETYPE; f.FontWeight=400;
    const wchar_t* src=kFontFaces[idx];
    int i=0;
    for(;i<LF_FACESIZE-1 && src[i];i++) f.FaceName[i]=src[i];
    f.FaceName[i]=L'\0';
    if(!pSetFont(term.h,FALSE,&f)) return false;
    gFontIdx=idx; gFontChanged=true;
    return true;
#else
    (void)idx; return false;
#endif
}
static void ensureCJKFont(){
#ifdef _WIN32
    if(!gConsole||!term.fontSaved||!pGetFont||!pSetFont) return;
    const char* nf=getenv("NR_FONT");
    if(nf && !atoi(nf)) return;                 /* NR_FONT=0 ¹Ø±Õ×Ô¶¯»»×ÖÌå */
    CONSOLE_FONT_INFOEX cur;
    memset(&cur,0,sizeof(cur)); cur.cbSize=sizeof(cur);
    if(!pGetFont(term.h,FALSE,&cur)) return;
    if((cur.FontFamily&TMPF_TRUETYPE) && cur.FaceName[0]) return;
    for(int i=0;i<4;i++) if(applyFont(i)) return;
#endif
}
static bool cycleFont(){
    for(int d=1;d<=4;d++) if(applyFont((gFontIdx+d)%4)) return true;
    return false;
}

static void restoreTermScale(){
#ifdef _WIN32
    if(gFontChanged && term.fontSaved && pSetFont){
        CONSOLE_FONT_INFOEX f=term.oldFont;
        f.cbSize=sizeof(f);
        pSetFont(term.h,FALSE,&f);
    }
#endif
    if(gScaleSteps!=0){
        int rc=(gPreZoomC>0?gPreZoomC:term.origCols);
        int rr=(gPreZoomR>0?gPreZoomR:term.origRows);
        char b[64];
        snprintf(b,sizeof(b),"\x1b[8;%d;%dt",rr,rc);
        term.raw(b);
    }
    gFontChanged=false; gScaleSteps=0; gFontSteps=0;
}

/* Windows conhost: one step is one point of font height, with the width
   scaled proportionally so the cells keep their aspect ratio. */
static bool winFontStep(int dir,bool reset){
#ifdef _WIN32
    if(!pGetFont||!pSetFont||!term.fontSaved) return false;
    CONSOLE_FONT_INFOEX f;
    memset(&f,0,sizeof(f)); f.cbSize=sizeof(f);
    if(!pGetFont(term.h,FALSE,&f) || f.dwFontSize.Y<=0) return false;
    if(reset){
        f=term.oldFont; f.cbSize=sizeof(f);
    }else{
        int nh=(int)f.dwFontSize.Y+(dir<0?-1:1);
        if(nh<6||nh>72) return false;
        if(f.dwFontSize.X>0){
            int nw=(int)(f.dwFontSize.X*(float)nh/(float)f.dwFontSize.Y+0.5f);
            f.dwFontSize.X=(SHORT)imax(3,nw);
        }
        f.dwFontSize.Y=(SHORT)nh;
    }
    return pSetFont(term.h,FALSE,&f)!=0;
#else
    (void)dir; (void)reset; return false;
#endif
}

/* xterm / WezTerm / Konsole / kitty honour CSI 8 ; rows ; cols t. */
static void ansiGridStep(int dir){
    int c=gWinC, r=gWinR;
    if(dir<0){ c=(int)(c*1.10f)+2; r=(int)(r*1.10f)+1; }
    else     { c=(int)(c*0.90f);   r=(int)(r*0.90f);   }
    c=imax(42,imin(GRID_MAX_C,c)); r=imax(18,imin(GRID_MAX_R,r));
    char b[64];
    snprintf(b,sizeof(b),"\x1b[8;%d;%dt",r,c);
    term.raw(b);
    gScaleSteps += (dir<0?1:-1);
}

static void zoomStep(int dir){
    if(gPreZoomC<=0){ gPreZoomC=gWinC; gPreZoomR=gWinR; }
    int bc=gWinC, br=gWinR;
    bool fontOk=false;
#ifdef _WIN32
    fontOk=winFontStep(dir,false);
    if(fontOk){ gFontChanged=true; gFontSteps += (dir<0?-1:1); }
#endif
    if(!fontOk) ansiGridStep(dir);
    /* Give conhost / the terminal emulator time to reflow and resize. */
    std::this_thread::sleep_for(std::chrono::milliseconds(150));
    detectWindow();
    int dc=gWinC-bc, dr=gWinR-br;
    char b[176];
    if(dc>0||dr>0){
        gZoomWorks=true;
        snprintf(b,sizeof(b),
                 "   %s: %d x %d -> %d x %d   (ÁÐ %+d / ÐÐ %+d)",
                 dir<0?"ËõС×ÖÌå":"·Å´ó×ÖÌå",bc,br,gWinC,gWinR,dc,dr);
    }else if(fontOk){
        snprintf(b,sizeof(b),
                 "   ×ÖÌåÒÑ¸Ä %+d ²½£»Íø¸ñÈÔΪ %d x %d£¬Çë×î´ó»¯´°¿Úºó°´ R",
                 gFontSteps,gWinC,gWinR);
    }else{
        snprintf(b,sizeof(b),
                 "   ´ËÖն˲»Ö§³Ö³ÌÐòËõ·Å - ÇëÓà Ctrl+- / ¹öÂÖ£¬ÔÙ°´ R");
    }
    gZoomMsg=b;
}

static void zoomReset(){
    if(gFontChanged){
        winFontStep(0,true);
        gFontChanged=false; gFontSteps=0;
    }
    if(gScaleSteps!=0 && gPreZoomC>0){
        char q[64];
        snprintf(q,sizeof(q),"\x1b[8;%d;%dt",gPreZoomR,gPreZoomC);
        term.raw(q);
        gScaleSteps=0;
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(150));
    detectWindow();
    char b[128];
    snprintf(b,sizeof(b),"   ÒÑ»¹Ô­Ô­Ê¼×ÖÌå - µ±Ç°´°¿Ú %d x %d ¸ñ",gWinC,gWinR);
    gZoomMsg=b;
}

static void zoomAuto(){
    if(gPreZoomC<=0){ gPreZoomC=gWinC; gPreZoomR=gWinR; }
    int stall=0;
    for(int i=0;i<24 && (gWinC<GRID_MAX_C||gWinR<GRID_MAX_R);i++){
        int bc=gWinC, br=gWinR;
        zoomStep(-1);
        if(gWinC<=bc && gWinR<=br){ if(++stall>=2) break; }
        else stall=0;
    }
    char b[176];
    if(gWinC>=GRID_MAX_C&&gWinR>=GRID_MAX_R)
        snprintf(b,sizeof(b),"   ÒѴKÏÞÍø¸ñ %d x %d£¬°´ ×Ô¶¯ Ñ¡Ï¾Ö£¨Ö¡ÂÊ×Ô¶¯½µµÍ£©",
                 gWinC,gWinR);
    else
        snprintf(b,sizeof(b),"   ¿É´ï×î´óÍø¸ñ %d x %d - Çë×î´ó»¯´°¿Ú»òÊÖ¶¯Ëõ·Åºó°´ R",
                 gWinC,gWinR);
    gZoomMsg=b;
}

/* Windows' default timer tick is ~15.6 ms, which would cap a 50 fps loop at
   ~31 fps. Ask the multimedia timer for 1 ms resolution, loaded dynamically
   so no extra library needs to be linked. */
#ifdef _WIN32
typedef UINT (WINAPI *TBP)(UINT);
static HMODULE winmmH=nullptr; static TBP pBegin=nullptr,pEnd=nullptr;
static void hiresTimer(bool on){
    if(on){
        winmmH=LoadLibraryA("winmm.dll");
        if(winmmH){
            pBegin=(TBP)(void*)GetProcAddress(winmmH,"timeBeginPeriod");
            pEnd  =(TBP)(void*)GetProcAddress(winmmH,"timeEndPeriod");
            if(pBegin) pBegin(1);
        }
    }else if(winmmH){
        if(pEnd) pEnd(1);
        FreeLibrary(winmmH);
        winmmH=nullptr;
    }
}
#else
static inline void hiresTimer(bool){}
#endif

/* color -> SGR code (truecolor rgb, or quantized 16-color index) ------ */
static inline u32 quant16(u32 c){
    int r=cR(c),g=cG(c),b=cB(c);
    int ri=r>190?2:(r>64?1:0), gi=g>190?2:(g>64?1:0), bi=b>190?2:(b>64?1:0);
    int idx=(ri>0?1:0)|(gi>0?2:0)|(bi>0?4:0);
    if(ri==2||gi==2||bi==2) idx|=8;
    return (u32)idx;
}
static inline u32 codeOf(u32 rgb){
#ifdef NR_QUANT
    return term.tc ? (rgb&0x00fcfcfcu) : quant16(rgb); /* 6 bits/channel: fewer SGR runs */
#else
    return term.tc ? (rgb&0x00ffffffu) : quant16(rgb);
#endif
}
static inline void dec(std::string& s,int v){
    char b[4]; int n=0;
    if(v==0){ s+='0'; return; }
    while(v>0){ b[n++]=(char)('0'+v%10); v/=10; }
    while(n--) s+=b[n];
}
static void sgrFG(std::string& s,u32 code){
    if(term.tc){
        s+="\x1b[38;2;"; dec(s,(int)((code>>16)&255)); s+=';';
        dec(s,(int)((code>>8)&255)); s+=';'; dec(s,(int)(code&255)); s+='m';
    }else{ s+="\x1b["; dec(s,code<8?30+(int)code:90+((int)code-8)); s+='m'; }
}
static void sgrBG(std::string& s,u32 code){
    if(term.tc){
        s+="\x1b[48;2;"; dec(s,(int)((code>>16)&255)); s+=';';
        dec(s,(int)((code>>8)&255)); s+=';'; dec(s,(int)(code&255)); s+='m';
    }else{ s+="\x1b["; dec(s,code<8?40+(int)code:100+((int)code-8)); s+='m'; }
}

/* ------------------------------------------------------------------ */
/* framebuffer / renderer state                                        */
/* ------------------------------------------------------------------ */
static int   W=0,H=0;                 /* H = 2 * terminal rows (subpixels) */
static float focal=70.0f;
static std::vector<u32>   pix;
static std::vector<float> zb;
static std::vector<unsigned char> vig;
static u32   FOG = PK(74,44,84);
static float gTime=0.0f;
static float camX=0,camY=2.85f,camZ=-6.6f,pitch=-0.125f,ca=1.0f,sa=0.0f,horizon=30.0f;

static float FOG_LUT[256];
static void initFog(){
    for(int i=0;i<256;i++){
        float z=i*0.36f;
        FOG_LUT[i]=fminf(0.88f,1.0f-expf(-z*0.0145f));
    }
}
static inline float fogAt(float z){
    int i=(int)(z/0.36f);
    if(i<0)i=0; if(i>255)i=255;
    return FOG_LUT[i];
}
static void resize(){
    W=term.cols; H=term.rows*2;
    pix.assign((size_t)W*H,0);
    zb.assign((size_t)W*H,0.0f);
    vig.assign((size_t)W*H,64);
    focal=(float)W*0.5f/tanf(0.70f);
    for(int y=0;y<H;y++)for(int x=0;x<W;x++){
        float nx=(x-W*0.5f)/(W*0.5f), ny=(y-H*0.5f)/(H*0.5f);
        float d=sqrtf(nx*nx*0.82f+ny*ny*0.72f);
        float v=1.0f-0.44f*powf(fminf(1.0f,d),1.7f);
        vig[(size_t)y*W+x]=(unsigned char)(v*64.0f);
    }
}

/* ------------------------------------------------------------------ */
/* projection + triangle rasterizer                                    */
/* ------------------------------------------------------------------ */
struct V2 { float x,y,w; };  /* w = 1 / cameraZ */

static inline bool project(const Vec3& q,V2& o){
    float dx=q.x-camX, dy=q.y-camY, dz=q.z-camZ;
    float yc=dy*ca-dz*sa;
    float zc=dy*sa+dz*ca;
    if(zc<0.22f) return false;               /* behind / too close to near plane */
    o.x=W*0.5f+dx*focal/zc;
    o.y=H*0.5f-yc*focal/zc;
    o.w=1.0f/zc;
    return true;
}

static void raster(const V2& a,const V2& b,const V2& c,u32 c0,u32 c1,u32 c2){
    float mnx=fminf(a.x,fminf(b.x,c.x)), mxx=fmaxf(a.x,fmaxf(b.x,c.x));
    float mny=fminf(a.y,fminf(b.y,c.y)), mxy=fmaxf(a.y,fmaxf(b.y,c.y));
    if(mxx<0||mxy<0||mnx>=(float)W||mny>=(float)H) return;
    int x0=imax(0,(int)floorf(mnx)), x1=imin(W-1,(int)ceilf(mxx));
    int y0=imax(0,(int)floorf(mny)), y1=imin(H-1,(int)ceilf(mxy));
    if(x0>x1||y0>y1) return;
    float den=(b.y-c.y)*(a.x-c.x)+(c.x-b.x)*(a.y-c.y);
    if(fabsf(den)<0.0001f) return;
    float inv=1.0f/den;
    float px=(float)x0+0.5f, py=(float)y0+0.5f;
    float w0row=((b.y-c.y)*(px-c.x)+(c.x-b.x)*(py-c.y))*inv;
    float w1row=((c.y-a.y)*(px-c.x)+(a.x-c.x)*(py-c.y))*inv;
    float d0x=(b.y-c.y)*inv, d0y=(c.x-b.x)*inv;
    float d1x=(c.y-a.y)*inv, d1y=(a.x-c.x)*inv;
    bool flat=(c0==c1&&c1==c2);
    int r0=cR(c0),g0=cG(c0),b0=cB(c0);
    int r1=cR(c1),g1=cG(c1),bb1=cB(c1);
    int r2=cR(c2),g2=cG(c2),b2=cB(c2);
    for(int y=y0;y<=y1;y++){
        /* Exact horizontal span of the triangle on this scanline, solved from
           the three half-plane inequalities. Avoids walking empty pixels of
           thin / steep triangles (huge win for rails and distant buildings). */
        float tlo=0.0f, thi=(float)(x1-x0);
        float a0=w0row, a1=w1row, a2=1.0f-a0-a1;
        float d2x=-d0x-d1x;
        float A[3]={a0,a1,a2}, D[3]={d0x,d1x,d2x};
        for(int q=0;q<3;q++){
            if(fabsf(D[q])<1e-9f){ if(A[q]<0.0f) thi=-1.0f; continue; }
            float t=-A[q]/D[q];
            if(D[q]>0.0f){ if(t>tlo) tlo=t; }
            else         { if(t<thi) thi=t; }
        }
        int xs=x0+(int)ceilf(tlo-1e-4f), xe=x0+(int)floorf(thi+1e-4f);
        if(xs<x0) xs=x0;
        if(xe>x1) xe=x1;
        if(xs<=xe){
            float w0=a0+d0x*(float)(xs-x0), w1=a1+d1x*(float)(xs-x0);
            size_t idx=(size_t)y*W+xs;
            for(int x=xs;x<=xe;x++,idx++){
                float w2=1.0f-w0-w1;
                if(w0>=-1e-5f&&w1>=-1e-5f&&w2>=-1e-5f){
                    float iw=w0*a.w+w1*b.w+w2*c.w;
                    if(iw>zb[idx]){
                        zb[idx]=iw;
                        if(flat) pix[idx]=c0;
                        else pix[idx]=PKF((int)(w0*r0+w1*r1+w2*r2),
                                          (int)(w0*g0+w1*g1+w2*g2),
                                          (int)(w0*b0+w1*bb1+w2*b2));
                    }
                }
                w0+=d0x; w1+=d1x;
            }
        }
        w0row+=d0y; w1row+=d1y;
    }
}

static void tri3(const Vec3& a,const Vec3& b,const Vec3& c,u32 col,float bright=1.0f,bool emis=false){
    V2 p0,p1,p2;
    if(!project(a,p0)||!project(b,p1)||!project(c,p2)) return;
    u32 base=scaleCol(col,bright);
    u32 q0,q1,q2;
    if(emis) q0=q1=q2=base;
    else{
        q0=mixCol(base,FOG,fogAt(1.0f/p0.w));
        q1=mixCol(base,FOG,fogAt(1.0f/p1.w));
        q2=mixCol(base,FOG,fogAt(1.0f/p2.w));
    }
    raster(p0,p1,p2,q0,q1,q2);
}
static void quad3(const Vec3& a,const Vec3& b,const Vec3& c,const Vec3& d,
                  u32 col,float bright=1.0f,bool emis=false){
    tri3(a,b,c,col,bright,emis);
    tri3(a,c,d,col,bright,emis);
}

/* eight corners -> six shaded quads (no culling, z-buffer decides) */
static void box(const Vec3& c,const Vec3& s,u32 col,float bright=1.0f,
                bool emis=false,float rot=0.0f,const Vec3& piv=Vec3()){
    Vec3 p[8];
    float cr=cosf(rot), sr=sinf(rot);
    for(int i=0;i<8;i++){
        float x=c.x+((i&1)?0.5f:-0.5f)*s.x;
        float y=c.y+((i&2)?0.5f:-0.5f)*s.y;
        float z=c.z+((i&4)?0.5f:-0.5f)*s.z;
        if(rot!=0.0f){
            float ry=y-piv.y, rz=z-piv.z;
            y=piv.y+ry*cr-rz*sr;
            z=piv.z+ry*sr+rz*cr;
        }
        p[i]=Vec3(x,y,z);
    }
    static const int F[6][4]={
        {0,1,2,3},{5,4,7,6},{3,2,6,7},{4,5,1,0},{4,0,3,7},{1,5,6,2}
    };
    static const float K[6]={0.90f,0.50f,1.22f,0.38f,0.66f,1.06f};
    u32 base=scaleCol(col,bright);
    for(int f=0;f<6;f++){
        const Vec3& A=p[F[f][0]]; const Vec3& B=p[F[f][1]]; const Vec3& C=p[F[f][2]];
        float e1x=B.x-A.x,e1y=B.y-A.y,e1z=B.z-A.z;
        float e2x=C.x-A.x,e2y=C.y-A.y,e2z=C.z-A.z;
        /* All six faces are wound so this normal points INTO the box.
           If it points at the camera the face is hidden -> cull it. */
        float nx=e1y*e2z-e1z*e2y, ny=e1z*e2x-e1x*e2z, nz=e1x*e2y-e1y*e2x;
        if(nx*(camX-A.x)+ny*(camY-A.y)+nz*(camZ-A.z)>0.0f) continue;
        quad3(A,B,C,p[F[f][3]],scaleCol(base,K[f]),1.0f,emis);
    }
}
static void floorStrip(float x0,float z0,float x1,float z1,float w,u32 col,bool emis){
    quad3(V(x0-w,0.025f,z0),V(x0+w,0.025f,z0),
          V(x1+w,0.025f,z1),V(x1-w,0.025f,z1),col,1.0f,emis);
}

/* ------------------------------------------------------------------ */
/* procedural background                                               */
/* ------------------------------------------------------------------ */
static u32 skyGrad(float t){
    static const float P[6]={0.0f,0.22f,0.48f,0.70f,0.87f,1.0f};
    static const u32   C[6]={PK(5,7,26),PK(20,16,54),PK(62,30,86),
                             PK(146,54,96),PK(238,116,96),PK(255,190,124)};
    t=clampf(t,0.0f,1.0f);
    for(int i=0;i<5;i++) if(t<=P[i+1]) return mixCol(C[i],C[i+1],(t-P[i])/(P[i+1]-P[i]));
    return C[5];
}

static void skyline(float baseY,float scroll,float maxH,u32 col,int seed,float winChance){
    const float bw=7.0f;
    float off=fmodf(scroll,bw);
    int n=(int)(W/bw)+4;
    for(int i=-2;i<n;i++){
        float h=maxH*(0.28f+0.72f*hash01(seed+i*37));
        float w=bw*(0.55f+0.40f*hash01(seed+i*91+7));
        float x0=(float)i*bw-off, y0=baseY-h;
        u32 bc=mixCol(col,PK(50,34,76),hash01(seed+i*53)*0.55f);
        int xi0=imax(0,(int)floorf(x0)), xi1=imin(W-1,(int)ceilf(x0+w));
        int yi0=imax(0,(int)floorf(y0)), yi1=imin(H-1,(int)baseY);
        for(int y=yi0;y<=yi1;y++){
            if(y<y0) continue;
            for(int x=xi0;x<=xi1;x++){
                if(x<x0||x>=x0+w) continue;
                pix[(size_t)y*W+x]=bc;
            }
        }
        for(int wy=(int)y0+2; wy<baseY-1; wy+=3){
            for(int wx=(int)x0+1; wx<x0+w-1; wx+=3){
                float hs=hash01(seed+i*1009+wy*31+wx*7);
                if(hs<winChance && wx>=0 && wx<W && wy>=0 && wy<H){
                    u32 wc=(hs<winChance*0.45f)?PK(255,198,120):PK(120,212,255);
                    pix[(size_t)wy*W+wx]=wc;
                    if(wx+1<W) pix[(size_t)wy*W+wx+1]=scaleCol(wc,0.45f);
                }
            }
        }
        if(0.5f+0.5f*sinf(gTime*2.1f+i*2.3f)>0.55f){
            int xx=(int)(x0+w*0.5f), yy=(int)y0-1;
            if(xx>=0&&xx<W&&yy>=0&&yy<H) pix[(size_t)yy*W+xx]=PK(255,92,116);
        }
    }
}

static void drawSky(){
    float hz=clampf(horizon,2.0f,(float)H-2.0f);
    for(int y=0;y<H;y++){
        u32 row;
        if(y<hz) row=skyGrad((float)y/fmaxf(1.0f,hz));
        else{
            float t=clampf((y-hz)/fmaxf(1.0f,H-hz),0.0f,1.0f);
            row=mixCol(PK(104,56,96),PK(8,8,24),powf(t,0.62f));
        }
        size_t i=(size_t)y*W;
        for(int x=0;x<W;x++) pix[i+x]=row;
    }
    /* horizon glow */
    int hy=(int)hz;
    for(int d=-3;d<=4;d++){
        int y=hy+d; if(y<0||y>=H) continue;
        float a=(d<0?0.16f:0.30f)*expf(-fabsf((float)d)*0.42f);
        for(int x=0;x<W;x++){
            size_t i=(size_t)y*W+x;
            pix[i]=addCol(pix[i],scaleCol(PK(255,120,96),a));
        }
    }
    /* stars */
    for(int i=0;i<90;i++){
        int x=(int)(hash01(i*13+1)*W);
        int y=(int)(hash01(i*29+77)*hz*0.78f);
        float tw=0.5f+0.5f*sinf(gTime*1.8f+hash01(i*7)*12.0f);
        if(tw<0.55f||x<0||x>=W||y<0||y>=H) continue;
        u32 c=scaleCol(PK(210,225,255),tw*0.75f);
        pix[(size_t)y*W+x]=addCol(pix[(size_t)y*W+x],c);
    }
    /* synthwave sun with glow + scan bands */
    float sx=W*0.66f-camX*2.2f, sy=hz-H*0.155f, rad=H*0.125f;
    int bx0=imax(0,(int)(sx-rad*3)), bx1=imin(W-1,(int)(sx+rad*3));
    int by0=imax(0,(int)(sy-rad*3)), by1=imin(H-1,(int)(sy+rad*3));
    for(int y=by0;y<=by1;y++)for(int x=bx0;x<=bx1;x++){
        float dx=(x-sx)/rad, dy=(y-sy)/rad;
        float d=sqrtf(dx*dx+dy*dy);
        size_t i=(size_t)y*W+x;
        if(d<1.0f){
            u32 core=mixCol(PK(255,240,178),PK(255,118,112),clampf((dy+1.0f)*0.5f,0,1));
            if(dy>0.04f){
                float band=fmodf(dy*7.5f,1.0f);
                if(band<0.34f) core=mixCol(core,skyGrad((float)y/fmaxf(1.0f,hz)),0.78f);
            }
            pix[i]=core;
        }else{
            float g=0.60f*expf(-(d-1.0f)*2.3f);
            pix[i]=addCol(pix[i],scaleCol(PK(255,116,92),g));
        }
    }
    /* drifting neon clouds */
    for(int i=0;i<7;i++){
        float cy=hz*(0.13f+0.60f*hash01(i*17+3));
        float len=W*(0.13f+0.22f*hash01(i*23+9));
        float span=W+len*2.0f;
        float cx=fmodf(gTime*(2.2f+i*0.6f)+hash01(i*41)*span,span)-len;
        for(int x=imax(0,(int)cx);x<imin(W,(int)(cx+len));x++){
            float t=(x-cx)/len;
            float a=sinf(t*PI)*0.15f;
            int yy=(int)(cy+sinf(t*8.0f+i)*1.5f);
            for(int dd=-1;dd<=1;dd++){
                int y=yy+dd; if(y<0||y>=H)continue;
                size_t idx=(size_t)y*W+x;
                pix[idx]=addCol(pix[idx],scaleCol(PK(255,158,176),a*(dd==0?1.0f:0.4f)));
            }
        }
    }
    /* two parallax skyline layers - deliberately low so the sun stays visible */
    skyline(hz+1.0f, camZ*0.34f+camX*1.6f, H*0.095f, PK(48,30,72), 1337, 0.20f);
    skyline(hz+3.0f, camZ*0.88f+camX*4.0f, H*0.165f, PK(24,20,52), 8123, 0.30f);
}

/* ------------------------------------------------------------------ */
/* game state                                                          */
/* ------------------------------------------------------------------ */
enum { MENU=0, PLAY=1, PAUSE=2, OVER=3 };
enum { T_LOW=0, T_HIGH=1, T_WALL=2 };

static const float LANEX[3]={-3.2f,0.0f,3.2f};
static const float HALF=5.4f, TILE=3.0f, DRAW=68.0f;

struct Obstacle { float z; int lane; int type; bool passed; };
struct Coin     { Vec3 p; int type; bool got; };   /* 0=gold, 1=shield */
struct Gap      { float a,b; };
struct Part     { Vec3 p,v; float life,max,size; u32 col; };

static int   state=MENU;
static float pz=0,py=0,vy=0,px=0;
static int   lane=1, jumps=0;
static bool  onGround=true;
static float speed=13.0f, speedPenalty=0.0f, slideT=0.0f, invuln=0.0f;
static float shake=0.0f, flashAmt=0.0f, runPhase=0.0f, trailAcc=0.0f;
static float menuTimer=0.0f, comboT=0.0f, msgT=0.0f;
static int   hpNow=3, shields=0, combo=0, coinCount=0, score=0, best=0, distM=0;
static bool  newBest=false;
static char  msgBuf[64]={0};
static float nextZ=20.0f;
static std::vector<Obstacle> obs;
static std::vector<Coin>     coinList;
static std::vector<Gap>      gaps;
static std::vector<Part>     parts;

static void setMsg(const char* s,float t){ snprintf(msgBuf,sizeof(msgBuf),"%s",s); msgT=t; }

static void addCoin(float x,float y,float z,int type){
    Coin c; c.p=V(x,y,z); c.type=type; c.got=false; coinList.push_back(c);
}
static void coinLine(int l,float z,float y,int n,float step){
    for(int i=0;i<n;i++) addCoin(LANEX[l],y,z+(float)i*step,0);
}
static void coinArc(int l,float z0,float z1,float peak){
    int n=9;
    for(int i=0;i<n;i++){
        float t=(float)i/(n-1);
        addCoin(LANEX[l],0.90f+sinf(t*PI)*peak,lerpf(z0,z1,t),0);
    }
}
static void spawnBurst(float x,float y,float z,u32 col,int n,float power=1.0f){
    for(int i=0;i<n;i++){
        if(parts.size()>430) break;
        Part p;
        float a=rndf()*PI*2.0f, e=(rndf()-0.35f)*2.0f;
        float sp=(2.0f+rndf()*7.0f)*power;
        p.p=V(x+(rndf()-0.5f)*0.4f,y+(rndf()-0.5f)*0.4f,z+(rndf()-0.5f)*0.4f);
        p.v=V(cosf(a)*sp,e*sp*0.8f,sinf(a)*sp*0.7f-1.0f);
        p.max=p.life=0.35f+rndf()*0.55f;
        p.size=0.055f+rndf()*0.075f; p.col=col;
        parts.push_back(p);
    }
}

static void resetGame(bool menu){
    state=menu?MENU:PLAY;
    pz=0; py=0; vy=0; px=0; lane=1; jumps=0; onGround=true;
    speed=13.0f; speedPenalty=0; slideT=0; invuln=0; shake=0; flashAmt=0;
    runPhase=0; trailAcc=0; comboT=0; msgT=0; menuTimer=0;
    hpNow=3; shields=0; combo=0; coinCount=0; score=0; distM=0;
    newBest=false;                 /* best itself survives across runs */
    nextZ=24.0f; camX=0;
    obs.clear(); coinList.clear(); gaps.clear(); parts.clear();
    msgBuf[0]=0;
}

static void spawnWorld(){
    bool menu=(state==MENU);
    float ahead=pz+DRAW+34.0f;
    int guard=0;
    while(nextZ<ahead && guard++<80){
        float z=nextZ;
        int l=rndi(3);
        if(menu){
            coinLine(l,z,0.95f,6,1.55f);
            if(rndi(3)==0) coinArc(rndi(3),z+8.0f,z+15.0f,1.6f);
            nextZ += 15.0f+rndf()*7.0f;
            continue;
        }
        int pat=rndi(8);
        switch(pat){
        case 0: /* hurdle -> jump */
            obs.push_back(Obstacle{z,l,T_LOW,false});
            coinArc(l,z-3.2f,z+3.6f,1.85f);
            break;
        case 1: /* overhead beam -> slide */
            obs.push_back(Obstacle{z,l,T_HIGH,false});
            coinLine(l,z-4.0f,0.60f,7,1.35f);
            break;
        case 2: /* single wall -> switch lane */
            obs.push_back(Obstacle{z,l,T_WALL,false});
            coinLine((l+1+rndi(2))%3,z-4.0f,0.95f,6,1.55f);
            break;
        case 3: { /* two walls, one safe lane */
            int safe=rndi(3);
            for(int k=0;k<3;k++) if(k!=safe) obs.push_back(Obstacle{z,k,T_WALL,false});
            coinLine(safe,z-4.0f,0.95f,7,1.45f);
            break; }
        case 4: { /* gap in the rooftop */
            float gl=3.6f+rndf()*1.9f;
            gaps.push_back(Gap{z,z+gl});
            coinArc(1,z-1.2f,z+gl+1.2f,2.25f);
            break; }
        case 5: { /* mixed: jump lane A, slide lane B, run lane C */
            int l2=(l+1+rndi(2))%3;
            obs.push_back(Obstacle{z,l,T_LOW,false});
            obs.push_back(Obstacle{z,l2,T_HIGH,false});
            coinLine(3-l-l2,z-3.0f,0.95f,5,1.5f);
            break; }
        case 6: /* reward stretch */
            for(int k=0;k<3;k++) coinLine(k,z,0.95f,5,1.5f);
            break;
        default: /* double hurdle with a coin bridge */
            obs.push_back(Obstacle{z,l,T_LOW,false});
            obs.push_back(Obstacle{z+6.0f,(l+1)%3,T_LOW,false});
            coinArc(l,z-2.0f,z+2.5f,1.7f);
            break;
        }
        if(rndi(9)==0) addCoin(LANEX[rndi(3)],1.05f,z+3.0f,1);  /* shield pickup */
        nextZ += 17.0f+speed*0.42f+rndf()*6.0f;
    }
    /* drop stuff behind the camera */
    for(size_t i=0;i<obs.size();){
        if(obs[i].z<pz-14.0f){ obs[i]=obs.back(); obs.pop_back(); } else i++;
    }
    for(size_t i=0;i<coinList.size();){
        if(coinList[i].p.z<pz-14.0f){ coinList[i]=coinList.back(); coinList.pop_back(); } else i++;
    }
    for(size_t i=0;i<gaps.size();){
        if(gaps[i].b<pz-14.0f){ gaps[i]=gaps.back(); gaps.pop_back(); } else i++;
    }
    std::sort(gaps.begin(),gaps.end(),[](const Gap&a,const Gap&b){return a.a<b.a;});
}
static inline float playerHeight(){ return slideT>0.0f?0.76f:1.75f; }

static void damage(){
    if(invuln>0.0f) return;
    if(shields>0){ shields--; invuln=1.1f; shake=0.35f; flashAmt=0.45f;
        spawnBurst(px,py+0.9f,pz,PK(110,240,255),22,1.2f);
        setMsg("»¤¶ÜÆÆËé",0.9f); return; }
    hpNow--; invuln=1.75f; shake=0.85f; flashAmt=1.0f; combo=0; comboT=0;
    speedPenalty=0.45f;
    spawnBurst(px,py+0.9f,pz,PK(255,86,86),30,1.4f);
    setMsg("ײ»÷£¡",0.9f);
    if(hpNow<=0){
        hpNow=0; state=OVER;
        newBest=(score>best);
        if(newBest) best=score;
        shake=1.2f;
    }
}
static void collect(Coin& c){
    c.got=true;
    if(c.type==0){
        coinCount++; combo++; comboT=2.2f;
        score+=40+combo*6;
        spawnBurst(c.p.x,c.p.y,c.p.z,PK(255,210,90),12,0.75f);
        if(combo>=3 && (combo%3)==0) setMsg("Á¬»÷ÌáÉý£¡",0.8f);
    }else{
        shields=imin(shields+1,2);
        spawnBurst(c.p.x,c.p.y,c.p.z,PK(110,240,255),20,1.0f);
        setMsg("»¤¶Ü +1",1.0f);
    }
}
static void checkCollisions(bool harmful){
    float h=playerHeight();
    if(harmful && invuln<=0.0f){
        for(size_t i=0;i<obs.size();i++){
            const Obstacle& o=obs[i];
            if(fabsf(o.z-pz)>0.85f) continue;
            if(fabsf(LANEX[o.lane]-px)>1.34f) continue;
            bool hit=false;
            if(o.type==T_LOW)       hit=(py<0.88f);
            else if(o.type==T_HIGH) hit=(py+h>1.12f);
            else                    hit=true;
            if(hit){ damage(); break; }
        }
        if(invuln<=0.0f){
            for(size_t i=0;i<gaps.size();i++){
                if(pz>gaps[i].a+0.15f && pz<gaps[i].b-0.15f && py<0.22f){
                    pz=gaps[i].b+0.5f;
                    damage(); break;
                }
            }
        }
    }
    for(size_t i=0;i<coinList.size();i++){
        Coin& c=coinList[i];
        if(c.got) continue;
        if(fabsf(c.p.z-pz)<0.95f && fabsf(c.p.x-px)<1.05f &&
           fabsf(c.p.y-(py+0.92f))<1.15f) collect(c);
    }
    for(size_t i=0;i<obs.size();i++){
        Obstacle& o=obs[i];
        if(!o.passed && o.z<pz-1.1f){
            o.passed=true;
            if(harmful){ combo++; comboT=2.2f; score+=25+combo*4; }
        }
    }
}

static void jump(){
    if(onGround){ vy=9.85f; onGround=false; jumps=1;
        spawnBurst(px,py+0.15f,pz,PK(120,220,255),8,0.55f); }
    else if(jumps<2){ vy=8.75f; jumps=2;
        spawnBurst(px,py+0.6f,pz,PK(180,130,255),14,0.85f); }
}
static void slide(){
    slideT=0.62f;
    if(!onGround) vy=-21.0f;
    spawnBurst(px,py+0.12f,pz,PK(255,160,90),8,0.55f);
}
static void emitTrail(float dt){
    trailAcc+=dt*(onGround?26.0f:14.0f);
    while(trailAcc>=1.0f){
        trailAcc-=1.0f;
        if(parts.size()>430) break;
        Part p;
        float k=rndf();
        p.p=V(px+(rndf()-0.5f)*0.55f,py+0.10f+rndf()*0.35f,pz-0.30f);
        p.v=V((rndf()-0.5f)*1.6f,0.5f+rndf()*1.6f,-3.0f-rndf()*4.0f);
        p.max=p.life=0.25f+rndf()*0.38f;
        p.size=0.04f+rndf()*0.06f;
        p.col = k<0.5f?PK(90,220,255):(k<0.82f?PK(255,90,180):PK(255,200,100));
        parts.push_back(p);
    }
}
static void updateParts(float dt){
    for(size_t i=0;i<parts.size();){
        Part& p=parts[i];
        p.life-=dt;
        if(p.life<=0.0f){ p=parts.back(); parts.pop_back(); continue; }
        p.p.x+=p.v.x*dt; p.p.y+=p.v.y*dt; p.p.z+=p.v.z*dt;
        p.v.y-=7.0f*dt;
        i++;
    }
}

static void update(float dt){
    if(state==PAUSE) return;
    if(state==OVER){
        /* Freeze the run: the game-over panel must show the FINAL numbers.
           Only cosmetic effects keep settling; pz, score and pickups stop. */
        invuln=fmaxf(0.0f,invuln-dt);
        shake=fmaxf(0.0f,shake-dt*1.7f);
        flashAmt=fmaxf(0.0f,flashAmt-dt*2.1f);
        msgT=fmaxf(0.0f,msgT-dt);
        updateParts(dt);
        return;
    }
    float sp=fmaxf(4.0f,speed*(1.0f-speedPenalty));
    speedPenalty=fmaxf(0.0f,speedPenalty-dt*0.55f);
    pz+=sp*dt;
    distM=(int)(pz*0.42f);
    if(state==PLAY){
        speed=fminf(13.0f+pz*0.0115f,30.0f);
        score+=(int)(sp*dt*3.0f);
    }else speed=10.0f;
    runPhase+=dt*(7.0f+sp*0.36f);
    vy-=27.0f*dt;
    py+=vy*dt;
    if(py<=0.0f){
        if(!onGround && vy<-4.0f) spawnBurst(px,0.12f,pz,PK(150,170,220),12,0.7f);
        py=0.0f; vy=0.0f; onGround=true; jumps=0;
    }
    px+=(LANEX[lane]-px)*(1.0f-expf(-13.0f*dt));
    slideT=fmaxf(0.0f,slideT-dt);
    invuln=fmaxf(0.0f,invuln-dt);
    shake=fmaxf(0.0f,shake-dt*1.7f);
    flashAmt=fmaxf(0.0f,flashAmt-dt*2.1f);
    comboT=fmaxf(0.0f,comboT-dt);
    if(comboT<=0.0f) combo=0;
    msgT=fmaxf(0.0f,msgT-dt);

    if(state==MENU){
        menuTimer-=dt;
        if(menuTimer<=0.0f){
            menuTimer=1.5f+rndf()*1.7f;
            lane=rndi(3);
            if(rndi(3)==0 && onGround){ vy=9.2f; onGround=false; }
        }
    }
    checkCollisions(state==PLAY);
    spawnWorld();
    updateParts(dt);
    emitTrail(dt);

    /* camera follow */
    camX+=(px*0.32f-camX)*(1.0f-expf(-7.0f*dt));
    float bob=onGround?sinf(runPhase*2.0f)*0.035f:0.0f;
    float shx=0.0f,shy=0.0f,shp=0.0f;
    if(shake>0.0f){ shx=(rndf()-0.5f)*shake*0.5f; shy=(rndf()-0.5f)*shake*0.4f; shp=(rndf()-0.5f)*shake*0.045f; }
    camY=2.85f+py*0.30f+bob+shy;
    camZ=pz-6.6f+shx*0.2f;
    pitch=-0.125f+py*0.006f+shp;
    ca=cosf(pitch); sa=sinf(pitch);
    horizon=H*0.5f+tanf(pitch)*focal;
}

/* ------------------------------------------------------------------ */
/* world geometry                                                      */
/* ------------------------------------------------------------------ */
static void floorTile(float za,float zb,int ti){
    float len=zb-za, mz=(za+zb)*0.5f;
    if(len<0.05f) return;
    u32 base=(ti&1)?PK(64,72,116):PK(78,88,138);
    quad3(V(-HALF,0,za),V(HALF,0,za),V(HALF,0,zb),V(-HALF,0,zb),base);
    /* platform thickness */
    quad3(V(-HALF,0,za),V(-HALF,-2.4f,za),V(-HALF,-2.4f,zb),V(-HALF,0,zb),PK(24,27,54));
    quad3(V(HALF,0,za),V(HALF,0,zb),V(HALF,-2.4f,zb),V(HALF,-2.4f,za),PK(24,27,54));
    /* seam */
    quad3(V(-HALF,0.012f,za),V(HALF,0.012f,za),
          V(HALF,0.012f,za+0.07f),V(-HALF,0.012f,za+0.07f),PK(28,32,62));
    /* dashed lane dividers */
    if((ti&1)==0){
        floorStrip(-1.6f,mz-0.78f,-1.6f,mz+0.78f,0.055f,PK(178,198,244),false);
        floorStrip( 1.6f,mz-0.78f, 1.6f,mz+0.78f,0.055f,PK(178,198,244),false);
    }
    /* glowing edge lines */
    floorStrip(-HALF+0.34f,za,-HALF+0.34f,zb,0.065f,PK(90,240,255),true);
    floorStrip( HALF-0.34f,za, HALF-0.34f,zb,0.065f,PK(255,96,196),true);
    /* chevrons */
    if((ti%4)==0){
        floorStrip(-0.75f,mz-0.55f,0.0f,mz+0.42f,0.10f,PK(150,215,255),true);
        floorStrip( 0.75f,mz-0.55f,0.0f,mz+0.42f,0.10f,PK(150,215,255),true);
    }
    /* side rails + neon caps */
    box(V(-HALF-0.17f,0.23f,mz),V(0.34f,0.46f,len*0.99f),PK(36,42,78));
    box(V( HALF+0.17f,0.23f,mz),V(0.34f,0.46f,len*0.99f),PK(36,42,78));
    box(V(-HALF-0.17f,0.475f,mz),V(0.14f,0.055f,len*0.99f),PK(80,235,255),1.0f,true);
    box(V( HALF+0.17f,0.475f,mz),V(0.14f,0.055f,len*0.99f),PK(255,80,190),1.0f,true);
    if((ti%3)==0){
        box(V(-HALF-0.17f,0.70f,mz),V(0.12f,0.42f,0.12f),PK(160,240,255),1.0f,true);
        box(V( HALF+0.17f,0.70f,mz),V(0.12f,0.42f,0.12f),PK(255,150,215),1.0f,true);
    }
}

static void drawTrack(){
    float z0=floorf((camZ+2.5f)/TILE)*TILE;
    if(z0<camZ+0.8f) z0+=TILE;
    float zEnd=camZ+DRAW;
    for(float z=z0;z<zEnd;z+=TILE){
        int ti=(int)floorf(z/TILE+0.5f);
        float end=z+TILE, cur=z;
        for(size_t gi=0;gi<gaps.size();gi++){
            const Gap& g=gaps[gi];
            if(g.b<=z||g.a>=end) continue;
            if(g.a>cur+0.02f) floorTile(cur,fminf(g.a,end),ti);
            cur=fmaxf(cur,fminf(g.b,end));
            if(cur>=end-0.02f) break;
        }
        if(cur<end-0.02f) floorTile(cur,end,ti);
    }
    /* pit rims */
    for(size_t i=0;i<gaps.size();i++){
        float a=gaps[i].a,b=gaps[i].b;
        if(b<camZ+1.0f||a>camZ+DRAW) continue;
        quad3(V(-HALF,0.06f,a-0.18f),V(HALF,0.06f,a-0.18f),
              V(HALF,0.06f,a+0.10f),V(-HALF,0.06f,a+0.10f),PK(255,132,70),1,true);
        quad3(V(-HALF,0.06f,b-0.10f),V(HALF,0.06f,b-0.10f),
              V(HALF,0.06f,b+0.18f),V(-HALF,0.06f,b+0.18f),PK(255,132,70),1,true);
        quad3(V(-HALF,0,a),V(HALF,0,a),V(HALF,-2.4f,a),V(-HALF,-2.4f,a),PK(52,20,46));
        quad3(V(-HALF,0,b),V(HALF,0,b),V(HALF,-2.4f,b),V(-HALF,-2.4f,b),PK(52,20,46));
    }
}

static void drawCity3D(){
    float z0=floorf((camZ+20.0f)/18.0f)*18.0f;
    for(float z=z0;z<camZ+DRAW+14.0f;z+=18.0f){
        for(int side=-1;side<=1;side+=2){
            float h1=hash01((int)z*3+side*977);
            float h2=hash01((int)z*7+side*421+9);
            float x=side*(12.0f+h1*6.0f);
            float hh=8.0f+h2*15.0f;
            box(V(x,hh*0.5f-3.0f,z),V(6.4f,hh,9.0f),PK(34,38,72));
            float ix=x-side*3.25f;
            u32 neon=(hash01((int)z+side*55)>0.5f)?PK(100,225,255):PK(255,96,186);
            box(V(ix,hh*0.22f-3.0f,z+2.4f),V(0.10f,hh*0.40f,0.16f),neon,1.0f,true);
            box(V(ix,hh*0.22f-3.0f,z-2.4f),V(0.10f,hh*0.28f,0.16f),
                scaleCol(neon,0.72f),1.0f,true);
            box(V(ix,hh*0.22f-3.0f,z+0.0f),V(0.10f,hh*0.34f,0.16f),
                scaleCol(neon,0.45f),1.0f,true);
            box(V(x,hh-3.0f,z),V(6.6f,0.16f,9.2f),scaleCol(neon,0.72f),1.0f,true);
        }
    }
}

static void drawObstacles(){
    for(size_t i=0;i<obs.size();i++){
        const Obstacle& o=obs[i];
        if(o.z<camZ-2.0f||o.z>camZ+DRAW) continue;
        float x=LANEX[o.lane];
        /* warning chevrons on the floor before it */
        for(int k=0;k<2;k++){
            float wz=o.z-3.4f-(float)k*1.1f;
            floorStrip(x-0.95f,wz-0.42f,x,wz+0.40f,0.085f,PK(255,110,80),true);
            floorStrip(x+0.95f,wz-0.42f,x,wz+0.40f,0.085f,PK(255,110,80),true);
        }
        if(o.type==T_LOW){
            box(V(x,0.44f,o.z),V(2.72f,0.88f,0.78f),PK(196,52,72));
            box(V(x,0.91f,o.z),V(2.82f,0.10f,0.88f),PK(255,158,72),1,true);
            box(V(x,0.28f,o.z-0.40f),V(2.50f,0.07f,0.05f),PK(255,220,120),1,true);
            for(int s=-1;s<=1;s+=2)
                box(V(x+s*1.30f,0.45f,o.z),V(0.11f,0.90f,0.82f),PK(255,196,96),1,true);
        }else if(o.type==T_HIGH){
            box(V(x,1.88f,o.z),V(2.90f,1.46f,0.80f),PK(38,142,182));
            box(V(x,1.14f,o.z),V(3.00f,0.10f,0.90f),PK(110,244,255),1,true);
            box(V(x,2.60f,o.z),V(3.00f,0.09f,0.90f),PK(110,244,255),1,true);
            for(int s=-1;s<=1;s+=2)
                box(V(x+s*1.40f,1.30f,o.z),V(0.14f,2.60f,0.86f),PK(46,90,130));
            for(int s=-1;s<=1;s+=2)
                box(V(x+s*0.55f,1.09f,o.z-0.47f),V(0.40f,0.08f,0.05f),PK(180,250,255),1,true);
        }else{
            box(V(x,1.55f,o.z),V(2.82f,3.10f,0.82f),PK(112,44,158));
            float fz=o.z-0.43f;
            box(V(x,3.05f,fz),V(2.90f,0.11f,0.07f),PK(230,110,255),1,true);
            box(V(x,0.08f,fz),V(2.90f,0.11f,0.07f),PK(230,110,255),1,true);
            for(int s=-1;s<=1;s+=2)
                box(V(x+s*1.40f,1.55f,fz),V(0.11f,3.10f,0.07f),PK(230,110,255),1,true);
            for(int k=0;k<4;k++)
                box(V(x,0.55f+(float)k*0.68f,fz-0.02f),V(2.50f,0.065f,0.05f),
                    PK(255,150,240),1,true);
        }
    }
}

/* additive, depth-tested soft disc ---------------------------------- */
static void glowDisc(float cx,float cy,float rx,float ry,u32 inner,u32 outer,float alpha,float iw){
    rx=fmaxf(rx,0.6f); ry=fmaxf(ry,0.6f);
    int x0=imax(0,(int)(cx-rx-1)), x1=imin(W-1,(int)(cx+rx+1));
    int y0=imax(0,(int)(cy-ry-1)), y1=imin(H-1,(int)(cy+ry+1));
    if(x0>x1||y0>y1) return;
    for(int y=y0;y<=y1;y++)for(int x=x0;x<=x1;x++){
        float dx=((float)x+0.5f-cx)/rx, dy=((float)y+0.5f-cy)/ry;
        float d2=dx*dx+dy*dy;
        if(d2>=1.0f) continue;
        size_t i=(size_t)y*W+x;
        if(iw<=zb[i]) continue;
        float f=(1.0f-d2); f*=f;
        u32 col=mixCol(inner,outer,d2);
        u32 d=pix[i];
        pix[i]=PK((int)(cR(d)+cR(col)*f*alpha),
                  (int)(cG(d)+cG(col)*f*alpha),
                  (int)(cB(d)+cB(col)*f*alpha));
    }
}
static void drawCoins(){
    for(size_t i=0;i<coinList.size();i++){
        Coin& c=coinList[i];
        if(c.got||c.p.z<camZ-1.0f||c.p.z>camZ+DRAW) continue;
        V2 v; if(!project(c.p,v)) continue;
        float r=clampf(0.38f*focal*v.w,1.0f,24.0f);
        float squash=0.32f+0.68f*fabsf(cosf(gTime*3.1f+c.p.z*0.8f));
        u32 core=c.type==0?PK(255,232,128):PK(150,250,255);
        u32 edge=c.type==0?PK(255,126,36) :PK(40,150,255);
        glowDisc(v.x,v.y,r*2.5f,r*2.5f,core,edge,0.11f,v.w);
        glowDisc(v.x,v.y,r*squash,r,core,edge,0.95f,v.w);
    }
}
static void drawParts(){
    for(size_t i=0;i<parts.size();i++){
        Part& p=parts[i];
        V2 v; if(!project(p.p,v)) continue;
        float r=clampf(p.size*focal*v.w,0.7f,13.0f);
        float a=clampf(p.life/p.max,0.0f,1.0f);
        glowDisc(v.x,v.y,r*2.1f,r*2.1f,p.col,p.col,0.09f*a,v.w);
        glowDisc(v.x,v.y,r,r,p.col,scaleCol(p.col,0.25f),a,v.w);
    }
}

/* 3D humanoid from boxes, running / jumping / sliding ---------------- */
static void limb(float x,float pivotY,float z,float w,float len,u32 col,float rot,u32 tipCol){
    Vec3 piv(x,pivotY,z);
    box(V(x,pivotY-len*0.5f,z),V(w,len,w),col,1.0f,false,rot,piv);
    float cr=cosf(rot),sr=sinf(rot);
    float ex=x, ey=pivotY-len*cr, ez=z-len*sr;
    box(V(ex,ey,ez),V(w*1.12f,w*0.62f,w*1.12f),tipCol,1.0f,true);
}
static void drawPlayer(){
    if(invuln>0.0f && fmodf(gTime*15.0f,1.0f)<0.32f) return;
    float s=clampf(slideT/0.62f,0.0f,1.0f);
    float sw=sinf(runPhase)*0.72f*(1.0f-s);
    float air=clampf(py/1.6f,0.0f,1.0f);
    float lean=clampf((LANEX[lane]-px)*0.10f,-0.38f,0.38f);
    /* ground shadow */
    float sr=lerpf(0.92f,0.48f,clampf(py/3.0f,0,1));
    quad3(V(px-sr,0.035f,pz-sr*0.70f),V(px+sr,0.035f,pz-sr*0.70f),
          V(px+sr,0.035f,pz+sr*0.70f),V(px-sr,0.035f,pz+sr*0.70f),PK(19,21,40));

    float bodyY=py+lerpf(1.14f,0.53f,s);
    float headY=py+lerpf(1.74f,0.94f,s);
    float torsoH=lerpf(0.82f,0.36f,s);
    float cx=px+lean*0.30f;
    u32 jacket=PK(42,60,112), dark=PK(25,33,64), skin=PK(238,190,152);
    u32 trim=PK(80,240,255), warm=PK(255,132,80);

    box(V(cx,bodyY,pz),V(0.72f,torsoH,0.44f),jacket);
    box(V(cx,bodyY+0.04f,pz-0.245f),V(0.44f,torsoH*0.64f,0.055f),PK(18,24,52));
    box(V(cx,bodyY+0.04f,pz-0.278f),V(0.09f,torsoH*0.52f,0.035f),trim,1,true);
    box(V(px,bodyY-torsoH*0.44f,pz),V(0.76f,0.10f,0.47f),warm,1,true);
    /* head + helmet */
    float hx=px+lean*0.55f;
    box(V(hx,headY,pz),V(0.42f,0.40f,0.40f),skin);
    box(V(hx,headY+0.18f,pz+0.01f),V(0.47f,0.18f,0.45f),PK(28,36,76));
    box(V(hx,headY+0.02f,pz-0.218f),V(0.30f,0.07f,0.035f),trim,1,true);
    /* arms */
    for(int i=-1;i<=1;i+=2){
        float ax=px+i*0.47f+lean*0.30f;
        float rot=(i<0?-sw:sw)-air*0.55f-s*0.9f;
        limb(ax,bodyY+torsoH*0.32f,pz,0.20f,0.60f,jacket,rot,trim);
    }
    /* legs */
    for(int i=-1;i<=1;i+=2){
        float lx=px+i*0.19f;
        float pivY=py+lerpf(0.86f,0.40f,s);
        float len=lerpf(0.80f,0.44f,s);
        float rot=(i<0?sw:-sw)-air*0.62f;
        limb(lx,pivY,pz,0.26f,len,dark,rot,warm);
    }
}

/* ------------------------------------------------------------------ */
/* post processing                                                     */
/* ------------------------------------------------------------------ */
static void speedLines(){
    if(speed<18.0f||state==PAUSE) return;
    float a=clampf((speed-18.0f)/12.0f,0.0f,1.0f)*0.30f;
    float cx=W*0.5f,cy=H*0.56f;
    for(int i=0;i<14;i++){
        float ang=hash01(i*31+(int)(gTime*7.0f))*PI*2.0f;
        float r0=W*(0.30f+0.18f*hash01(i*57));
        float r1=r0+W*(0.05f+0.12f*hash01(i*89));
        int steps=(int)(r1-r0);
        for(int k=0;k<steps;k++){
            float r=r0+k;
            int x=(int)(cx+cosf(ang)*r), y=(int)(cy+sinf(ang)*r*0.62f);
            if(x<0||x>=W||y<0||y>=H) continue;
            size_t idx=(size_t)y*W+x;
            pix[idx]=addCol(pix[idx],scaleCol(PK(150,210,255),a*(1.0f-(float)k/steps)));
        }
    }
}
static void post(){
    int bw=W/2,bh=H/2;
    if(bw<2||bh<2) return;
    static std::vector<u32> br,tmp,bl;
    br.assign((size_t)bw*bh,0);
    tmp.assign((size_t)bw*bh,0);
    bl.assign((size_t)bw*bh,0);
    for(int y=0;y<bh;y++)for(int x=0;x<bw;x++){
        int r=0,g=0,b=0;
        for(int dy=0;dy<2;dy++)for(int dx=0;dx<2;dx++){
            u32 c=pix[(size_t)(y*2+dy)*W+x*2+dx];
            int lum=(cR(c)*77+cG(c)*150+cB(c)*29)>>8;
            if(lum>150){ r+=cR(c); g+=cG(c); b+=cB(c); }
        }
        br[(size_t)y*bw+x]=PKF(r>>2,g>>2,b>>2);
    }
    static const int KW[5]={1,2,3,2,1};
    for(int y=0;y<bh;y++)for(int x=0;x<bw;x++){
        int r=0,g=0,b=0,ws=0;
        for(int k=-2;k<=2;k++){
            int xx=imax(0,imin(bw-1,x+k)); u32 c=br[(size_t)y*bw+xx]; int w=KW[k+2];
            r+=cR(c)*w; g+=cG(c)*w; b+=cB(c)*w; ws+=w;
        }
        tmp[(size_t)y*bw+x]=PKF(r/ws,g/ws,b/ws);
    }
    for(int y=0;y<bh;y++)for(int x=0;x<bw;x++){
        int r=0,g=0,b=0,ws=0;
        for(int k=-2;k<=2;k++){
            int yy=imax(0,imin(bh-1,y+k)); u32 c=tmp[(size_t)yy*bw+x]; int w=KW[k+2];
            r+=cR(c)*w; g+=cG(c)*w; b+=cB(c)*w; ws+=w;
        }
        bl[(size_t)y*bw+x]=PKF(r/ws,g/ws,b/ws);
    }
    for(int y=0;y<H;y++){
        float fy=((float)y-0.5f)*0.5f;
        int iy=(int)floorf(fy); float ty=fy-iy;
        int ya=imax(0,imin(bh-1,iy)), yb=imax(0,imin(bh-1,iy+1));
        for(int x=0;x<W;x++){
            float fx=((float)x-0.5f)*0.5f;
            int ix=(int)floorf(fx); float tx=fx-ix;
            int xa=imax(0,imin(bw-1,ix)), xb=imax(0,imin(bw-1,ix+1));
            u32 c00=bl[(size_t)ya*bw+xa], c10=bl[(size_t)ya*bw+xb];
            u32 c01=bl[(size_t)yb*bw+xa], c11=bl[(size_t)yb*bw+xb];
            float brr=(float)(cR(c00)*(1-tx)+cR(c10)*tx)*(1-ty)+(float)(cR(c01)*(1-tx)+cR(c11)*tx)*ty;
            float bgg=(float)(cG(c00)*(1-tx)+cG(c10)*tx)*(1-ty)+(float)(cG(c01)*(1-tx)+cG(c11)*tx)*ty;
            float bbb=(float)(cB(c00)*(1-tx)+cB(c10)*tx)*(1-ty)+(float)(cB(c01)*(1-tx)+cB(c11)*tx)*ty;
            size_t i=(size_t)y*W+x;
            u32 d=pix[i];
            int v=vig[i];
            int r=(cR(d)+(int)(brr*0.78f))*v/64;
            int g=(cG(d)+(int)(bgg*0.78f))*v/64;
            int b=(cB(d)+(int)(bbb*0.78f))*v/64;
            if(y&1){ r=r*61/64; g=g*61/64; b=b*61/64; }
            pix[i]=PK(r,g,b);
        }
    }
    if(flashAmt>0.0f){
        float a=flashAmt*0.55f;
        for(size_t i=0;i<pix.size();i++) pix[i]=mixCol(pix[i],PK(255,40,56),a);
    }
}

/* ------------------------------------------------------------------ */
/* HUD overlay (crisp terminal text on top of the pixel framebuffer)    */
/* ------------------------------------------------------------------ */
static std::string overlay;
static void ovMove(int r,int c){ char b[32]; snprintf(b,sizeof(b),"\x1b[%d;%dH",r,c); overlay+=b; }
static void ovText(int r,int c,const char* txt,u32 fg,u32 bg,bool bold=false){
    if(r<1||r>term.rows||c<1||c>term.cols) return;
    ovMove(r,c);
    if(bold) overlay+="\x1b[1m";
    sgrFG(overlay,codeOf(fg)); sgrBG(overlay,codeOf(bg));
    overlay+=txt; overlay+="\x1b[0m";
}
static void ovPanel(int r,int c,int w,int h,u32 bg){
    w=imin(w,term.cols-c+1);
    if(w<1) return;
    u32 code=codeOf(bg);
    std::string line((size_t)w,' ');
    for(int i=0;i<h;i++){
        int rr=r+i; if(rr<1||rr>term.rows) continue;
        ovMove(rr,c);
        sgrBG(overlay,code); sgrFG(overlay,code);
        overlay+=line; overlay+="\x1b[0m";
    }
}
/* One SGR per WHOLE UTF-8 codepoint - inserting SGR inside a multi-byte
   sequence would corrupt the Chinese text. */
static void ovGrad(int r,int c,const char* txt,u32 a,u32 b,u32 bg){
    if(r<1||r>term.rows||c<1||c>term.cols) return;
    ovMove(r,c);
    sgrBG(overlay,codeOf(bg));
    int total=dispWidth(txt), used=0;
    for(const unsigned char* p=(const unsigned char*)txt;*p;){
        int n=u8Step(p);
        sgrFG(overlay,codeOf(mixCol(a,b,(float)used/fmaxf(1.0f,(float)(total-1)))));
        overlay.append((const char*)p,(size_t)n);
        used+=u8Width(p,n);
        p+=n;
    }
    overlay+="\x1b[0m";
}
static void centerText(int r,const char* txt,u32 fg,u32 bg,bool bold=false){
    int c=imax(2,(term.cols-dispWidth(txt))/2);
    ovText(r,c,txt,fg,bg,bold);
}
static void centerGrad(int r,const char* txt,u32 a,u32 b,u32 bg){
    int c=imax(2,(term.cols-dispWidth(txt))/2);
    ovGrad(r,c,txt,a,b,bg);
}
static const u32 PANEL=PK(9,10,26);

static void buildMenu(){
    int C=term.cols,R=term.rows;
    int w=imin(C-2,60), h=13;
    int r0=imax(2,(R-h)/2), c0=imax(2,(C-w)/2);
    ovPanel(r0,c0,w,h,PANEL);
    centerGrad(r0+1,"ÄÞ ºç ÅÜ ¿á   3 D",PK(90,235,255),PK(255,92,180),PANEL);
    centerText(r0+2,"´¿Èí¼þ¹âÕ¤»¯  /  ÎÞͼÐοâ",PK(150,162,212),PANEL);
    const char* L1="A / D  »ò  ¡û ¡ú        Çл»ÅܵÀ";
    const char* L2="¿Õ¸ñ / W / ¡ü          ÌøÔ¾ + ¶þ¶ÎÌø";
    const char* L3="S / ¡ý                 »¬²ù / ¿ÕÖÐÏÂÔÒ";
    const char* L4="P / ESC ÔÝÍ£    V ·Ö±æÂÊÓëËõ·Å    Q Í˳ö";
    ovText(r0+4,c0+4,L1,PK(214,224,250),PANEL);
    ovText(r0+5,c0+4,L2,PK(214,224,250),PANEL);
    ovText(r0+6,c0+4,L3,PK(214,224,250),PANEL);
    ovText(r0+7,c0+4,L4,PK(214,224,250),PANEL);
    centerText(r0+9,"¿çÔ½°«À¸ - »¬¹ýºá¸Ë - ¶ã±Ü¸ßǽ - Ô¾¹ý¶ÏÇÅ",
               PK(140,220,235),PANEL);
    centerGrad(r0+11,">>>   °´ ¿Õ¸ñ ¿ªÊ¼   <<<",PK(255,232,120),PK(255,110,90),PANEL);
}
static void buildPause(){
    int C=term.cols,R=term.rows;
    int w=imin(C-2,46),h=5;
    int r0=imax(2,(R-h)/2),c0=imax(2,(C-w)/2);
    ovPanel(r0,c0,w,h,PANEL);
    centerGrad(r0+1,"ÓÎ Ï· ÔÝ Í£",PK(110,235,255),PK(255,110,180),PANEL);
    centerText(r0+3,"P / ESC ¼ÌÐø   V ·Ö±æÂÊÓëËõ·Å   Q Í˳ö",PK(210,220,245),PANEL);
}
static void buildOver(){
    int C=term.cols,R=term.rows;
    int w=imin(C-2,52),h=9;
    int r0=imax(2,(R-h)/2),c0=imax(2,(C-w)/2);
    ovPanel(r0,c0,w,h,PANEL);
    centerGrad(r0+1,"ÓÎ Ï· ½á Êø",PK(255,90,110),PK(255,190,90),PANEL);
    char b[96];
    snprintf(b,sizeof(b),"·ÖÊý %06d    ¾àÀë %5dm    ½ð±Ò %3d",score,distM,coinCount);
    centerText(r0+3,b,PK(230,236,255),PANEL,true);
    snprintf(b,sizeof(b),"×î¸ß·Ö %06d",best);
    centerText(r0+4,b,PK(255,220,130),PANEL);
    if(newBest && score>0) centerText(r0+5,"* мͼ *",PK(140,255,190),PANEL);
    centerGrad(r0+7,"V ·Ö±æÂÊÓëËõ·Å    R / ¿Õ¸ñ ÔÙÀ´Ò»¾Ö",PK(120,235,255),PK(255,120,190),PANEL);
}
static void buildHUD(){
    overlay.clear();
    int C=term.cols,R=term.rows;
    ovPanel(1,1,C,2,PANEL);
    ovText(1,2," ÄÞºçÅÜ¿á 3D ",PK(110,240,255),PANEL,true);
    char b[128];
    snprintf(b,sizeof(b)," ·ÖÊý:%06d  ¾àÀë:%5dm  ½ð±Ò:%3d  ×î¸ß:%06d",score,distM,coinCount,best);
    ovText(2,2,b,PK(226,232,255),PANEL);
    std::string hp=" ÉúÃü ";
    for(int i=0;i<3;i++) hp += (i<hpNow?"¡ñ":"¡ð");
    char sh[32]; snprintf(sh,sizeof(sh),"  »¤¶Ü:%d ",shields);
    hp+=sh;
    ovText(1,imax(30,C-dispWidth(hp.c_str())-2),hp.c_str(),PK(255,96,116),PANEL,true);
    if(C>=96){
        int bars=imax(0,imin(10,(int)((speed-13.0f)/17.0f*10.0f)));
        std::string s=" ËÙ¶È [";
        for(int i=0;i<10;i++) s+=(i<bars?'|':'.');
        s+="]";
        ovText(2,C-dispWidth(s.c_str())-2,s.c_str(),PK(150,255,190),PANEL);
    }
    if(combo>=3 && state==PLAY){
        char cb[48]; snprintf(cb,sizeof(cb)," Á¬»÷ x%d ",combo);
        int cc=imax(2,(C-dispWidth(cb))/2);
        ovGrad(4,cc,cb,PK(255,230,110),PK(255,100,160),PANEL);
    }
    if(msgT>0.0f && msgBuf[0]){
        int cc=imax(2,(C-dispWidth(msgBuf)-4)/2);
        std::string m="  "; m+=msgBuf; m+="  ";
        ovText(6,cc,m.c_str(),PK(255,220,120),PANEL,true);
    }
    ovPanel(R,1,C,1,PANEL);
    std::string foot=" A/D »»µÀ  ¿Õ¸ñ Ìø  S ²ù  P Í£  V ·Ö±æÂÊ";
    if(C>=110) foot+="  L ±àÂë  F ×ÖÌå";
    foot+="  R ÖØ¿ª  Q Í˳ö ";
    float tf=targetFPS();
    if(tf<50.0f){
        char tail[96];
        snprintf(tail,sizeof(tail),"  Íø¸ñ %d x %d ¡¤ %d Ö¡/Ãë ",C,R,(int)tf);
        foot+=tail;
    }
    centerText(R,foot.c_str(),PK(160,178,215),PANEL);
    if(state==MENU)       buildMenu();
    else if(state==PAUSE) buildPause();
    else if(state==OVER)  buildOver();
}

/* framebuffer -> delta encoded ANSI half-blocks ---------------------- */
static std::string encode(){
    std::string s;
    s.reserve((size_t)W*(H/2)*24+8192);
    s+="\x1b[0m\x1b[H";
    /* °ë¿é×Ö·ûÏÈд³É ASCII ռλ·û£»write() Êä³öǰÔÙ°´Ä¿±ê±àÂëÕ¹¿ª£¬
       ±ÜÃâÖ¡Àï»ìÈë UTF-8 ×Ö½Ú¡¢°Ñ GBK ÖÐÎÄÃæÁ¿ÎóÅгɷǷ¨ÐòÁС£ */
    u32 cfg=0xffffffffu,cbg=0xffffffffu;
    for(int row=0;row<H/2;row++){
        const u32* top=&pix[(size_t)(row*2)*W];
        const u32* bot=&pix[(size_t)(row*2+1)*W];
        for(int x=0;x<W;x++){
            u32 a=codeOf(top[x]), b=codeOf(bot[x]);
            u32 fg=a, bg=b;
            if(gEnc){ fg=b; bg=a; }        /* ¨{ µÄǰ¾°»­Ï°룬Ðè¶Ôµ÷ÑÕÉ« */
            if(fg!=cfg){ sgrFG(s,fg); cfg=fg; }
            if(bg!=cbg){ sgrBG(s,bg); cbg=bg; }
            s+=HALF_MARK;
        }
        if(row<H/2-1) s+="\r\n";
    }
    s+=overlay;
    s+="\x1b[0m";
    return s;
}

/* ------------------------------------------------------------------ */
/* startup resolution picker                                          */
/* ------------------------------------------------------------------ */
static bool fixedRes=false;   /* user pinned a grid -> stop following the window */

static bool ttyInteractive(){
#ifdef _WIN32
    return _isatty(_fileno(stdin))!=0 && _isatty(_fileno(stdout))!=0;
#else
    return isatty(STDIN_FILENO)!=0 && isatty(STDOUT_FILENO)!=0;
#endif
}
struct ResOpt { const char* label; int c,r; const char* note; };

static void resLine(std::string& s,int row,int c0,int width,u32 fg,u32 bg,const char* text){
    char b[32]; snprintf(b,sizeof(b),"\x1b[%d;%dH",row,c0); s+=b;
    sgrFG(s,codeOf(fg)); sgrBG(s,codeOf(bg));
    int used=0;
    for(const unsigned char* p=(const unsigned char*)text;*p;){
        int n=u8Step(p), cw=u8Width(p,n);
        if(used+cw>width) break;              /* never split a CJK glyph */
        s.append((const char*)p,(size_t)n);
        used+=cw; p+=n;
    }
    for(int i=used;i<width;i++) s+=' ';
    s+="\x1b[0m";
}
static void resTitle(std::string& s,int row,int c0,int width,const char* text,u32 a,u32 b,u32 bg){
    char pos[32]; snprintf(pos,sizeof(pos),"\x1b[%d;%dH",row,c0); s+=pos;
    sgrBG(s,codeOf(bg));
    int total=dispWidth(text), pad=(width-total)/2; if(pad<0) pad=0;
    for(int i=0;i<pad;i++) s+=' ';
    int used=0;
    for(const unsigned char* p=(const unsigned char*)text;*p;){
        int n=u8Step(p), cw=u8Width(p,n);
        if(pad+used+cw>width) break;
        sgrFG(s,codeOf(mixCol(a,b,(float)used/fmaxf(1.0f,(float)(total-1)))));
        s.append((const char*)p,(size_t)n);
        used+=cw; p+=n;
    }
    for(int i=pad+used;i<width;i++) s+=' ';
    s+="\x1b[0m";
}

/* force=true is the in-game "V" key; false is the startup prompt. */
static void chooseResolution(bool force){
    if(!ttyInteractive()) return;             /* captured / scripted run */
    if(!force){
        if(getenv("NR_COLS")||getenv("NR_ROWS")){ fixedRes=true; return; }
        if(getenv("NR_NORES")) return;
        const char* ep=getenv("NR_PLAY"); if(ep && atoi(ep)) return;
    }
    detectWindow();                           /* real grid, may have been zoomed */
    int maxC=gWinC, maxR=gWinR;
    if(maxC<60||maxR<19) return;              /* not enough room for the panel */

    static const ResOpt O[]={
        {"×Ô¶¯",        0,   0,"ʵʱ¸úËæ´°¿Ú³ß´ç"},
        {"80 x 24",    80,  24,"½ô´Õ ¡¤ ×î¿ì"},
        {"100 x 30",  100,  30,"¾ùºâ"},
        {"120 x 40",  120,  40,"¾«Ï¸ ¡¤ ÍÆ¼ö"},
        {"140 x 45",  140,  45,"³¬¾«Ï¸"},
        {"160 x 50",  160,  50,"¼«¾«Ï¸ ¡¤ ÉÔÂý"},
        {"200 x 60",  200,  60,"¸ßÇå ¡¤ Ðè¸ü´ó´°¿Ú"},
        {"320 x 100", 320, 100,"³¬¸ßÇå ¡¤ ½ÏÂý"},
        {"600 x 150", 600, 150,"¾ÞÄ» ¡¤ Ã÷ÏÔ±äÂý"},
        {"1200 x 300",1200, 300,"¼«ÏÞ ¡¤ ʵÑéÐÔ£¬¼«Âý"},
        {"×Ô¶¨Òå",     -1,  -1,"·½Ïò¼ü±à¼­Íø¸ñ"},
    };
    const int N=(int)(sizeof(O)/sizeof(O[0]));
    const int VIS=7;                 /* rows visible in the scrollable list */
    int top=0;                       /* first visible option               */
    int cc=imax(42,imin(maxC,120)), rr=imax(18,imin(maxR,40));
    int sel=0; bool editing=false; const char* warn=nullptr;
    gZoomMsg.clear();
    /* A full 22-row panel gets its own ZOOM section; narrow windows keep the
       original 19-row layout with a one-line zoom shortcut strip. */
    const bool full=(maxR>=22);
    const int  PH  =full?22:19;

    const u32 BG=PK(9,10,26), DIM=PK(126,136,172), TXT=PK(226,232,255),
              HOT=PK(255,232,120), LOCK=PK(92,98,130), SELBG=PK(38,30,68),
              WARN=PK(255,120,130);

    auto keepVisible=[&](){
        if(sel<top) top=sel;
        if(sel>=top+VIS) top=sel-VIS+1;
        int lim=imax(0,N-VIS);
        if(top>lim) top=lim;
    };

    auto draw=[&](){
        std::string s="\x1b[2J\x1b[H";
        int width=imin(72,maxC-2);
        int c0=imax(1,(maxC-width)/2+1);
        int r0=imax(1,(maxR-PH)/2+1);
        for(int i=0;i<PH;i++) resLine(s,r0+i,c0,width,BG,BG,"");
        resTitle(s,r0,  c0,width,"ÄÞ ºç ÅÜ ¿á  3 D   ¡¤   ·Ö ±æ ÂÊ Óë Ëõ ·Å",
                 PK(100,235,255),PK(255,92,180),BG);
        resTitle(s,r0+1,c0,width,"--  »­ Ãæ ·Ö ±æ ÂÊ  --",
                 PK(255,214,120),PK(255,110,150),BG);
        char b[256];
        snprintf(b,sizeof(b),
                 "   ´°¿Ú %d x %d ¸ñ   Ëõ·Å %+d ²½   ±àÂë %s   ×ÖÌå %s",
                 maxC,maxR,gFontSteps,encName(),fontLabel());
        resLine(s,r0+3,c0,width,DIM,BG,b);
        resLine(s,r0+4,c0,width,DIM,BG,
                "   Íø¸ñÔ½´ó»­ÃæÔ½¾«Ï¸£¬µ«´¦ÀíÆ÷ÓëÖÕ¶ËÊä³ö¿ªÏúÒ²Ô½´ó");
        snprintf(b,sizeof(b),"   µÚ %d-%d / %d Ïî   %s%s  1-7 ¿ìÑ¡¿É¼ûÏî",
                 top+1,imin(N,top+VIS),N,
                 top>0?"¡ü ÉÏ ":"",top+VIS<N?"¡ý ÏÂ ":"");
        resLine(s,r0+5,c0,width,DIM,BG,b);
        /* Scrollable list: VIS rows, numbered 1..VIS for quick picking.  Rows
           are described in display columns, never in bytes, so CJK labels and
           notes line up with the ASCII presets. */
        for(int v=0;v<VIS;v++){
            int i=top+v;
            if(i>=N){ resLine(s,r0+6+v,c0,width,BG,BG,""); continue; }
            bool avail=(O[i].c==0)||(O[i].c<0)||(O[i].c<=maxC&&O[i].r<=maxR);
            std::string ln="  ";
            ln+=(i==sel?"> ":"  ");
            char idx[16]; snprintf(idx,sizeof(idx),"%d  ",v+1); ln+=idx;
            ln+=O[i].label;
            for(int q=dispWidth(O[i].label);q<11;q++) ln+=' ';
            if(O[i].c==0){
                char g[64]; snprintf(g,sizeof(g),"%d x %d  ",maxC,maxR);
                ln+=g; ln+=O[i].note;
            }else if(O[i].c<0){
                char g[64]; snprintf(g,sizeof(g),"[%d x %d]  ",cc,rr);
                ln+=g; ln+=O[i].note;
            }else{
                if(avail) ln+=O[i].note;
                else      ln+="´°¿Ú²»×ã ¡¤ ÇëÏȰ´ Z Ëõ·Å»ò·Å´ó´°¿Ú";
            }
            resLine(s,r0+6+v,c0,width,
                    !avail?LOCK:(i==sel?HOT:TXT),(i==sel?SELBG:BG),ln.c_str());
        }
        if(full){
            resTitle(s,r0+14,c0,width,"--  ÖÕ ¶Ë Ëõ ·Å  --",
                     PK(120,255,190),PK(90,170,255),BG);
            resLine(s,r0+15,c0,width,DIM,BG,
                    "   - ËõС×ÖÌå = ¸ü¶à¸ñ×Ó      + ·Å´ó×ÖÌå = ¸üÉÙ¸ñ×Ó");
            resLine(s,r0+16,c0,width,DIM,BG,
                    "   Z ×Ô¶¯Ëõ·Åµ½×î´óÍø¸ñ      0 »¹Ô­Ô­Ê¼×ÖÌå");
            resLine(s,r0+17,c0,width,DIM,BG,
                    "   R ÊÖ¶¯ Ctrl+- / ¹öÂÖËõ·ÅºóÖØÐ¼ì²â´°¿Ú");
            if(warn)                    resLine(s,r0+18,c0,width,WARN,BG,warn);
            else if(editing)            resLine(s,r0+18,c0,width,HOT,BG,
                     "   ±à¼­£º¡û / ¡ú ÁÐÊý ¡À4   ¡ü / ¡ý ÐÐÊý ¡À2   »Ø³µ Ó¦ÓÃ");
            else if(!gZoomMsg.empty())  resLine(s,r0+18,c0,width,HOT,BG,gZoomMsg.c_str());
            else if(gZoomWorks)         resLine(s,r0+18,c0,width,LOCK,BG,
                     "   Ëõ·ÅÒÑÉúЧ - ÔÙ°´ - ¿É»ñµÃ¸ü¶à×Ö·û¸ñ");
            else                        resLine(s,r0+18,c0,width,LOCK,BG,
                     "   ½¨ÒéÏÈ×î´ó»¯´°¿Ú£»×Ô¶¯Ñ¡Ïî»áʵʱ¸úËæ´°¿Ú±ä»¯");
            resLine(s,r0+19,c0,width,DIM,BG,
                    "   W/S ÒÆ¶¯   »Ø³µ Ó¦Óà   L ±àÂë   F ×ÖÌå   Q ±£Áôµ±Ç°");
            resLine(s,r0+20,c0,width,DIM,BG,
                    "   ÓÎÏ·Öа´ V ÖØ¿ª±¾Ãæ°å   Ëõ·Å½âËø¸ü¸ßµµÎ»   ÖÐÎÄÂÒÂë°´ L");
            snprintf(b,sizeof(b),"   ·¶Î§: %d..%d ÁÐ x %d..%d ÐÐ   £¨²»µÃ³¬¹ý´°¿Ú£©",
                     42,maxC,18,maxR);
            resLine(s,r0+21,c0,width,LOCK,BG,b);
        }else{
            if(warn)                    resLine(s,r0+14,c0,width,WARN,BG,warn);
            else if(editing)            resLine(s,r0+14,c0,width,HOT,BG,
                     "   ±à¼­£º¡û / ¡ú ÁÐÊý ¡À4   ¡ü / ¡ý ÐÐÊý ¡À2");
            else if(!gZoomMsg.empty())  resLine(s,r0+14,c0,width,HOT,BG,gZoomMsg.c_str());
            else                        resLine(s,r0+14,c0,width,DIM,BG,
                     "   W/S »ò ¡ü¡ý ÒÆ¶¯   »Ø³µ Ó¦Óà   1-7 ¿ìÑ¡");
            if(editing) resLine(s,r0+15,c0,width,DIM,BG,
                                "   »Ø³µ Ó¦Óà     ESC ·µ»ØËõ·Å°´¼ü");
            else        resLine(s,r0+15,c0,width,DIM,BG,
                                "   Q ±£Áôµ±Ç°   ÓÎÏ·Öа´ V ÖØ¿ª±¾Ãæ°å");
            resLine(s,r0+16,c0,width,LOCK,BG,
                    "   -/+ Ëõ·Å   0 »¹Ô­   Z ×î´ó   R ÖØ²â   L ±àÂë   F ×ÖÌå");
            snprintf(b,sizeof(b),"   ·¶Î§: %d..%d ÁÐ x %d..%d ÐÐ",42,maxC,18,maxR);
            resLine(s,r0+17,c0,width,LOCK,BG,b);
            resLine(s,r0+18,c0,width,DIM,BG,
                    "   1-7 ¿ìÑ¡¿É¼ûÏî   ÖÐÎÄÂÒÂë°´ L Çл»±àÂë   ¹² 11 Ïî");
        }
        term.raw(s);
    };
    auto pin=[&](int c,int r){
        term.cols=imax(42,imin(maxC,c));
        term.rows=imax(18,imin(maxR,r));
        fixedRes=true;
        resize();
    };
    auto synced=[&](){                       /* refresh limits after a zoom */
        maxC=gWinC; maxR=gWinR;
        cc=imax(42,imin(maxC,cc));
        rr=imax(18,imin(maxR,rr));
    };

    draw();
    bool done=false;
    while(!done){
        int k;
        if(term.poll(k)){
            warn=nullptr;
            gZoomMsg.clear();
            if(k=='l'||k=='L'){
                toggleEnc();
                char z[160];
                snprintf(z,sizeof(z),"   ÒÑÇл»ÖÐÎıàÂë: %s   ÎʺÅδÏûʧÇëÔÙ°´ L   ",
                         encName());
                gZoomMsg=z; draw(); continue;
            }
            if(k=='f'||k=='F'){
                char z[160];
                if(cycleFont())
                    snprintf(z,sizeof(z),"   ÒÑÇл»×ÖÌå: %s   ÔÙ°´ F »»ÏÂÒ»ÖÖ   ",fontLabel());
                else
                    snprintf(z,sizeof(z),"   ÎÞ·¨¸Ä×ÖÌå - ÇëÔÚ´°¿ÚÊôÐÔÑ¡ Consolas   ");
                gZoomMsg=z; draw(); continue;
            }
            if(editing){
                if(k==1075||k=='a'||k=='A') cc=imax(42,cc-4);
                else if(k==1077||k=='d'||k=='D') cc=imin(maxC,cc+4);
                else if(k==1072||k=='w'||k=='W') rr=imin(maxR,rr+2);
                else if(k==1080||k=='s'||k=='S') rr=imax(18,rr-2);
                else if(k=='\r'||k=='\n'||k==' '){ pin(cc,rr); done=true; }
                else if(k==27||k=='q'||k=='Q'){ editing=false; }
                draw();
                continue;
            }
            /* ---- terminal zoom keys (list mode) ---- */
            if(k=='-'||k=='_'){ zoomStep(-1); synced(); draw(); continue; }
            if(k=='+'||k=='='){ zoomStep( 1); synced(); draw(); continue; }
            if(k=='0')        { zoomReset();  synced(); draw(); continue; }
            if(k=='r'||k=='R'){
                detectWindow(); synced();
                char z[128];
                snprintf(z,sizeof(z),"   ÒÑÖØÐ¼ì²â´°¿Ú: %d x %d ¸ñ   £¨ÊÖ¶¯Ëõ·ÅºóʹÓã©",
                         maxC,maxR);
                gZoomMsg=z; draw(); continue;
            }
            if(k=='z'||k=='Z'){
                zoomAuto(); synced();
                term.cols=maxC; term.rows=maxR; fixedRes=false; resize();
                draw();
                std::this_thread::sleep_for(std::chrono::milliseconds(800));
                done=true; break;
            }
            bool confirm=false;
            if(k>='1'&&k<='7'){
                int t=top+(k-'1');                 /* quick pick a VISIBLE row */
                if(t<N){ sel=t; confirm=true; }
            }
            else if(k==1072||k=='w'||k=='W'){ sel=(sel+N-1)%N; keepVisible(); }
            else if(k==1080||k=='s'||k=='S'){ sel=(sel+1)%N;   keepVisible(); }
            else if(k=='q'||k=='Q'||k==27){ done=true; draw(); break; }
            else if(k=='\r'||k=='\n'||k==' ') confirm=true;
            if(confirm){
                if(sel==0){ term.cols=maxC; term.rows=maxR; fixedRes=false; resize(); done=true; }
                else if(sel==N-1){ editing=true; }
                else if(O[sel].c>maxC||O[sel].r>maxR){
                    warn="   ´°¿Ú²»¹»´ó - Çë°´ Z Ëõ·ÅÖÕ¶Ë»ò·Å´ó´°¿ÚºóÖØÊÔ";
                }
                else { pin(O[sel].c,O[sel].r); done=true; }
            }
            draw();
        }else{
            std::this_thread::sleep_for(std::chrono::milliseconds(12));
        }
    }
    term.raw("\x1b[2J\x1b[H");
}

/* ------------------------------------------------------------------ */
/* input + main                                                        */
/* ------------------------------------------------------------------ */
static void handleKey(int k,bool& quit){
    if(k=='l'||k=='L'){
        toggleEnc();
        char m[128];
        snprintf(m,sizeof(m),"ÖÐÎıàÂë: %s   ÈÔÊÇÎʺŰ´ L£¬×ÖÌå²»¶Ô°´ F",encName());
        setMsg(m,1.8f);
        return;
    }
    if(k=='f'||k=='F'){
        char m[160];
        if(cycleFont())
            snprintf(m,sizeof(m),"ÖÕ¶Ë×ÖÌå: %s   °´ F »»ÏÂÒ»ÖÖ",fontLabel());
        else
            snprintf(m,sizeof(m),"´ËÖն˲»ÔÊÐí³ÌÐò¸Ä×ÖÌå - ÇëÔÚ´°¿ÚÊôÐÔÀïÑ¡ Consolas »òÐÂËÎÌå");
        setMsg(m,2.0f);
        return;
    }
    if(k=='v'||k=='V'){ chooseResolution(true); return; }
    if(k=='q'||k=='Q'){ quit=true; return; }
    if(k==27){
        if(state==PLAY) state=PAUSE;
        else if(state==PAUSE) state=PLAY;
        else quit=true;
        return;
    }
    if(k=='p'||k=='P'){
        if(state==PLAY) state=PAUSE;
        else if(state==PAUSE) state=PLAY;
        return;
    }
    if(state==MENU||state==OVER){
        if(k==' '||k=='\r'||k=='\n'||k=='r'||k=='R'){ resetGame(false); }
        return;
    }
    if(state!=PLAY) return;
    if(k=='a'||k=='A'||k==1075){ if(lane>0){ lane--; spawnBurst(px,py+0.3f,pz,PK(120,220,255),5,0.45f); } }
    else if(k=='d'||k=='D'||k==1077){ if(lane<2){ lane++; spawnBurst(px,py+0.3f,pz,PK(255,120,190),5,0.45f); } }
    else if(k==' '||k=='w'||k=='W'||k==1072) jump();
    else if(k=='s'||k=='S'||k==1080) slide();
    else if(k=='r'||k=='R') resetGame(false);
}

int main(){
    rngState=(uint32_t)std::chrono::high_resolution_clock::now().time_since_epoch().count()|1u;
    initFog();
    term.init();
    hiresTimer(true);
    chooseResolution(false);
    resize();
    const char* ep=getenv("NR_PLAY");
    resetGame(!(ep && atoi(ep)));
    camZ=pz-6.6f; ca=cosf(pitch); sa=sinf(pitch);
    horizon=H*0.5f+tanf(pitch)*focal;
    spawnWorld();

    bool quit=false;
    int frame=0;
    const char* bench=getenv("NR_BENCH");
    auto last=std::chrono::steady_clock::now();
    while(!quit){
        auto start=std::chrono::steady_clock::now();
        const float target=1.0f/targetFPS();      /* adapts to the grid area */
        const float maxDt=fminf(0.075f,2.75f*target);
        float dt=std::chrono::duration<float>(start-last).count();
        last=start;
        if(dt>maxDt) dt=maxDt;
        if(dt<0.001f) dt=0.001f;
        gTime+=dt;

        int k;
        while(term.poll(k)){ handleKey(k,quit); if(quit) break; }
        if(quit) break;

        frame++;
        if(!fixedRes && (frame%45)==0){
            int oc=term.cols, orr=term.rows;
            term.querySize();
            if(oc!=term.cols||orr!=term.rows) resize();
        }
        update(dt);

        std::fill(zb.begin(),zb.end(),0.0f);
        drawSky();
        drawCity3D();
        drawTrack();
        drawObstacles();
        drawCoins();
        drawPlayer();
        drawParts();
        speedLines();
        post();
        buildHUD();
        std::string out=encode();
        term.write(out.data(),out.size());

        if(bench && (frame%20)==0){
            static auto bt=std::chrono::steady_clock::now();
            static bool btReady=false;
            auto bn=std::chrono::steady_clock::now();
            if(btReady){
                float ms=std::chrono::duration<float,std::milli>(bn-bt).count();
                fprintf(stderr,"NR Ö¡ÂÊ: 20 Ö¡ºÄʱ %.0f ºÁÃë (%.1f fps)\n",ms,20000.0f/fmaxf(1.0f,ms));
            }
            bt=bn; btReady=true;
        }
        /* Frame pacing.  Windows sometimes silently reverts the 1 ms timer back
           to its 15.6 ms default, which stretches a 20 ms frame to 31 ms and
           halves the frame rate.  Detect that (3 consecutive overshoots) and
           switch to a sleep + yield-spin hybrid that meets the target without
           depending on the system timer resolution at all. */
        /* target is computed at the top of the loop from the current grid. */
        static bool coarse=false;
        static int coarseHits=0;
        float el=std::chrono::duration<float>(std::chrono::steady_clock::now()-start).count();
        if(el<target){
            float remain=target-el;
            if(!coarse && remain>0.0025f){
                auto ws=std::chrono::steady_clock::now();
                std::this_thread::sleep_for(std::chrono::microseconds(
                    (int)((remain-0.0015f)*1000000.0f)));
                float slept=std::chrono::duration<float>(
                    std::chrono::steady_clock::now()-ws).count();
                if(slept>remain+0.003f){ if(++coarseHits>=3) coarse=true; }
                else coarseHits=0;
            }
            while(std::chrono::duration<float>(
                      std::chrono::steady_clock::now()-start).count()<target)
                std::this_thread::yield();
        }
    }
    char fin[192];
    snprintf(fin,sizeof(fin),
             "ÄÞºçÅÜ¿á 3D  -  ×îÖÕ·ÖÊý: %d   ×î¸ß·Ö: %d   ¾àÀë: %dm   ÖÐÎıàÂë: %s\n",
             score,best,distM,encName());
    term.restore(fin);
    hiresTimer(false);
    return 0;
}