﻿using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices;
// Cesped dibujado (codigo propio, 21-11). El color sale del original ampliado (caminos, flores y manchas quedan donde
// estaban) y el detalle fino son briznas dibujadas aqui: miles de trazos finos con sombra, repartidos al azar y
// envolviendo los bordes (la textura se repite sin costuras). Solo se ponen briznas donde el original es verde.
public static class Cesped {
  public static int[] Leer(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 Guardar(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); }
  }
  static float CR(float a, float b, float c, float d, float t) {
    return b + 0.5f * t * (c - a + t * (2 * a - 5 * b + 4 * c - d + t * (3 * (b - c) + d - a)));
  }
  // Catmull-Rom envolvente: canal ch (0 b, 1 g, 2 r, 3 a) ampliado k veces.
  public static float[] Ampliar(float[] c, int w, int h, int k) {
    int W = w * k, H = h * k; var q = new float[W * H];
    for (int Y = 0; Y < H; Y++) for (int X = 0; X < W; X++) {
      float fx = (X + 0.5f) / k - 0.5f, fy = (Y + 0.5f) / k - 0.5f;
      int ix = (int)Math.Floor(fx), iy = (int)Math.Floor(fy); float tx = fx - ix, ty = fy - iy;
      var fila = new float[4];
      for (int j = 0; j < 4; j++) { int yy = ((iy - 1 + j) % h + h) % h;
        Func<int, float> g = i => c[yy * w + ((ix - 1 + i) % w + w) % w];
        fila[j] = CR(g(0), g(1), g(2), g(3), tx); }
      q[Y * W + X] = CR(fila[0], fila[1], fila[2], fila[3], ty);
    }
    return q;
  }
  static float[] Canal(int[] p, int s) { var q = new float[p.Length]; for (int i = 0; i < p.Length; i++) q[i] = (p[i] >> s) & 255; return q; }
  // Briznas: valor 0 (hueco oscuro) a 1 (brizna al sol), envolvente.
  public static float[] Briznas(int W, int H, int semilla, double densidad, double largo, double grueso, double dirFija) {
    var r = new Random(semilla); var d = new float[W * H];
    for (int i = 0; i < d.Length; i++) d[i] = 0.25f;
    int n = (int)(W * H * densidad / (largo * grueso));
    for (int b = 0; b < n; b++) {
      double x = r.NextDouble() * W, y = r.NextDouble() * H;
      double ang = dirFija >= 0 ? dirFija + (r.NextDouble() - 0.5) * 1.2 : r.NextDouble() * Math.PI * 2;
      double L = largo * (0.6 + 0.8 * r.NextDouble()), curva = (r.NextDouble() - 0.5) * 1.4 / L, g0 = grueso * (0.7 + 0.6 * r.NextDouble());
      float v = (float)(0.55 + 0.45 * r.NextDouble());
      for (int pasada = 0; pasada < 2; pasada++) {
        double px = x, py = y, a = ang;
        // pasada 0: sombra desplazada; pasada 1: la brizna
        double ox = pasada == 0 ? 1.2 : 0, oy = pasada == 0 ? 1.6 : 0;
        for (double t = 0; t < L; t += 0.5) {
          double rad = g0 * (1 - 0.85 * t / L) * 0.5 + 0.35;
          float val = pasada == 0 ? 0.05f : v * (float)(0.75 + 0.25 * t / L);
          Disco(d, W, H, px + ox, py + oy, rad, val, pasada == 0 ? 0.5f : 1f);
          a += curva * 0.5; px += Math.Cos(a) * 0.5; py += Math.Sin(a) * 0.5;
        }
      }
    }
    return d;
  }
  static void Disco(float[] d, int W, int H, double cx, double cy, double rad, float val, float op) {
    int x0 = (int)Math.Floor(cx - rad - 1), x1 = (int)Math.Ceiling(cx + rad + 1), y0 = (int)Math.Floor(cy - rad - 1), y1 = (int)Math.Ceiling(cy + rad + 1);
    for (int y = y0; y <= y1; y++) for (int x = x0; x <= x1; x++) {
      double dx = x + 0.5 - cx, dy = y + 0.5 - cy; double dist = Math.Sqrt(dx * dx + dy * dy);
      double cob = Math.Max(0, Math.Min(1, rad + 0.5 - dist)) * op; if (cob <= 0) continue;
      int i = ((y % H + H) % H) * W + ((x % W + W) % W);
      d[i] = (float)(d[i] + (val - d[i]) * cob);
    }
  }
  // Desenfoque gaussiano envolvente (sigma en texeles) de un canal.
  static float[] Suavizar(float[] c, int w, int h, double sigma) {
    if (sigma <= 0) return c;
    int rr = (int)Math.Ceiling(sigma * 3); var k = new float[2 * rr + 1]; float s = 0;
    for (int i = -rr; i <= rr; i++) { k[i + rr] = (float)Math.Exp(-i * i / (2 * sigma * sigma)); s += k[i + rr]; }
    for (int i = 0; i < k.Length; i++) k[i] /= s;
    var t = new float[c.Length]; var q = new float[c.Length];
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { float a = 0; for (int i = -rr; i <= rr; i++) a += k[i + rr] * c[y * w + ((x + i) % w + w) % w]; t[y * w + x] = a; }
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { float a = 0; for (int i = -rr; i <= rr; i++) a += k[i + rr] * t[((y + i) % h + h) % h * w + x]; q[y * w + x] = a; }
    return q;
  }
  // ia: la version reescalada por IA (W x H) o null; se usa donde el original no es cesped (flores, piedras, caminos).
  public static int[] Hacer(int[] o, int w, int h, int k, int semilla, double fuerza, double densidad, double largo, double grueso, double suave, int[] ia) {
    int W = w * k, H = h * k;
    // Color de fondo: el original suavizado contando solo los texeles verdes (las flores no dejan halo blanco).
    var peso = new float[w * h];
    for (int i = 0; i < peso.Length; i++) { int p = o[i]; float r1 = (p >> 16) & 255, g1 = (p >> 8) & 255, b1 = p & 255; peso[i] = Math.Max(0.02f, EsCesped(r1, g1, b1)); }
    var sp = Suavizar(peso, w, h, suave);
    Func<int, float[]> canalPesado = s => { var c0 = Canal(o, s); var m0 = new float[c0.Length]; for (int i = 0; i < c0.Length; i++) m0[i] = c0[i] * peso[i];
      var sm = Suavizar(m0, w, h, suave); for (int i = 0; i < sm.Length; i++) sm[i] /= sp[i]; return sm; };
    float[] B = Ampliar(canalPesado(0), w, h, k), G = Ampliar(canalPesado(8), w, h, k), R = Ampliar(canalPesado(16), w, h, k), A = Ampliar(Canal(o, 24), w, h, k);
    float[] Bn = Ampliar(Canal(o, 0), w, h, k), Gn = Ampliar(Canal(o, 8), w, h, k), Rn = Ampliar(Canal(o, 16), w, h, k);
    // Variacion local del original (cuanto "grano" tenia): poca en caminos lisos.
    var lum = new float[w * h]; for (int i = 0; i < lum.Length; i++) lum[i] = 0.3f * ((o[i] >> 16) & 255) + 0.59f * ((o[i] >> 8) & 255) + 0.11f * (o[i] & 255);
    var var1 = new float[w * h];
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { float s = 0, s2 = 0;
      for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) { float v = lum[((y + j + h) % h) * w + (x + i + w) % w]; s += v; s2 += v * v; }
      var1[y * w + x] = (float)Math.Sqrt(Math.Max(0, s2 / 9 - (s / 9) * (s / 9))); }
    float[] V = Ampliar(var1, w, h, k);
    float[] D = Briznas(W, H, semilla, densidad, largo, grueso, -1);
    double m = 0; foreach (var v in D) m += v; m /= D.Length;
    var q = new int[W * H];
    for (int i = 0; i < q.Length; i++) {
      float r = R[i], g = G[i], b = B[i];
      // verde: g por encima de r y b
      float verde = EsCesped(Rn[i], Gn[i], Bn[i]);
      if (ia != null) { int p = ia[i]; verde *= 1 - EsFlor((p >> 16) & 255, (p >> 8) & 255, p & 255); }
      float grano = Math.Max(0.35f, Math.Min(1.3f, V[i] / 14f));
      float f = (float)(1 + fuerza * verde * grano * (D[i] - m) * 2.2);
      // las briznas al sol tiran un poco al amarillo, los huecos al azul oscuro
      float dr = (float)((D[i] - m) * 10 * verde * fuerza);
      int R8 = Sat(r * f + dr), G8 = Sat(g * f), B8 = Sat(b * f - dr * 0.6f), A8 = Sat(A[i]);
      if (ia != null && verde < 1) { int p = ia[i]; float u = verde;
        R8 = Sat(R8 * u + ((p >> 16) & 255) * (1 - u)); G8 = Sat(G8 * u + ((p >> 8) & 255) * (1 - u)); B8 = Sat(B8 * u + (p & 255) * (1 - u)); }
      q[i] = (A8 << 24) | (R8 << 16) | (G8 << 8) | B8;
    }
    return q;
  }
  // Cesped: mas verde que rojo y que azul (tambien el verde oscuro de la sombra).
  public static float EsCesped(float r, float g, float b) {
    float c = Math.Max(0, Math.Min(1, Math.Min(g - r + 2, g - b - 4) / 14f));
    float mx = Math.Max(r, Math.Max(g, b)); return Math.Max(c, Math.Max(0, Math.Min(1, (70 - mx) / 25f)) * (g >= r - 4 ? 1 : 0)); // sombra oscura entre la hierba
  }
  // Flor o piedra clara: luminosa y poco saturada.
  public static float EsFlor(float r, float g, float b) {
    float mx = Math.Max(r, Math.Max(g, b)), mn = Math.Min(r, Math.Min(g, b)); float sat = mx > 0 ? (mx - mn) / mx : 0;
    return Math.Max(0, Math.Min(1, (mx - 140) / 40f)) * Math.Max(0, Math.Min(1, (0.45f - sat) / 0.2f));
  }
  // Parte de la textura que es cesped (para decidir si se le aplica).
  public static double Fraccion(int[] o) { double s = 0; foreach (var p in o) s += EsCesped((p >> 16) & 255, (p >> 8) & 255, p & 255) > 0.5f ? 1 : 0; return s / o.Length; }
  public static bool Opaca(int[] p) { foreach (var v in p) if (((uint)v >> 24) < 250) return false; return true; }
  static int Sat(float v) { int i = (int)Math.Round(v); return i < 0 ? 0 : i > 255 ? 255 : i; }
}





