import QuartzCore
import Foundation

private enum ScoopItem {
    case circle(Double, Double, Double)
    case polygon([CGPoint])
}

private struct ScoopParticle {
    var x: Double
    var y: Double
    var vx: Double
    var vy: Double
    var r: Double
    var kind: UInt8
    var sink: Bool
}

private struct ScoopRipple {
    let t0: Double
    let x: Double
    let amp: Double
}

private struct ScoopState {
    let t: Double
    let vol: Double
    let bvol: Double
    let parts: [ScoopParticle]
    let rips: [ScoopRipple]
    let tg: Double
}

private struct ScoopFrame {
    let tint: CGPath
    let goo: CGPath
    let ink: CGPath
    let ladleLine: CGPath
    let bowlLine: CGPath
}

private typealias ScoopPose = (x: Double, y: Double, a: Double, sx: Double, sy: Double)

private enum ScoopModel {
    static let duration = 3.4
    static let count = 102
    static let total = 3.4
    static let pw = 80.0
    static let gravity = 900.0
    static let ts = 1.15
    static let px0 = 16.0
    static let px1 = 56.0
    static let bx = 84.0
    static let by = 108.0
    static let land = 2.94
    static let dt = 1.0 / 600

    static let inner: [(Double, Double)] = bez((-11.6, 0), (-11.6, 15.6), (11.6, 15.6), (11.6, 0), 24)
    static let binner: [(Double, Double)] = bez((-15.4, 0), (-15.4, 19.2), (15.4, 19.2), (15.4, 0), 28)
    static let handle: (poly: [(Double, Double)], end: (Double, Double)) = handlePath()
    static let handleRadius = 3.5
    static let full = area(inner)
    static let bfull = area(binner) * 0.66

    nonisolated(unsafe) static let states: [ScoopState] = simulate()
    nonisolated(unsafe) static let frames: [ScoopFrame] = states.map { build($0) }

    static func clamp(_ u: Double) -> Double { max(0, min(1, u)) }
    static func ease(_ u: Double) -> Double { let v = clamp(u); return v * v * (3 - 2 * v) }

    static func keys(_ t: Double, _ ks: [(Double, Double)]) -> Double {
        if t <= ks[0].0 { return ks[0].1 }
        for (a, b) in zip(ks, ks.dropFirst()) where t <= b.0 {
            return a.1 + (b.1 - a.1) * ease((t - a.0) / (b.0 - a.0))
        }
        return ks[ks.count - 1].1
    }

    static func bez(_ p0: (Double, Double), _ p1: (Double, Double), _ p2: (Double, Double), _ p3: (Double, Double), _ n: Int) -> [(Double, Double)] {
        (0...n).map { i in
            let u = Double(i) / Double(n)
            let v = 1 - u
            return (v * v * v * p0.0 + 3 * v * v * u * p1.0 + 3 * v * u * u * p2.0 + u * u * u * p3.0, v * v * v * p0.1 + 3 * v * v * u * p1.1 + 3 * v * u * u * p2.1 + u * u * u * p3.1)
        }
    }

    static func quad(_ p0: (Double, Double), _ c: (Double, Double), _ p1: (Double, Double), _ n: Int) -> [(Double, Double)] {
        (1...n).map { i in
            let u = Double(i) / Double(n)
            let v = 1 - u
            return (v * v * p0.0 + 2 * v * u * c.0 + u * u * p1.0, v * v * p0.1 + 2 * v * u * c.1 + u * u * p1.1)
        }
    }

    static func handlePath() -> (poly: [(Double, Double)], end: (Double, Double)) {
        let cl = bez((13.0, -0.6), (17.0, -10.0), (24.5, -24.0), (32.5, -38.0), 24)
        var l: [(Double, Double)] = []
        var r: [(Double, Double)] = []
        for (i, (x, y)) in cl.enumerated() {
            let a = cl[max(0, i - 1)]
            let b = cl[min(cl.count - 1, i + 1)]
            let dx = b.0 - a.0
            let dy = b.1 - a.1
            let d = hypot(dx, dy)
            let nx = -dy / d
            let ny = dx / d
            let s = Double(i) / Double(cl.count - 1)
            let hw = 1.75 + 1.75 * pow(s, 1.4)
            l.append((x + nx * hw, y + ny * hw))
            r.append((x - nx * hw, y - ny * hw))
        }
        return (l + r.reversed(), cl[cl.count - 1])
    }

    static func pose(_ t: Double) -> ScoopPose {
        let x = keys(t, [(0, 36), (1.3, 36), (1.75, 93), (2.12, 93), (2.6, 36)])
        var y = keys(t, [(0, 54), (0.4, 54), (0.5, 49), (0.7, 87), (0.85, 85.5), (1.13, 52), (1.2, 48), (1.32, 53), (1.52, 50), (1.75, 70), (2.12, 70), (2.36, 50), (2.6, 54)])
        y += 1.0 * sin(2 * .pi * t / 1.7) * (1 - clamp((t - 1.25) / 0.1) + clamp((t - 2.6) / 0.2))
        let a = keys(t, [(0, 0), (0.4, 0), (0.5, -7), (0.66, 15), (0.82, -9), (0.98, 0), (1.17, 0), (1.24, 5), (1.33, -1), (1.45, -4), (1.7, -26), (1.78, -22), (1.86, -35), (2.04, -37), (2.14, -30), (2.4, -4), (2.54, 6), (2.66, -2), (2.8, 0)])
        let sy = keys(t, [(0, 1), (0.4, 1), (0.5, 1.08), (0.6, 0.92), (0.72, 1.06), (0.85, 1), (0.95, 1.06), (1.13, 1.04), (1.2, 0.88), (1.3, 1.05), (1.4, 1), (1.74, 1), (1.8, 0.92), (1.9, 1.03), (2.0, 1), (2.14, 1), (2.22, 0.92), (2.32, 1.04), (2.42, 1)])
        return (x, y, a, 1 / sqrt(sy), sy)
    }

    static func bowlPose(_ t: Double) -> ScoopPose {
        if t < 2.68 {
            let x = keys(t, [(0, bx), (2.25, bx), (2.35, bx - 3), (2.66, 145)])
            let r = keys(t, [(0, 0), (2.25, 0), (2.35, 5), (2.46, -7), (2.66, -4)])
            let sy = keys(t, [(0, 1), (1.9, 1), (1.97, 0.93), (2.06, 1.04), (2.15, 1), (2.25, 1), (2.33, 1.07), (2.42, 0.95), (2.52, 1)])
            return (x, by, r, 1 / sqrt(sy), sy)
        }
        let u = clamp((t - 2.74) / 0.2)
        let y = -30 + (by + 30) * u * u
        let st = t < land ? 1 + 0.25 * u : keys(t, [(land, 1.25), (land + 0.04, 0.66), (land + 0.13, 1.12), (land + 0.21, 0.94), (land + 0.29, 1.03), (land + 0.37, 1)])
        return (bx, y, 0, 1 / sqrt(st), st)
    }

    static func tw(_ p: (Double, Double), _ ps: ScoopPose) -> (Double, Double) {
        let ca = cos(ps.a * .pi / 180)
        let sa = sin(ps.a * .pi / 180)
        let px = p.0 * ps.sx
        let py = p.1 * ps.sy
        return (ps.x + px * ca - py * sa, ps.y + px * sa + py * ca)
    }

    static func bw(_ p: (Double, Double), _ bp: ScoopPose) -> (Double, Double) { tw((p.0, p.1 - 19.5), bp) }

    static func area(_ poly: [(Double, Double)]) -> Double {
        var s = 0.0
        for (a, b) in zip(poly, poly.dropFirst() + [poly[0]]) { s += a.0 * b.1 - b.0 * a.1 }
        return abs(s) / 2
    }

    static func clipy(_ poly: [(Double, Double)], _ level: Double) -> [(Double, Double)] {
        var out: [(Double, Double)] = []
        for (p, q) in zip(poly, poly.dropFirst() + [poly[0]]) {
            let pin = p.1 >= level
            let qin = q.1 >= level
            if pin { out.append(p) }
            if pin != qin {
                let u = (level - p.1) / (q.1 - p.1)
                out.append((p.0 + u * (q.0 - p.0), level))
            }
        }
        return out
    }

    static func levelFor(_ poly: [(Double, Double)], _ vol: Double) -> Double {
        var lo = poly.map { $0.1 }.min() ?? 0
        var hi = poly.map { $0.1 }.max() ?? 0
        for _ in 0..<26 {
            let m = (lo + hi) / 2
            if area(clipy(poly, m)) > vol { lo = m } else { hi = m }
        }
        return (lo + hi) / 2
    }

    static func capacity(_ poly: [(Double, Double)]) -> Double {
        let rim = max(poly[0].1, poly[poly.count - 1].1)
        return area(clipy(poly, rim))
    }

    static func neckTop(_ ps: ScoopPose) -> (Double, Double) { tw((0, 12.4), ps) }

    static func flux(_ t: Double) -> Double { sin(.pi * clamp((t - 1.74) / 0.3)) }

    static func simulate() -> [ScoopState] {
        let n = Int(total / dt)
        var emitArea = 0.0
        for step in 0..<n {
            let t = Double(step) * dt
            let f = flux(t)
            if f > 0.05 && step % 2 == 0 {
                let r = 0.8 + 2.2 * pow(f, 0.6)
                emitArea += .pi * r * r
            }
        }
        let scale = bfull / emitArea
        var out = [ScoopState?](repeating: nil, count: count)
        var parts: [ScoopParticle] = []
        var ripples: [ScoopRipple] = []
        var vol = 0.0
        var bvol = 0.0
        var prevSub = false
        var blev = 0.0
        for loop in 0..<2 {
            for step in 0..<n {
                let t = Double(step) * dt
                let tg = t + Double(loop) * total
                let ps = pose(t)
                let bp = bowlPose(t)
                if t >= 2.68 && t - dt < 2.68 { bvol = 0 }
                let sub = neckTop(ps).1 > pw + 2
                if sub != prevSub { ripples.append(ScoopRipple(t0: tg, x: ps.x, amp: sub ? 3.0 : 2.0)) }
                prevSub = sub
                let poly = inner.map { tw($0, ps) }
                if tw((0, 5), ps).1 > pw { vol = full * 0.97 }
                if t > 1.6 { vol = full * 0.97 * (1 - ease((t - 1.74) / 0.28)) }
                if t < 0.45 { vol = 0 }
                let f = flux(t)
                if f > 0.05 && step % 2 == 0 {
                    let lip = poly[0].1 > poly[poly.count - 1].1 ? poly[0] : poly[poly.count - 1]
                    parts.append(ScoopParticle(x: lip.0 - 0.8, y: lip.1 + 0.5, vx: -8.0 * f, vy: 95, r: 0.8 + 2.2 * pow(f, 0.6), kind: 115, sink: false))
                }
                if t >= ts && t - dt < ts {
                    let top = neckTop(ps)
                    parts.append(ScoopParticle(x: top.0, y: top.1 + 0.42 * (pw - top.1), vx: 0, vy: -10, r: 3.0, kind: 100, sink: false))
                }
                if step % 4 == 0 {
                    let bpoly = binner.map { bw($0, bp) }
                    blev = bvol > 2 ? levelFor(bpoly, bvol) : (bpoly.map { $0.1 }.max() ?? 0) - 1
                }
                var nxt: [ScoopParticle] = []
                for var p in parts {
                    if p.sink {
                        p.vy *= exp(-dt / 0.05)
                        p.vx *= exp(-dt / 0.05)
                        p.x += p.vx * dt
                        p.y += p.vy * dt
                        p.r *= exp(-dt / (p.kind == 115 ? 0.035 : 0.07))
                        if p.r > 0.3 { nxt.append(p) }
                        continue
                    }
                    p.vy += gravity * dt
                    p.x += p.vx * dt
                    p.y += p.vy * dt
                    let inpot = px0 - 2 < p.x && p.x < px1 + 2
                    if inpot && p.y >= pw - 0.5 && p.vy > 0 {
                        p.sink = true
                        if p.kind == 100 {
                            ripples.append(ScoopRipple(t0: tg, x: p.x, amp: 1.4))
                            nxt.append(ScoopParticle(x: p.x - 1, y: pw - 2, vx: -26, vy: -120, r: 1.7, kind: 120, sink: false))
                            nxt.append(ScoopParticle(x: p.x + 1, y: pw - 2, vx: 24, vy: -105, r: 1.6, kind: 120, sink: false))
                        } else if p.kind == 120 {
                            ripples.append(ScoopRipple(t0: tg, x: p.x, amp: 0.35))
                        }
                    } else if !inpot && p.kind == 115 && p.y >= blev - 0.5 && p.vy > 0 {
                        p.sink = true
                        bvol += .pi * p.r * p.r * scale
                    }
                    nxt.append(p)
                }
                parts = nxt
                ripples = ripples.filter { tg - $0.t0 < 1.7 }
                if loop == 1 && step % 20 == 0 && step / 20 < count {
                    out[step / 20] = ScoopState(t: t, vol: vol, bvol: bvol, parts: parts, rips: ripples, tg: tg)
                }
            }
        }
        return out.compactMap { $0 }
    }

    static func surface(_ x: Double, _ rips: [ScoopRipple], _ ps: ScoopPose, _ tg: Double) -> Double {
        var y = pw
        for r in rips {
            let d0 = tg - r.t0
            if d0 <= 0 { continue }
            let fade = 1 - ease((d0 - 1.1) / 0.5)
            for xs in [r.x, 2 * px0 - r.x, 2 * px1 - r.x] {
                let d = abs(x - xs)
                let front = 45 * d0
                let env = exp(-d0 / 0.45) * fade
                y -= r.amp * env * cos(0.6 * (d - front)) * exp(-pow((d - front) / 8, 2)) * (xs == r.x ? 1 : 0.6)
            }
            y -= r.amp * 0.8 * exp(-d0 / 0.22) * cos(20 * d0) * exp(-pow((x - r.x) / 5, 2))
        }
        let sub = clamp((tw((0, 5), ps).1 - pw + 6) / 10)
        y -= 2.0 * sub * exp(-pow((x - ps.x) / 13, 2))
        return y
    }

    static func neck(_ t: Double, _ ps: ScoopPose, _ sy: Double) -> [ScoopItem] {
        var g: [ScoopItem] = []
        let top = neckTop(ps)
        if t < 0.8 || t > ts + 0.22 { return g }
        let len = sy - top.1
        if len < 1 { return g }
        let sd = 0.42
        let grow = clamp((t - 0.85) / 0.25)
        let rm = 2.3 - 1.5 * clamp((len - 8) / 26)
        if t < ts {
            let n = Int(len) + 1
            for i in 0...n {
                let s = Double(i) / Double(n)
                let w = pow(sin(.pi * s), 0.7)
                let r = 3.0 - (3.0 - rm) * w
                let y = top.1 + s * len
                let sway = 0.6 * sin(9 * t) * w
                g.append(.circle(top.0 + sway, y, r))
            }
            g.append(.circle(top.0, top.1 + sd * len, 3.0 * (0.5 + 0.5 * grow)))
        } else {
            let u = ease((t - ts) / 0.12)
            let lu = sd * len * (1 - u) * 0.6
            let n = Int(lu) + 1
            for i in 0...n {
                let y = top.1 + lu * Double(i) / Double(n)
                g.append(.circle(top.0, y, 2.7 - 1.3 * (Double(i) / Double(n))))
            }
            let v = ease((t - ts) / 0.18)
            let ytop = top.1 + sd * len + 5 + (sy - top.1 - sd * len - 5) * v
            let n2 = Int(max(0, sy - ytop)) + 1
            for i in 0...n2 {
                let y = ytop + (sy - ytop) * Double(i) / Double(n2)
                g.append(.circle(top.0, y, (1.5 + 1.7 * Double(i) / Double(n2)) * (1 - 0.5 * v)))
            }
        }
        return g
    }

    static func affine(_ ps: ScoopPose, lift: Double) -> CGAffineTransform {
        CGAffineTransform(translationX: 0, y: lift)
            .concatenating(CGAffineTransform(scaleX: ps.sx, y: ps.sy))
            .concatenating(CGAffineTransform(rotationAngle: ps.a * .pi / 180))
            .concatenating(CGAffineTransform(translationX: ps.x, y: ps.y))
    }

    static func points(_ pts: [(Double, Double)], _ m: CGAffineTransform) -> [CGPoint] {
        pts.map { CGPoint(x: $0.0, y: $0.1).applying(m) }
    }

    static func add(_ path: CGMutablePath, _ pts: [CGPoint]) {
        guard pts.count > 2 else { return }
        var s = 0.0
        for (a, b) in zip(pts, pts.dropFirst() + [pts[0]]) { s += Double(a.x * b.y - b.x * a.y) }
        path.addLines(between: s < 0 ? pts.reversed() : pts)
        path.closeSubpath()
    }

    static func disc(_ x: Double, _ y: Double, _ r: Double) -> [CGPoint] {
        (0..<24).map { i in
            let a = Double(i) / 24 * 2 * .pi
            return CGPoint(x: x + r * cos(a), y: y + r * sin(a))
        }
    }

    static func roundRect(_ x: Double, _ y: Double, _ w: Double, _ h: Double, _ r: Double) -> [(Double, Double)] {
        var out: [(Double, Double)] = []
        let corners: [(Double, Double, Double)] = [(x + w - r, y + r, -90), (x + w - r, y + h - r, 0), (x + r, y + h - r, 90), (x + r, y + r, 180)]
        for (cx, cy, start) in corners {
            for i in 0...6 {
                let a = (start + 90 * Double(i) / 6) * .pi / 180
                out.append((cx + r * cos(a), cy + r * sin(a)))
            }
        }
        return out
    }

    static let potBack: [(Double, Double)] = {
        var pts: [(Double, Double)] = [(14, 66), (14, 97)]
        pts += quad((14, 97), (14, 106), (23, 106), 8)
        pts.append((49, 106))
        pts += quad((49, 106), (58, 106), (58, 97), 8)
        pts.append((58, 66))
        return pts
    }()

    nonisolated(unsafe) static let potFrontLine: CGPath = {
        let path = CGMutablePath()
        path.move(to: CGPoint(x: 14, y: 67))
        path.addLine(to: CGPoint(x: 14, y: 97))
        path.addQuadCurve(to: CGPoint(x: 23, y: 106), control: CGPoint(x: 14, y: 106))
        path.addLine(to: CGPoint(x: 49, y: 106))
        path.addQuadCurve(to: CGPoint(x: 58, y: 97), control: CGPoint(x: 58, y: 106))
        path.addLine(to: CGPoint(x: 58, y: 67))
        return path
    }()

    static func build(_ s: ScoopState) -> ScoopFrame {
        let t = s.t
        let ps = pose(t)
        let bp = bowlPose(t)
        let poly = inner.map { tw($0, ps) }
        var goo: [ScoopItem] = []
        let vd = min(s.vol, capacity(poly))
        if vd > 2 {
            let cl = clipy(poly, levelFor(poly, vd))
            if cl.count > 2 { goo.append(.polygon(cl.map { CGPoint(x: $0.0, y: $0.1) })) }
        }
        let bpoly = binner.map { bw($0, bp) }
        if s.bvol > 2 {
            let cl = clipy(bpoly, levelFor(bpoly, s.bvol))
            if cl.count > 2 { goo.append(.polygon(cl.map { CGPoint(x: $0.0, y: $0.1) })) }
        }
        let xs = (0...40).map { px0 + (px1 - px0) * Double($0) / 40 }
        let surf = xs.map { ($0, surface($0, s.rips, ps, s.tg)) }
        var pool: [CGPoint] = [CGPoint(x: 14, y: 97), CGPoint(x: 14, y: surf[0].1)]
        pool += surf.map { CGPoint(x: $0.0, y: $0.1) }
        pool.append(CGPoint(x: 58, y: surf[surf.count - 1].1))
        pool.append(CGPoint(x: 58, y: 97))
        pool += quad((58, 97), (58, 106), (49, 106), 8).map { CGPoint(x: $0.0, y: $0.1) }
        pool += quad((23, 106), (14, 106), (14, 97), 8).map { CGPoint(x: $0.0, y: $0.1) }
        pool.insert(CGPoint(x: 23, y: 106), at: pool.count - 8)
        goo.append(.polygon(pool))
        let top = neckTop(ps)
        let sy = surface(top.0, s.rips, ps, s.tg)
        goo += neck(t, ps, sy)
        for p in s.parts where p.r > 0.2 { goo.append(.circle(p.x, p.y, p.r)) }

        let ladleM = affine(ps, lift: 0)
        let bowlM = affine(bp, lift: -19.5)
        let tint = CGMutablePath()
        add(tint, potBack.map { CGPoint(x: $0.0, y: $0.1) })
        add(tint, points(bez((-17, 0), (-17, 21), (17, 21), (17, 0), 24), bowlM))
        add(tint, points(bez((-13, 0), (-13, 17), (13, 17), (13, 0), 24), ladleM))

        let ink = CGMutablePath()
        add(ink, points(handle.poly, ladleM))
        let ring = (0..<24).map { i -> (Double, Double) in
            let a = Double(i) / 24 * 2 * .pi
            return (handle.end.0 + handleRadius * cos(a), handle.end.1 + handleRadius * sin(a))
        }
        add(ink, points(ring, ladleM))
        add(ink, points(roundRect(-8, 15, 16, 4.5, 2.25), bowlM))
        add(ink, points(roundRect(9, 64, 11, 5, 2.5), .identity))
        add(ink, points(roundRect(52, 64, 11, 5, 2.5), .identity))
        let u = (t - land) / 0.32
        if u > 0 && u < 1 {
            let e = 1 - pow(1 - u, 3)
            for side in [-1.0, 1.0] {
                let x = bx + side * (17 + (side < 0 ? 5.0 : 9.0) * e)
                let r1 = 2.8 * min(1, u / 0.15) * (1 - ease((u - 0.4) / 0.6))
                let r2 = 1.8 * min(1, u / 0.15) * (1 - ease((u - 0.3) / 0.6))
                if r1 > 0.2 { add(ink, disc(x, by - 1.5 - 2.5 * e, r1)) }
                if r2 > 0.2 { add(ink, disc(x - side * 5 * e, by - 0.5 - 0.8 * e, r2)) }
            }
        }

        let ladleLine = CGMutablePath()
        ladleLine.move(to: CGPoint(x: -13, y: 0))
        ladleLine.addCurve(to: CGPoint(x: 13, y: 0), control1: CGPoint(x: -13, y: 17), control2: CGPoint(x: 13, y: 17))
        ladleLine.closeSubpath()
        let bowlLine = CGMutablePath()
        bowlLine.move(to: CGPoint(x: -17, y: 0))
        bowlLine.addCurve(to: CGPoint(x: 17, y: 0), control1: CGPoint(x: -17, y: 21), control2: CGPoint(x: 17, y: 21))
        var lm = ladleM
        var bm = bowlM
        return ScoopFrame(tint: tint, goo: contour(goo, 2.0), ink: ink, ladleLine: ladleLine.copy(using: &lm) ?? ladleLine, bowlLine: bowlLine.copy(using: &bm) ?? bowlLine)
    }

    static func blur(_ field: inout [Float], _ w: Int, _ h: Int, _ radius: Int) {
        let inv = 1 / Float(2 * radius + 1)
        var cum = [Float](repeating: 0, count: max(w, h) + 1)
        for _ in 0..<3 {
            for y in 0..<h {
                let base = y * w
                for x in 0..<w { cum[x + 1] = cum[x] + field[base + x] }
                for x in 0..<w { field[base + x] = (cum[min(x + radius + 1, w)] - cum[max(x - radius, 0)]) * inv }
            }
            for x in 0..<w {
                for y in 0..<h { cum[y + 1] = cum[y] + field[y * w + x] }
                for y in 0..<h { field[y * w + x] = (cum[min(y + radius + 1, h)] - cum[max(y - radius, 0)]) * inv }
            }
        }
    }

    static func contour(_ items: [ScoopItem], _ sigma: Double) -> CGPath {
        let path = CGMutablePath()
        guard !items.isEmpty else { return path }
        let res = 2.0
        var minX = Double.infinity
        var minY = Double.infinity
        var maxX = -Double.infinity
        var maxY = -Double.infinity
        func grow(_ x: Double, _ y: Double, _ r: Double) {
            minX = min(minX, x - r)
            maxX = max(maxX, x + r)
            minY = min(minY, y - r)
            maxY = max(maxY, y + r)
        }
        for item in items {
            switch item {
            case let .circle(x, y, r): grow(x, y, r)
            case let .polygon(ps): ps.forEach { grow(Double($0.x), Double($0.y), 0) }
            }
        }
        let pad = sigma * 3.5 + 1
        let x0 = max(minX - pad, -14)
        let y0 = max(minY - pad, -34)
        let x1 = min(maxX + pad, 134)
        let y1 = min(maxY + pad, 130)
        guard x1 > x0, y1 > y0 else { return path }
        let w = Int(ceil((x1 - x0) * res)) + 2
        let h = Int(ceil((y1 - y0) * res)) + 2
        guard let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { return path }
        ctx.translateBy(x: 0, y: CGFloat(h))
        ctx.scaleBy(x: 1, y: -1)
        ctx.scaleBy(x: res, y: res)
        ctx.translateBy(x: -x0, y: -y0)
        ctx.setFillColor(gray: 1, alpha: 1)
        ctx.setStrokeColor(gray: 1, alpha: 1)
        for item in items {
            switch item {
            case let .circle(x, y, r):
                ctx.fillEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r))
            case let .polygon(ps):
                ctx.addLines(between: ps)
                ctx.closePath()
                ctx.fillPath()
            }
        }
        guard let data = ctx.data?.assumingMemoryBound(to: UInt8.self) else { return path }
        var field = (0..<(w * h)).map { Float(data[$0]) / 255 }
        let box = max(1, Int((sqrt(4 * sigma * res * sigma * res + 1) - 1) / 2 + 0.5))
        blur(&field, w, h, box)
        for x in 0..<w {
            field[x] = 0
            field[(h - 1) * w + x] = 0
        }
        for y in 0..<h {
            field[y * w] = 0
            field[y * w + w - 1] = 0
        }
        let level: Float = 0.45
        var links: [Int: [Int]] = [:]
        func link(_ a: Int, _ b: Int) {
            links[a, default: []].append(b)
            links[b, default: []].append(a)
        }
        for r in 0..<(h - 1) {
            for c in 0..<(w - 1) {
                let tl = field[r * w + c]
                let tr = field[r * w + c + 1]
                let br = field[(r + 1) * w + c + 1]
                let bl = field[(r + 1) * w + c]
                let index = (tl > level ? 1 : 0) | (tr > level ? 2 : 0) | (br > level ? 4 : 0) | (bl > level ? 8 : 0)
                if index == 0 || index == 15 { continue }
                let cell = (r * w + c) * 2
                let top = cell
                let bottom = ((r + 1) * w + c) * 2
                let leftEdge = cell + 1
                let rightEdge = (r * w + c + 1) * 2 + 1
                let centre = (tl + tr + br + bl) / 4 > level
                switch index {
                case 1, 14: link(leftEdge, top)
                case 2, 13: link(top, rightEdge)
                case 3, 12: link(leftEdge, rightEdge)
                case 4, 11: link(rightEdge, bottom)
                case 6, 9: link(top, bottom)
                case 7, 8: link(leftEdge, bottom)
                case 5:
                    if centre { link(top, rightEdge); link(leftEdge, bottom) } else { link(leftEdge, top); link(rightEdge, bottom) }
                default:
                    if centre { link(leftEdge, top); link(rightEdge, bottom) } else { link(top, rightEdge); link(leftEdge, bottom) }
                }
            }
        }
        func point(_ id: Int) -> CGPoint {
            let cell = id / 2
            let c = cell % w
            let r = cell / w
            var px = Double(c)
            var py = Double(r)
            if id % 2 == 0 {
                let f0 = field[r * w + c]
                let f1 = field[r * w + c + 1]
                px += Double((level - f0) / (f1 - f0))
            } else {
                let f0 = field[r * w + c]
                let f1 = field[(r + 1) * w + c]
                py += Double((level - f0) / (f1 - f0))
            }
            return CGPoint(x: x0 + (px + 0.5) / res, y: y0 + (py + 0.5) / res)
        }
        var seen = Set<Int>()
        for start in links.keys.sorted() where !seen.contains(start) {
            var loop: [CGPoint] = []
            var current = start
            var previous = -1
            while true {
                loop.append(point(current))
                seen.insert(current)
                guard let next = links[current]?.first(where: { $0 != previous && !seen.contains($0) }) else { break }
                previous = current
                current = next
            }
            if loop.count > 2 {
                path.addLines(between: loop)
                path.closeSubpath()
            }
        }
        return path
    }

}

extension FlairLayer {
    func buildScoop() {
        let unit = side
        let k = unit / 110
        let frames = ScoopModel.frames
        let duration = ScoopModel.duration
        let steps = frames.count
        var map = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: -5 * k, ty: unit + 5 * k)
        func placed(_ path: CGPath) -> CGPath { path.copy(using: &map) ?? path }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
        func paths(_ layer: CAShapeLayer, _ pick: (ScoopFrame) -> CGPath) {
            layer.path = placed(pick(frames[0]))
            guard animating else { return }
            let animation = keyframes("path", frames.map { placed(pick($0)) }, times: times, timing: .linear)
            animation.calculationMode = .discrete
            run(group([animation], duration: duration), on: layer)
        }
        let clipper = container()
        let tile = CAShapeLayer()
        tile.bounds = CGRect(origin: .zero, size: full)
        tile.position = mid
        tile.path = CGPath(roundedRect: CGRect(origin: .zero, size: full), cornerWidth: 22 * k, cornerHeight: 22 * k, transform: nil)
        tile.fillColor = CGColor(gray: 0, alpha: 1)
        clipper.mask = tile

        let tint = shape(placed(frames[0].tint), size: full, at: mid, in: clipper)
        tint.opacity = 0.22
        paths(tint) { $0.tint }
        let goo = shape(placed(frames[0].goo), size: full, at: mid, in: clipper)
        goo.fillRule = .evenOdd
        paths(goo) { $0.goo }
        let ink = shape(placed(frames[0].ink), size: full, at: mid, in: clipper)
        paths(ink) { $0.ink }
        let potLine = shape(placed(ScoopModel.potFrontLine), size: full, at: mid, stroke: 4 * k, in: clipper)
        potLine.lineCap = .round
        potLine.lineJoin = .round
        let ladleLine = shape(placed(frames[0].ladleLine), size: full, at: mid, stroke: 3.5 * k, in: clipper)
        ladleLine.lineJoin = .round
        paths(ladleLine) { $0.ladleLine }
        let bowlLine = shape(placed(frames[0].bowlLine), size: full, at: mid, stroke: 3.5 * k, in: clipper)
        bowlLine.lineCap = .round
        paths(bowlLine) { $0.bowlLine }
    }
}
