"""A layered pixel art pond. Every water pixel ends up as one tone of RAMP, so the water
stays crisp pixel art however many layers you stack. One function per layer.
Guide: https://www.spritecook.ai/blog/pixel-art-pond-water-reflections-ripples

Use it like this (Python 3, numpy, scipy):

    pond = Pond(ground, water, filled, np.random.default_rng(11))
    cut = dark_cut(tree_sprites)                 # once, from every tree and bush sprite
    each frame, t in seconds:
        img = pond.damp_ground(ground.astype(float))
        idx = pond.tones(t, sprites, cut, ALL)   # sprites: (rgba, x0, base_y) as drawn now
        img = pond.paint(img, t, idx, ALL)       # then draw your trees on top

ground: the art, H x W x 3. water: True on open water, False on lily pads, rocks and
reed stems. filled: the whole pond, holes included. A sprite's base_y is the row under
its feet: it is drawn with its top-left at (x0, base_y - height)."""
import math

import numpy as np
from scipy import ndimage

LOOP = 5.0                    # seconds; every motion runs whole cycles per loop
TAU = 2 * math.pi
K4 = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
ALL = ("depth", "sky", "reflections", "edges", "bank", "life")

# the palette, dark to light: 0-6 water, 7 shallow water over mud,
# 8 and 9 the bank's mud and grass as seen in the water
RAMP = np.array([[0x1d, 0x3a, 0x44], [0x24, 0x50, 0x5a], [0x2e, 0x64, 0x68],
                 [0x3f, 0x84, 0x84], [0x5d, 0x9f, 0xa6], [0x6f, 0xb3, 0xa8],
                 [0xc4, 0xec, 0xe2], [0x5a, 0x93, 0x84], [0x2c, 0x3b, 0x36],
                 [0x2d, 0x52, 0x46]], float)
LUMA = np.array([0.3, 0.59, 0.11])       # brightness = rgb @ LUMA, 0 to 255


def phase(t, cycles):
    # the angle of something that runs `cycles` times per loop.
    # Keep cycles a whole number and the loop has no seam.
    return TAU * cycles * t / LOOP


def shore_depth(filled):
    # px from each pixel to the shore. Blur the mask first, so the bands
    # follow the bank's shape and skip every notch in it.
    smooth = ndimage.gaussian_filter(filled.astype(float), 2) > 0.5
    return ndimage.distance_transform_edt(smooth)


def dark_cut(sprites):
    # the brightness below which a reflected pixel is tone 0: the darkest 15%
    # of all tree and bush pixels (trunks, deep shade)
    lum = [(s[..., :3] @ LUMA)[s[..., 3] > 0] for s in sprites]
    return float(np.percentile(np.concatenate(lum), 15))


# glint frames over its 0.6 s life: (until, [(dx, tone)]) = 1 px, 3 px, 5 px, split
GLINT = [(0.15, [(0, 6)]),
         (0.30, [(-1, 5), (0, 6), (1, 5)]),
         (0.65, [(-2, 5), (-1, 6), (0, 6), (1, 6), (2, 5)]),
         (0.85, [(-2, 5), (-1, 6), (1, 6), (2, 5)]),
         (1.00, [(-2, 5), (2, 5)])]


class Pond:
    def __init__(self, ground, water, filled, rng):
        self.ground, self.water, self.filled = ground, water, filled
        self.H, self.W = water.shape
        self.yy, self.xx = np.mgrid[0:self.H, 0:self.W]
        self.depth = shore_depth(filled)
        # the far shore's row in each column, and rows below it
        self.top = np.where(filled.any(0), filled.argmax(0), self.H)
        self.row = self.yy - self.top[None, :]
        self.mid_y = int(np.median(np.nonzero(filled)[0]))
        self.far_cols = np.nonzero(self.top < self.mid_y)[0]      # the back bank
        self.setup_edges()
        self.setup_life(rng)

    # ---- 1. depth ---------------------------------------------------------
    def depth_tones(self):
        idx = np.where(self.depth > 7, 1, 2)   # deep middle, base tone further out
        idx[self.depth < 3] = 3                # a lighter rim along every shore
        return idx

    # ---- 2. sky -----------------------------------------------------------
    def sky_light(self, idx):
        inner = self.filled & (self.depth >= 3)
        idx[inner & (self.row >= 14)] = 3      # the near half mirrors the sky,
        idx[inner & (self.row >= 28)] = 4      # lighter further from the far bank
        return idx

    # ---- 3. reflections ---------------------------------------------------
    def reflect(self, idx, sprite, x0, base_y, t, dark_cut, squash=0.55):
        flipped = sprite[::-1]                 # upside down, foot at the top
        lum = flipped[..., :3] @ LUMA
        r = 0
        while int(r / squash) < len(flipped):
            y, src = base_y + r, int(r / squash)
            # rows wobble by whole pixels: none at the foot, more further out
            amp = 0 if r < 3 else (1 if r < 30 else 2)
            dx = round(amp * math.sin(y * 0.75 - phase(t, 2)))
            xs = np.arange(flipped.shape[1]) + x0 + dx
            ok = (xs >= 0) & (xs < self.W) & (flipped[src, :, 3] > 0)
            if 0 <= y < self.H:
                xs, lr = xs[ok], lum[src, ok]
                # three flat tones: trunks and shade, leaves, light leaves
                tone = np.where(lr < dark_cut, 0, np.where(lr < 110, 1, 2))
                hit = self.water[y, xs]
                # where reflections overlap, the darker one wins
                idx[y, xs[hit]] = np.minimum(idx[y, xs[hit]], tone[hit])
            r += 1
        return idx

    # ---- 4. edges ---------------------------------------------------------
    def setup_edges(self):
        things = self.filled & ~self.water             # pads, rocks, reed stems
        solid = things & ~self.pad_like(things)        # rocks and reeds only
        dist = ndimage.distance_transform_cdt(self.water | things, metric="taxicab")
        self.near_thing = ndimage.binary_dilation(solid, K4, iterations=2)
        # the shore pixel itself, on the near half, away from rocks and reeds
        self.shallow = (self.water & (dist == 1) & (self.yy > self.mid_y)
                        & ~self.near_thing)
        # distance to a smoothed shore: a 5 x 5 closing fills the grass notches
        dry = ndimage.binary_closing(~self.filled, np.ones((5, 5)), border_value=1)
        self.lap_dist = ndimage.distance_transform_cdt(~dry, metric="taxicab")
        # roughly px along the shore, for the dashes to travel along
        cy, cx = np.nonzero(self.filled)
        self.along = np.arctan2((self.yy - cy.mean()) * 2.2, self.xx - cx.mean()) * 60
        # damp ground: dry pixels touching the near and side shore
        self.wet = (~self.filled & ndimage.binary_dilation(self.filled, K4)
                    & (self.yy > self.mid_y - 6))
        # contact: water beside and below each rock and reed, never above
        lab, n = ndimage.label(solid)
        self.contact = np.zeros_like(self.water)
        for k in range(1, n + 1):
            ys, _ = np.nonzero(lab == k)
            ring = self.water & ndimage.binary_dilation(lab == k, K4)
            self.contact |= ring & (self.yy >= (ys.min() + ys.max()) / 2)

    def damp_ground(self, img):
        img[self.wet] *= 0.82
        return img

    def edges(self, idx, t):
        # 1 px of shallow water over mud
        idx[self.shallow & (idx >= 3)] = 7
        # lapping: dashes and gaps that travel along the shore,
        # 2 px out, stepping to 3 px and back twice per loop
        dash = (np.sin(self.along * 0.55 - phase(t, 2))
                + 0.6 * np.sin(self.along * 0.23 + 1.3 - phase(t, 1))) > 0.55
        ring = 3 if math.sin(phase(t, 2)) > 0.35 else 2
        lap = self.water & (self.lap_dist == ring) & dash & ~self.near_thing
        idx[lap & (idx >= 2)] = 5
        # a broken light line where water touches rocks and reeds
        pulse = np.sin(self.xx * 0.9 + self.yy * 0.4 - phase(t, 2)) > 0.3
        idx[self.contact & pulse & (idx >= 1)] = 5
        return idx

    # ---- 5. back bank -----------------------------------------------------
    def bank_tone(self, c):
        if c @ LUMA < 36:
            return 0                            # deep shadow
        return 9 if c[1] > c[0] + 12 else 8     # grass and moss, or earth

    def bank_mirror(self, idx, t):
        for x in self.far_cols:
            top = int(self.top[x])
            if self.water[top, x]:
                idx[top, x] = 0                 # dark contact line under the bank
            for k in range(1, 7):
                y = top + k
                # rows 1 to 3 solid, then every other row, wobbling 1 px
                if y >= self.H or not self.water[y, x] or (k >= 4 and k % 2):
                    continue
                dx = round(math.sin(y * 0.45 - phase(t, 2))) if k >= 4 else 0
                sy, sx = top - k, min(max(x + dx, 0), self.W - 1)
                if sy >= 0 and not self.filled[sy, sx]:
                    idx[y, x] = self.bank_tone(self.ground[sy, sx].astype(float))
        return idx

    def bank_ripples(self, idx, t):
        # faint dark ripples drifting through rows 2 to 5 of the bank's mirror
        for x in self.far_cols:
            for k in range(2, 6):
                y = int(self.top[x]) + k
                wave = (math.sin(x * 0.6 - phase(t, 1) + k * 1.7)
                        + 0.6 * math.sin(x * 0.23 + k - phase(t, 1)))
                if y < self.H and self.water[y, x] and wave > 0.95 \
                        and idx[y, x] in (0, 8, 9):
                    idx[y, x] = 0 if idx[y, x] == 9 else 1
        return idx

    def creep(self, out, t):
        # in slow segments the water covers the bank's lowest pixel, then pulls back
        for x in self.far_cols:
            top = int(self.top[x])
            s = math.sin(x * 0.35 - phase(t, 1)) + 0.5 * math.sin(x * 0.13 + 1 - phase(t, 1))
            if top >= 1 and s > 0.6:
                out[top - 1, x] = RAMP[0]
        return out

    # ---- 6. life: drops, glints, leaves, lily pads --------------------------
    def pad_like(self, things):
        # lily pads: green pieces between 20 and 80 px, wider than tall
        lab, n = ndimage.label(things)
        pads = np.zeros_like(things)
        for k in range(1, n + 1):
            ys, xs = np.nonzero(lab == k)
            c = self.ground[ys, xs].astype(float).mean(0)
            wide = (xs.max() - xs.min()) >= (ys.max() - ys.min())
            if 20 <= len(ys) <= 80 and wide and c[1] > c[0] * 1.1 and c[1] > c[2]:
                pads |= lab == k
        return pads

    def setup_life(self, rng):
        sky = np.argwhere(self.water & (self.row >= 28) & (self.depth > 3))
        deep = np.argwhere(self.water & (self.depth > 4))
        self.glints = [(sky[k][1], sky[k][0], rng.uniform(0, LOOP))
                       for k in rng.choice(len(sky), 20)]
        self.drops = [(deep[k][1], deep[k][0], rng.uniform(0, LOOP))
                      for k in rng.choice(len(deep), 1)]
        lab, n = ndimage.label(self.pad_like(self.filled & ~self.water))
        self.pads = [(np.nonzero(lab == k), k * 1.7) for k in range(1, n + 1)]
        spots = np.argwhere(self.water & (self.depth > 4) & (self.row >= 28))
        self.leaves = [(LOOP * (0.12 + 0.3 * j), *spots[k][::-1].astype(float))
                       for j, k in enumerate(rng.choice(len(spots), 2, replace=False))]
        # a landing leaf makes a ring too
        self.drops += [(int(x), int(y), lt) for lt, x, y in self.leaves]

    def ripple_frames(self):
        # five ring frames, 0.2 s each: ellipses 3x1, 5x3, 9x5, 13x7, 17x9 px.
        # The last two keep only the top and bottom arcs, so the ring breaks up.
        frames = []
        for k, (rx, ry) in enumerate([(1, 0), (2, 1), (4, 2), (6, 3), (8, 4)]):
            pts = []
            for dy in range(-ry, ry + 1):
                for dx in range(-rx, rx + 1):
                    if ry == 0:
                        pts.append((dx, dy))
                        continue
                    inside = (dx / rx) ** 2 + (dy / ry) ** 2 <= 1
                    edge = (((abs(dx) + 1) / rx) ** 2 + (dy / ry) ** 2 > 1
                            or (dx / rx) ** 2 + ((abs(dy) + 1) / ry) ** 2 > 1)
                    if inside and edge and not (k >= 3 and abs(dy) < ry * 0.5):
                        pts.append((dx, dy))
            frames.append(pts)
        return frames

    def life(self, idx, t):
        def put(x, y, tone):
            if 0 <= y < self.H and 0 <= x < self.W and self.water[y, x]:
                idx[y, x] = tone
        for gx, gy, t0 in self.glints:          # each glint lives 0.6 s
            u = ((t - t0) % LOOP) / 0.6
            for until, pts in GLINT:
                if u < until:
                    for dx, tone in pts:
                        put(gx + dx, gy, tone)
                    break
        frames = self.ripple_frames()
        for rx, ry, t0 in self.drops:            # ring frames, 0.2 s each
            k = int(((t - t0) % LOOP) / 0.2)
            for dx, dy in (frames[k] if k < len(frames) else []):
                put(rx + dx, ry + dy, 6 if k < 3 else 5)
        for (ys, xs), dy in self.pad_bob(t):     # 1 px shadow under each pad
            sy = ys + dy + 1
            ok = (sy < self.H) & self.water[np.minimum(sy, self.H - 1), xs]
            idx[sy[ok], xs[ok]] = 0
        return idx

    def pad_bob(self, t):
        # each lily pad sits 0 or 1 px lower, out of step with the others
        return [(px, 1 if math.sin(phase(t, 1) + ph) > 0.4 else 0) for px, ph in self.pads]

    def leaf_at(self, t, lt, x, y, float_s=3.0):
        # falls for 1.2 s, lands at (x, y), drifts 3 px a second, sinks after float_s
        age = (t - lt) % LOOP
        if age > LOOP - 1.2:
            u = (age - (LOOP - 1.2)) / 1.2
            return x - 14 * (1 - u) + 3 * math.sin(u * 9), y - 34 * (1 - u), "falling"
        if age < float_s:
            return x + 3 * age, y + 0.6 * math.sin(age * 1.7), "floating"
        if age < float_s + 0.6:
            return x + 3 * float_s, y, "sinking"
        return None

    # ---- all layers ---------------------------------------------------------
    def tones(self, t, sprites, dark_cut, layers=ALL):
        """Tone index per pixel. sprites: (rgba, x0, base_y) for every tree and bush
        behind the pond, as drawn this frame."""
        idx = self.depth_tones() if "depth" in layers else np.full(self.water.shape, 2)
        if "sky" in layers:
            idx = self.sky_light(idx)
        for spr, x0, base_y in (sprites if "reflections" in layers else []):
            idx = self.reflect(idx, spr, x0, base_y, t, dark_cut)
        if "edges" in layers:
            idx = self.edges(idx, t)
        if "bank" in layers:
            idx = self.bank_ripples(self.bank_mirror(idx, t), t)
        if "life" in layers:
            idx = self.life(idx, t)
        return idx

    def paint(self, img, t, idx, layers=ALL, leaf_cols=((214, 168, 60), (190, 128, 46))):
        """Tones to colors, then what moves as a whole: pads, leaves, the waterline."""
        out = img.copy()
        out[self.water] = RAMP[idx[self.water]]
        if "life" in layers:
            for (ys, xs), dy in self.pad_bob(t):
                if dy:                          # the pad 1 px lower, water where it was
                    out[ys, xs] = RAMP[idx[ys, xs]]
                    out[ys + dy, xs] = self.ground[ys, xs]
            for (lt, x, y), col in zip(self.leaves, leaf_cols):
                p = self.leaf_at(t, lt, x, y)
                if p is None:
                    continue
                lx, ly, state = int(round(p[0])), int(round(p[1])), p[2]
                cells = [(0, 0), (1, 0)]
                if state == "falling" and int((t - lt) % LOOP * 7) % 2:
                    cells = [(0, 0), (0, 1)]    # tumbling: flat, on edge, flat
                if state == "floating":         # shadow under, wake behind
                    for dx, dy, tone in ((0, 1, 0), (1, 1, 0), (-1, 0, 5)):
                        if self.water[ly + dy, lx + dx]:
                            out[ly + dy, lx + dx] = RAMP[tone]
                if state == "sinking":
                    col, cells = (58, 90, 72), [(0, 0)]
                for dx, dy in cells:
                    inside = 0 <= ly + dy < self.H and 0 <= lx + dx < self.W
                    if inside and (state == "falling" or self.water[ly + dy, lx + dx]):
                        out[ly + dy, lx + dx] = col
        if "bank" in layers:
            out = self.creep(out, t)
        return out
