// Codigo propio (20-11). Texto del menu del titulo (title_image02/03 en 0769.bin, PSMT8 de 256x256).
// Cada pixel guarda un "nivel" (0 fondo, 1-127 brillo alrededor de la letra, 128-255 letra, 255 = centro) y cada paleta
// lo colorea de una forma (letra, contorno en degradado, brillo, mascara). El juego superpone varias.
using System; using System.IO; using System.Text; using System.Collections.Generic;
using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.Drawing.Text;
using System.Runtime.InteropServices;
public static class Titulo {
  // ---- direcciones PSMT8 subidas como CT32 (igual que extract_textures.ps1) ----
  static readonly int[,] B8 = {{0,1,4,5,16,17,20,21},{2,3,6,7,18,19,22,23},{8,9,12,13,24,25,28,29},{10,11,14,15,26,27,30,31}};
  static readonly int[,] C8 = {
    {0,4,16,20,32,36,48,52,2,6,18,22,34,38,50,54},{8,12,24,28,40,44,56,60,10,14,26,30,42,46,58,62},
    {33,37,49,53,1,5,17,21,35,39,51,55,3,7,19,23},{41,45,57,61,9,13,25,29,43,47,59,63,11,15,27,31},
    {96,100,112,116,64,68,80,84,98,102,114,118,66,70,82,86},{104,108,120,124,72,76,88,92,106,110,122,126,74,78,90,94},
    {65,69,81,85,97,101,113,117,67,71,83,87,99,103,115,119},{73,77,89,93,105,109,121,125,75,79,91,95,107,111,123,127},
    {128,132,144,148,160,164,176,180,130,134,146,150,162,166,178,182},{136,140,152,156,168,172,184,188,138,142,154,158,170,174,186,190},
    {161,165,177,181,129,133,145,149,163,167,179,183,131,135,147,151},{169,173,185,189,137,141,153,157,171,175,187,191,139,143,155,159},
    {224,228,240,244,192,196,208,212,226,230,242,246,194,198,210,214},{232,236,248,252,200,204,216,220,234,238,250,254,202,206,218,222},
    {193,197,209,213,225,229,241,245,195,199,211,215,227,231,243,247},{201,205,217,221,233,237,249,253,203,207,219,223,235,239,251,255}};
  static readonly int[,] B32 = {{0,1,4,5,16,17,20,21},{2,3,6,7,18,19,22,23},{8,9,12,13,24,25,28,29},{10,11,14,15,26,27,30,31}};
  static readonly int[,] C32 = {{0,1,4,5,8,9,12,13},{2,3,6,7,10,11,14,15},{16,17,20,21,24,25,28,29},{18,19,22,23,26,27,30,31},
    {32,33,36,37,40,41,44,45},{34,35,38,39,42,43,46,47},{48,49,52,53,56,57,60,61},{50,51,54,55,58,59,62,63}};
  static int[] inv32;
  static void Init(){ if(inv32!=null) return; inv32=new int[2048];
    for(int y=0;y<32;y++) for(int x=0;x<64;x++){ inv32[B32[y>>3,x>>3]*64+C32[y&7,x&7]]=y*64+x; } }
  static int Byte8(int x, int y, int w) {
    int pw = Math.Max(1, w / 128), page = (y >> 6) * pw + (x >> 7), px = x & 127, py = y & 63;
    int A = B8[py >> 4, px >> 4] * 256 + C8[py & 15, px & 15];
    int c = inv32[A >> 2]; int cw = Math.Min(pw * 64, w / 2); int X = (page % pw) * 64 + (c & 63), Y = (page / pw) * 32 + (c >> 6);
    return (Y * cw + X) * 4 + (A & 3); }
  static int Csm1(int i){ return (i & 0xE7) | ((i & 8) << 1) | ((i & 16) >> 1); }
  public static ulong Fnv(byte[] d, int off, int len) { ulong h=14695981039346656037UL; for (int j=0;j<len;j++){ h^=d[off+j]; h*=1099511628211UL; } return h; }

  public class Tex { public string nombre; public int w, h, off; public List<int> paletas = new List<int>(); }
  // Busca las entradas PXTB con ese nombre (una por paleta). PSMT8, paleta de 32 bits.
  public static Tex Buscar(byte[] d, string nombre) {
    Init(); var magic = Encoding.ASCII.GetBytes("PXTB0001"); Tex t = null;
    for (int o = 0; o + 16 <= d.Length; o += 16) {
      bool m = true; for (int k=0;k<8;k++) if (d[o+k]!=magic[k]) { m=false; break; } if (!m) continue;
      int n = BitConverter.ToInt32(d,o+8), es = BitConverter.ToInt32(d,o+12);
      for (int i=0;i<n;i++){ int e=o+16+i*es; int desc=o+BitConverter.ToInt32(d,e), pald=o+BitConverter.ToInt32(d,e+4);
        if (Encoding.ASCII.GetString(d,desc,16).Split('\0')[0] != nombre) continue;
        if (t == null) { t = new Tex(); t.nombre = nombre; t.w = 1 << (d[desc+18] >> 4); t.h = 1 << (d[desc+18] & 15); t.off = o + BitConverter.ToInt32(d,desc+24); }
        int pal = o + BitConverter.ToInt32(d,pald+24); if (!t.paletas.Contains(pal)) t.paletas.Add(pal); } }
    return t; }
  public static byte[] LeerNiveles(byte[] d, Tex t) { var r = new byte[t.w*t.h]; for (int y=0;y<t.h;y++) for (int x=0;x<t.w;x++) r[y*t.w+x] = d[t.off + Byte8(x,y,t.w)]; return r; }
  public static void EscribirNiveles(byte[] d, Tex t, byte[] v) { for (int y=0;y<t.h;y++) for (int x=0;x<t.w;x++) d[t.off + Byte8(x,y,t.w)] = v[y*t.w+x]; }
  // Colores ARGB (alfa del PNG = GS x2) de una paleta para cada nivel.
  public static int[] Colores(byte[] d, int pal) { var c = new int[256]; for (int i=0;i<256;i++){ int p = pal + Csm1(i)*4;
      int a = Math.Min(255, d[p+3]*2); c[i] = (a<<24)|(d[p]<<16)|(d[p+1]<<8)|d[p+2]; } return c; }
  public static string Clave(byte[] d, Tex t, int pal) { return Fnv(d, t.off, t.w*t.h).ToString("x16") + "_" + Fnv(d, pal, 1024).ToString("x16"); }

  // ---- niveles en alta resolucion ----
  static float Cub(float a, float b, float c, float e, float t) { // Catmull-Rom
    return b + 0.5f*t*(c - a + t*(2*a - 5*b + 4*c - e + t*(3*(b - c) + e - a))); }
  public static float[] AmpliarNiveles(byte[] v, int w, int h, int k) {
    int W=w*k, H=h*k; var r = new float[W*H];
    Func<int,int,float> g = (x,y) => v[Math.Max(0,Math.Min(h-1,y))*w + Math.Max(0,Math.Min(w-1,x))];
    for (int Y=0;Y<H;Y++) { float fy=(Y+0.5f)/k-0.5f; int y0=(int)Math.Floor(fy); float ty=fy-y0;
      for (int X=0;X<W;X++) { float fx=(X+0.5f)/k-0.5f; int x0=(int)Math.Floor(fx); float tx=fx-x0;
        float[] col = new float[4];
        for (int j=-1;j<=2;j++) col[j+1] = Cub(g(x0-1,y0+j), g(x0,y0+j), g(x0+1,y0+j), g(x0+2,y0+j), tx);
        r[Y*W+X] = Cub(col[0],col[1],col[2],col[3],ty); } }
    return r; }
  public static int[] Pintar(float[] f, int[] col) { var r = new int[f.Length]; for (int i=0;i<f.Length;i++){ int n=(int)Math.Round(f[i]); n=Math.Max(0,Math.Min(255,n)); r[i]=col[n]; } return r; }

  // ---- distancia con signo (dead reckoning de Grevera; dentro positiva) en pixeles ----
  public static float[] Distancia(bool[] dentro, int w, int h) {
    var px = new int[w*h]; var py = new int[w*h]; var d = new float[w*h];
    for (int y=0;y<h;y++) for (int x=0;x<w;x++) { int i=y*w+x; bool b=dentro[i];
      bool borde = (x>0&&dentro[i-1]!=b)||(x<w-1&&dentro[i+1]!=b)||(y>0&&dentro[i-w]!=b)||(y<h-1&&dentro[i+w]!=b);
      if (borde) { d[i]=0; px[i]=x; py[i]=y; } else { d[i]=1e9f; px[i]=-100000; py[i]=-100000; } }
    int[] fx={-1,0,1,-1}, fy={-1,-1,-1,0}, bx={1,-1,0,1}, by={0,1,1,1};
    for (int pase=0; pase<2; pase++) {
      int[] ox = pase==0?fx:bx, oy = pase==0?fy:by;
      for (int yy=0;yy<h;yy++) { int y = pase==0?yy:h-1-yy;
        for (int xx=0;xx<w;xx++) { int x = pase==0?xx:w-1-xx; int i=y*w+x;
          for (int k=0;k<4;k++){ int nx=x+ox[k], ny=y+oy[k]; if(nx<0||ny<0||nx>=w||ny>=h) continue; int j=ny*w+nx;
            if (px[j] < -1000) continue; float dx=x-px[j], dy=y-py[j]; float dd=(float)Math.Sqrt(dx*dx+dy*dy);
            if (dd < d[i]) { d[i]=dd; px[i]=px[j]; py[i]=py[j]; } } } } }
    for (int i=0;i<w*h;i++) d[i] = dentro[i] ? d[i]+0.5f : -(d[i]+0.5f);
    return d; }

  // Nivel medio segun la distancia con signo (en texeles), medido en el texto original ampliado: tabla de -8 a +4 en
  // pasos de 1/8. Monotona (cuanto mas dentro, mas nivel).
  public const float TMIN = -8f, TPASO = 0.125f; public const int TN = 97;
  public static float[] Calibrar(float[] f4, int W, int H, int y0, int y1, int x0) {
    var dentro = new bool[W*H]; for (int i=0;i<W*H;i++) dentro[i] = f4[i] >= 127.5f;
    var sd = Distancia(dentro, W, H); var s = new double[TN]; var n = new int[TN];
    for (int y=y0*4;y<y1*4;y++) for (int x=x0*4;x<W;x++){ int i=y*W+x; int b=(int)Math.Round((sd[i]/4f - TMIN)/TPASO); if(b<0||b>=TN) continue; s[b]+=f4[i]; n[b]++; }
    // Las distancias salen en saltos (raices de enteros): los cajones sin muestras se interpolan entre los vecinos.
    var t = new float[TN]; var ok = new bool[TN];
    for (int b=0;b<TN;b++){ ok[b] = n[b] > 20; t[b] = ok[b] ? (float)Math.Max(0, Math.Min(255, s[b]/n[b])) : 0; }
    for (int b=0;b<TN;b++) if (!ok[b]) {
      int a=b-1; while (a>=0 && !ok[a]) a--; int c=b+1; while (c<TN && !ok[c]) c++;
      if (a<0 && c>=TN) t[b]=0; else if (a<0) t[b]=t[c]; else if (c>=TN) t[b]=t[a]; else t[b] = t[a] + (t[c]-t[a])*(b-a)/(float)(c-a); }
    float ult = 0; for (int b=0;b<TN;b++){ t[b] = Math.Max(ult, t[b]); ult = t[b]; }
    return t; }
  public static float Nivel(float[] tabla, float sdTex) {
    float p = (sdTex - TMIN)/TPASO; if (p<=0) return tabla[0]; if (p>=TN-1) return tabla[TN-1];
    int a=(int)p; float f=p-a; return tabla[a]*(1-f)+tabla[a+1]*f; }

  // Dibuja una palabra con una fuente TrueType y devuelve su campo de niveles a x4 (ancho cw*4, alto ch*4) y a x1.
  // cx = centro horizontal y base = fila de la linea base, en texeles de la caja (0..cw, 0..ch).
  public static void Palabra(string texto, string fuente, float altoX, float estirar, float anchoMax, float cx, float base_,
                             float grosor, float[] tabla, int cw, int ch, out float[] f4, out byte[] f1, out string info) {
    const int S = 8; int W=cw*S, H=ch*S;
    var dentro = new bool[W*H];
    using (var fam = new FontFamily(fuente)) using (var gp = new GraphicsPath()) {
      gp.AddString("x", fam, 0, 100f, new PointF(0,0), StringFormat.GenericTypographic);
      var bx = gp.GetBounds(); float em = 100f * altoX / bx.Height;   // em en texeles para ese alto de la x
      float asc = em * fam.GetCellAscent(0) / fam.GetEmHeight(0);
      using (var p = new GraphicsPath()) {
        p.AddString(texto, fam, 0, em, new PointF(0,0), StringFormat.GenericTypographic);
        var b = p.GetBounds(); float sx = estirar; if (b.Width*sx > anchoMax) sx = anchoMax / b.Width;
        var m = new Matrix(); m.Scale(S, S); m.Translate(cx - (b.X + b.Width/2f)*sx, base_ - asc); m.Scale(sx, 1f);
        p.Transform(m);
        info = string.Format("em={0:0.0} ancho={1:0.0} estirado={2:0.00}", em, b.Width*sx, sx);
        using (var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb)) using (var g = Graphics.FromImage(bmp)) {
          g.Clear(Color.Black); g.SmoothingMode = SmoothingMode.None; g.FillPath(Brushes.White, p);
          var bd = bmp.LockBits(new Rectangle(0,0,W,H), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
          var px = new int[W*H]; Marshal.Copy(bd.Scan0, px, 0, px.Length); bmp.UnlockBits(bd);
          for (int i=0;i<W*H;i++) dentro[i] = (px[i] & 0xFF) > 127; } } }
    var sd = Distancia(dentro, W, H);
    f4 = new float[cw*4*ch*4];
    for (int y=0;y<ch*4;y++) for (int x=0;x<cw*4;x++){ float s=0; for(int j=0;j<2;j++) for(int i=0;i<2;i++) s+=sd[(y*2+j)*W + x*2+i];
      f4[y*cw*4+x] = Nivel(tabla, s/4f/S + grosor); }
    f1 = new byte[cw*ch];
    for (int y=0;y<ch;y++) for (int x=0;x<cw;x++){ float s=0; for(int j=0;j<4;j++) for(int i=0;i<4;i++) s+=f4[(y*4+j)*cw*4 + x*4+i];
      f1[y*cw+x] = (byte)Math.Max(0, Math.Min(255, (int)Math.Round(s/16f))); }
  }

  // ---- PNG ----
  public static int[] LeerPng(string f, out int w, out int h) {
    using (var b0 = new Bitmap(f)) { w=b0.Width; h=b0.Height;
      using (var b = b0.Clone(new Rectangle(0,0,w,h), PixelFormat.Format32bppArgb)) {
        var bd=b.LockBits(new Rectangle(0,0,w,h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
        var p=new int[w*h]; Marshal.Copy(bd.Scan0,p,0,p.Length); b.UnlockBits(bd); return p; } } }
  public static void GuardarPng(string f, int[] p, int w, int h) {
    using (var b=new Bitmap(w,h,PixelFormat.Format32bppArgb)) {
      var bd=b.LockBits(new Rectangle(0,0,w,h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
      Marshal.Copy(p,0,bd.Scan0,p.Length); b.UnlockBits(bd); b.Save(f, ImageFormat.Png); } }
}
