import QuartzCore
import Foundation

private struct VanFrame {
    let bodyT: CGAffineTransform
    let doorT: CGAffineTransform
    let door: CGPath
    let doorKnob: CGPath
    let wheelA: CGAffineTransform
    let wheelB: CGAffineTransform
    let fx: CGPath
    let parcelT: CGAffineTransform
    let hiddenMask: CGPath
    let bodyMask: CGPath
    let doorMask: CGPath
}

private enum VanModel {
    static let fps = 60.0
    static let duration = 3.3
    static let count = Int((duration * fps).rounded())
    static let gy = 92.0
    static let s = 0.8
    static let xs = 73.5
    static let bs = 1.15
    static let wr = 7.8 / 0.8
    static let tb0 = 0.32
    static let tb1 = 0.82
    static let tgo = 2.1
    static let v0 = 170.0
    static let ago = 210.0
    static let tdo = 1.12
    static let tdc = 1.95
    static let tp = 1.24
    static let tpop = 2.95
    static let pw = 16.0
    static let ph = 14.0
    static let x0 = xs - v0 * tb0 - v0 * (tb1 - tb0) / 2
    static let sq: [(Double, Double)] = [(0, 0), (0.05, -0.22), (0.16, 0.1), (0.28, -0.04), (0.4, 0)]
    static let wheelData: [String] = [
        "M362.0 572.0 Q367.0 554.0 367.0 539.0 Q367.0 524.0 361.5 510.0 Q356.0 496.0 350.5 489.0 Q345.0 482.0 337.5 476.0 Q330.0 470.0 325.0 467.5 Q320.0 465.0 308.5 462.0 Q297.0 459.0 288.5 459.0 Q280.0 459.0 267.0 462.5 Q254.0 466.0 244.5 472.5 Q235.0 479.0 229.0 485.5 Q223.0 492.0 218.5 500.0 Q214.0 508.0 211.5 518.0 Q209.0 528.0 208.5 534.5 Q208.0 541.0 213.0 569.0",
        "M362.0 572.0 Q359.0 574.0 357.5 577.5 Q356.0 581.0 350.5 588.0 Q345.0 595.0 337.0 601.0 Q329.0 607.0 321.5 610.5 Q314.0 614.0 308.0 615.5 Q302.0 617.0 288.0 617.0 Q274.0 617.0 264.5 614.0 Q255.0 611.0 248.0 607.0 Q241.0 603.0 231.5 593.5 Q222.0 584.0 218.5 577.0 Q215.0 570.0 213.0 569.0",
        "M327.0 549.0 Q321.0 563.0 317.0 567.0 Q313.0 571.0 305.5 574.5 Q298.0 578.0 288.5 578.0 Q279.0 578.0 270.0 573.5 Q261.0 569.0 256.0 562.5 Q251.0 556.0 249.5 550.0 Q248.0 544.0 249.0 534.0 Q250.0 524.0 254.0 517.5 Q258.0 511.0 263.0 507.0 Q268.0 503.0 276.5 500.5 Q285.0 498.0 291.5 498.5 Q298.0 499.0 303.5 501.0 Q309.0 503.0 315.0 508.5 Q321.0 514.0 324.5 521.5 Q328.0 529.0 327.0 549.0",
        "M288.0 526.0 Q295.0 527.0 297.5 530.5 Q300.0 534.0 299.5 539.5 Q299.0 545.0 295.0 548.0 Q291.0 551.0 286.0 550.0 Q281.0 549.0 278.5 546.0 Q276.0 543.0 276.5 537.5 Q277.0 532.0 279.5 529.5 Q282.0 527.0 288.0 526.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 eout(_ u: Double) -> Double { 1 - pow(1 - clamp(u), 3) }
    static func back(_ u: Double) -> Double {
        let v = clamp(u) - 1
        return 1 + 2.7 * v * v * v + 1.7 * v * 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 vel(_ t: Double) -> Double {
        if t < tb0 { return v0 }
        if t < tb1 { return v0 * (1 - (t - tb0) / (tb1 - tb0)) }
        if t < tgo { return 0 }
        return ago * (t - tgo)
    }

    static func acc(_ t: Double) -> Double {
        if t >= tb0 && t < tb1 { return -v0 / (tb1 - tb0) }
        if t >= tgo { return ago }
        return 0
    }

    static func doorOpen(_ t: Double) -> Double {
        if t < tdo { return 0 }
        if t < tdc { return -105 * back((t - tdo) / 0.2) }
        return -105 * (1 - back((t - tdc) / 0.16))
    }

    static func rpoly(_ pts: [(Double, Double)], _ radii: [Double]) -> CGPath {
        let path = CGMutablePath()
        let n = pts.count
        for i in 0..<n {
            let p0 = pts[(i + n - 1) % n]
            let p1 = pts[i]
            let p2 = pts[(i + 1) % n]
            func toward(_ a: (Double, Double), _ b: (Double, Double), _ k: Double) -> CGPoint {
                let dx = b.0 - a.0
                let dy = b.1 - a.1
                let l = hypot(dx, dy)
                let m = min(k, l / 2)
                return CGPoint(x: a.0 + dx * m / l, y: a.1 + dy * m / l)
            }
            let q0 = toward(p1, p0, radii[i])
            let q1 = toward(p1, p2, radii[i])
            if i == 0 { path.move(to: q0) } else { path.addLine(to: q0) }
            path.addQuadCurve(to: q1, control: CGPoint(x: p1.0, y: p1.1))
        }
        path.closeSubpath()
        return path
    }

    static func rpoly(_ pts: [(Double, Double)], _ r: Double) -> CGPath {
        rpoly(pts, Array(repeating: r, count: pts.count))
    }

    nonisolated(unsafe) static let bodyPath = rpoly([(-39, -6), (-39, -54), (13, -54), (13, -36), (27, -36), (40, -20), (40, -6)], [5, 8, 8, 3, 7, 6, 5])
    nonisolated(unsafe) static let windowPath = rpoly([(17, -31), (25.5, -31), (32.5, -21), (17, -21)], [3, 4, 3, 3])
    nonisolated(unsafe) static let boxPath = rpoly([(-27, -40), (-5, -40), (-5, -20), (-27, -20)], 5)

    static func parcelPath() -> CGPath {
        rpoly([(-pw / 2, -ph), (pw / 2, -ph), (pw / 2, 0), (-pw / 2, 0)], 3)
    }

    static func doorPaths(_ op: Double) -> (CGPath, CGPath) {
        if op <= 0.01 { return (CGMutablePath(), CGMutablePath()) }
        let d = rpoly([(-39, -52), (-39 - 15 * op, -50), (-39 - 15 * op, -10), (-39, -8)], [2, 3, 3, 2])
        let knob = CGMutablePath()
        knob.addEllipse(in: CGRect(x: -39 - 11 * op - 1.6, y: -31.6, width: 3.2, height: 3.2))
        return (d, knob)
    }

    static func rotated(_ deg: Double, _ cx: Double, _ cy: Double) -> CGAffineTransform {
        CGAffineTransform(translationX: cx, y: cy).rotated(by: deg * .pi / 180).translatedBy(x: -cx, y: -cy)
    }

    static func chain(_ list: [CGAffineTransform]) -> CGAffineTransform {
        var m = CGAffineTransform.identity
        for t in list.reversed() { m = m.concatenating(t) }
        return m
    }

    static func blob(_ x: Double, _ y: Double, _ r: Double, _ path: CGMutablePath) {
        if r > 0.05 { path.addEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r)) }
    }

    static func life(_ t: Double, _ t0: Double, _ dur: Double, _ rmax: Double) -> Double {
        let u = (t - t0) / dur
        if u <= 0 || u >= 1 { return 0 }
        return rmax * pow(sin(.pi * pow(u, 0.6)), 1.2)
    }

    static func dust(_ t: Double, _ t0: Double, _ ex: Double, _ ey: Double, _ side: Double, _ big: Double, _ path: CGMutablePath) {
        for (dx, dy, r, d0, dur) in [(9.0, -1.0, 3.6, 0.0, 0.38), (4.0, -8.0, 2.6, 0.03, 0.32), (13.0, -7.0, 2.0, 0.06, 0.28)] {
            let uu = eout((t - t0 - d0) / dur)
            blob(ex + side * dx * uu * big, ey - 2.5 + dy * uu * big, life(t, t0 + d0, dur, r * big), path)
        }
    }

    static func puffs(_ t: Double, _ x: Double, _ path: CGMutablePath) {
        for k in 0..<6 {
            let t0 = tgo - 0.05 + Double(k) * 0.1
            let u = (t - t0) / 0.55
            if u <= 0 || u >= 1 { continue }
            let bx = x + s * -41 * bs
            let by = gy - s * 7
            let r = 2.8 * back(u / 0.3) * (1 - ease((u - 0.35) / 0.65)) * (0.85 + 0.25 * Double(k % 2))
            blob(bx - 22 * u, by - 7 * u, r, path)
        }
    }

    struct Parcel {
        let x: Double
        let y: Double
        let landed: [Double]
    }

    static let parcels: [Int: Parcel] = {
        var out: [Int: Parcel] = [:]
        var x = xs + s * -36 * bs
        var y = gy + s * (-6 - 8 * bs)
        var vx = -36.0
        var vy = -90.0
        var g = 560.0
        var landed: [Double] = []
        let dt = 1.0 / 1200
        var n = 0
        while true {
            let t = tp + Double(n) * dt
            if t >= duration + 0.01 { break }
            vy += g * dt
            x += vx * dt
            y += vy * dt
            if y > gy {
                y = gy
                landed.append(t)
                if abs(vy) > 40 {
                    vy = -abs(vy) * 0.32
                    vx *= 0.5
                } else {
                    vy = 0
                    vx = 0
                    g = 0
                }
            }
            let f = t * fps
            if abs(f - f.rounded()) < dt * fps / 2 { out[Int(f.rounded())] = Parcel(x: x, y: y, landed: landed) }
            n += 1
        }
        return out
    }()

    static let sim: [(t: Double, x: Double, y: Double, vy: Double, a: Double, v: Double)] = {
        var out: [(t: Double, x: Double, y: Double, vy: Double, a: Double, v: Double)] = []
        let dt = 1.0 / 1200
        var x = x0
        var y = 0.0
        var vy = 0.0
        var a = 0.0
        var va = 0.0
        let stride = Int((1200 / fps).rounded())
        let steps = Int((duration / dt).rounded())
        for loop in 0..<2 {
            x = x0
            for i in 0..<steps {
                let t = Double(i) * dt
                let v = vel(t)
                x += v * dt
                let mv = clamp(v / 60)
                let kick = (0 <= t - tp && t - tp < 0.03) ? -2.2 : 0.0
                let yt = mv * (0.5 * sin(2 * .pi * 7.3 * t) + 0.35 * sin(2 * .pi * 3.1 * t + 1))
                let at = max(-5, min(4, 0.011 * acc(t) * -1))
                vy += (520 * (yt - y) - 11 * vy) * dt + kick * 60 * dt
                y += vy * dt
                va += (260 * (at - a) - 9 * va) * dt
                a += va * dt
                if loop == 1 && i % stride == 0 && i / stride < count { out.append((t, x, y, vy, a, v)) }
            }
        }
        return out
    }()

    static let bt = chain([CGAffineTransform(translationX: 0, y: -6), CGAffineTransform(scaleX: bs, y: bs), CGAffineTransform(translationX: 0, y: 6)])

    static func wheelCenter(_ x: Double, _ lx: Double, _ hr: Double) -> CGPoint {
        CGPoint(x: x + s * lx * bs, y: gy + s * (-wr + hr))
    }

    static func wheelT(_ c: CGPoint, _ ang: Double) -> CGAffineTransform {
        chain([CGAffineTransform(translationX: c.x, y: c.y), CGAffineTransform(rotationAngle: ang * .pi / 180), CGAffineTransform(scaleX: 0.1, y: 0.1)])
    }

    nonisolated(unsafe) static let frames: [VanFrame] = (0..<count).map { build($0) }

    static func build(_ k: Int) -> VanFrame {
        let (t, x, y, vy, a, v) = sim[k]
        let ang = x / 7.8 * 180 / .pi
        let mv = clamp(v / 60)
        let hr = mv * 0.45 * sin(2 * .pi * 7.3 * t + 0.6)
        let hf = mv * 0.45 * sin(2 * .pi * 7.3 * t + 2.0)
        let sqz = max(-0.07, min(0.07, -0.06 * vy / 10))
        let sy = 1 + sqz
        let sx = 1 / sqrt(sy)
        let op = doorOpen(t) / -105
        let group = chain([CGAffineTransform(translationX: x, y: gy), CGAffineTransform(scaleX: s, y: s)])
        let sway = chain([
            CGAffineTransform(translationX: 0, y: y),
            rotated(a, 0, -8),
            CGAffineTransform(translationX: 0, y: -8),
            CGAffineTransform(scaleX: sx, y: sy),
            CGAffineTransform(translationX: 0, y: 8),
        ])
        let bodyT = chain([group, sway, bt])
        let doorT = chain([group, CGAffineTransform(translationX: 0, y: y), rotated(a, 0, -8), bt])
        let (door, knob) = doorPaths(op)
        let ca = wheelCenter(x, -23, hr)
        let cb = wheelCenter(x, 24, hf)
        let fx = CGMutablePath()
        if t >= tb1 - 0.06 && t < tb1 + 0.5 { dust(t, tb1 - 0.06, x + s * 24 * bs + s * 9, gy, 1, 0.8, fx) }
        puffs(t, x, fx)
        var parcelT = CGAffineTransform(scaleX: 0.0001, y: 0.0001)
        if t >= tp, let p = parcels[k] {
            var visible = true
            if p.landed.isEmpty {
                let u = (t - tp) / 0.3
                let rot = -18 * sin(.pi * clamp(u))
                parcelT = chain([CGAffineTransform(translationX: p.x, y: p.y), rotated(rot, 0, -ph / 2)])
            } else {
                let tl = p.landed[p.landed.count - 1]
                let q = keys(t - tl, sq) * (p.landed.count > 1 ? 1 : 0.6)
                let syy = 1 + q
                let sxx = q < 0 ? 1 - q : 1 / sqrt(syy)
                var so = 1.0
                if t >= tpop {
                    let u = (t - tpop) / 0.3
                    so = u < 0.35 ? 1 + 0.15 * sin(.pi * u / 0.35) : 1 - ease((u - 0.35) / 0.65)
                    if so <= 0.01 { visible = false }
                }
                if visible {
                    parcelT = chain([CGAffineTransform(translationX: p.x, y: p.y), CGAffineTransform(scaleX: sxx * so, y: syy * so)])
                    dust(t, p.landed[0], p.x - pw / 2, gy, -1, 0.9, fx)
                    dust(t, p.landed[0], p.x + pw / 2, gy, 1, 0.9, fx)
                }
            }
        }
        let big = CGRect(x: -60, y: -60, width: 240, height: 240)
        let discs = CGMutablePath()
        for c in [ca, cb] { discs.addEllipse(in: CGRect(x: c.x - 8.1, y: c.y - 8.1, width: 16.2, height: 16.2)) }
        var bodyMap = bodyT
        let silhouette = bodyPath.copy(using: &bodyMap) ?? bodyPath
        let hole = silhouette.union(discs)
        let hidden = CGMutablePath()
        hidden.addRect(big)
        hidden.addPath(hole)
        let bodyMask = CGMutablePath()
        bodyMask.addRect(big)
        bodyMask.addPath(discs)
        let doorMask = CGMutablePath()
        doorMask.addRect(big)
        if abs(parcelT.a) > 0.001 { doorMask.addPath(parcelPath(), transform: parcelT) }
        return VanFrame(bodyT: bodyT, doorT: doorT, door: door, doorKnob: knob, wheelA: wheelT(ca, ang), wheelB: wheelT(cb, ang), fx: fx, parcelT: parcelT, hiddenMask: hidden, bodyMask: bodyMask, doorMask: doorMask)
    }
}

extension FlairLayer {
    func buildVan() {
        let unit = side
        let k = unit / 110
        let frames = VanModel.frames
        let duration = VanModel.duration
        let steps = VanModel.count
        let flip = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: -5 * k, ty: unit + 5 * k)
        let unflip = flip.inverted()
        func screen(_ path: CGPath) -> CGPath {
            var m = flip
            return path.copy(using: &m) ?? path
        }
        func place(_ t: CGAffineTransform) -> CATransform3D {
            CATransform3DMakeAffineTransform(unflip.concatenating(t).concatenating(flip))
        }
        func lift(_ t: CGAffineTransform) -> NSValue { NSValue(caTransform3D: place(t)) }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        func holder(in parent: CALayer) -> CALayer {
            let layer = container()
            layer.removeFromSuperlayer()
            parent.addSublayer(layer)
            layer.bounds = CGRect(origin: .zero, size: full)
            layer.anchorPoint = .zero
            layer.position = .zero
            return layer
        }
        func maskLayer(_ path: CGPath) -> CAShapeLayer {
            let layer = CAShapeLayer()
            layer.bounds = CGRect(origin: .zero, size: full)
            layer.position = mid
            layer.path = path
            layer.fillRule = .evenOdd
            layer.fillColor = CGColor(gray: 0, alpha: 1)
            return layer
        }
        func discrete(_ values: [Any]) -> CAKeyframeAnimation {
            let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
            let animation = keyframes("path", values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }
        func xforms(_ pick: (VanFrame) -> CGAffineTransform) -> CAKeyframeAnimation {
            keyframes("transform", frames.map { lift(pick($0)) }, timing: .linear)
        }
        @discardableResult
        func piece(_ path: CGPath, in parent: CALayer, fill opacity: Float = 1, stroke width: Double = 0, cap: CAShapeLayerLineCap = .round) -> CAShapeLayer {
            let layer = shape(screen(path), size: full, at: mid, stroke: CGFloat(width * k), in: parent)
            layer.opacity = opacity
            layer.lineCap = cap
            layer.lineJoin = .round
            return 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 behind = holder(in: clipper)
        let hiddenMask = maskLayer(screen(frames[0].hiddenMask))
        behind.mask = hiddenMask

        let fx = piece(frames[0].fx, in: behind)

        let doorClip = holder(in: behind)
        let doorMask = maskLayer(screen(frames[0].doorMask))
        doorClip.mask = doorMask
        let doorHolder = holder(in: doorClip)
        let doorFill = piece(frames[0].door, in: doorHolder, fill: 0.3)
        let doorLine = piece(frames[0].door, in: doorHolder, stroke: 4)
        let doorKnob = piece(frames[0].doorKnob, in: doorHolder)

        let parcelHolder = holder(in: behind)
        parcelHolder.transform = place(CGAffineTransform(scaleX: 0.0001, y: 0.0001))
        let parcel = VanModel.parcelPath()
        piece(parcel, in: parcelHolder, fill: 0.3)
        piece(parcel, in: parcelHolder, stroke: 4)
        let tie = CGMutablePath()
        tie.move(to: CGPoint(x: 0, y: -VanModel.ph + 0.5))
        tie.addLine(to: CGPoint(x: 0, y: -VanModel.ph * 0.45))
        piece(tie, in: parcelHolder, stroke: 3)

        let bodyClip = holder(in: clipper)
        let bodyMask = maskLayer(screen(frames[0].bodyMask))
        bodyClip.mask = bodyMask
        let bodyHolder = holder(in: bodyClip)
        bodyHolder.transform = place(frames[0].bodyT)
        let boxOffset = CGAffineTransform(translationX: 3, y: -3.5)
        func inBox(_ path: CGPath) -> CGPath {
            var m = boxOffset
            return path.copy(using: &m) ?? path
        }
        let box = inBox(VanModel.boxPath)
        let bodyFill = CGMutablePath()
        bodyFill.addPath(VanModel.bodyPath)
        bodyFill.addPath(VanModel.windowPath)
        bodyFill.addPath(box)
        piece(bodyFill, in: bodyHolder, fill: 0.22).fillRule = .evenOdd
        piece(VanModel.bodyPath, in: bodyHolder, stroke: 4)
        piece(VanModel.windowPath, in: bodyHolder, fill: 0.55)
        let lines = CGMutablePath()
        lines.addPath(VanModel.windowPath)
        lines.move(to: CGPoint(x: 13, y: -34))
        lines.addLine(to: CGPoint(x: 13, y: -6))
        lines.addPath(box)
        lines.move(to: CGPoint(x: -13, y: -43.5))
        lines.addLine(to: CGPoint(x: -13, y: -38.5))
        piece(lines, in: bodyHolder, stroke: 3.2)
        let face = CGMutablePath()
        face.addPath(box)
        for ex in [-17.5, -8.5] { face.addEllipse(in: CGRect(x: ex - 1.9, y: -33.5 - 1.9, width: 3.8, height: 3.8)) }
        let smile = CGMutablePath()
        smile.move(to: CGPoint(x: -16, y: -29))
        smile.addQuadCurve(to: CGPoint(x: -10, y: -29), control: CGPoint(x: -13, y: -26))
        face.addPath(smile.copy(strokingWithWidth: 1.9, lineCap: .round, lineJoin: .round, miterLimit: 10))
        piece(face, in: bodyHolder, fill: 0.45).fillRule = .evenOdd
        let cheeks = CGMutablePath()
        for cx in [-21.0, -5.0] { cheeks.addEllipse(in: CGRect(x: cx - 2, y: -30 - 1.3, width: 4, height: 2.6)) }
        piece(cheeks, in: bodyHolder, fill: 0.5)
        let dashes = CGMutablePath()
        for dy in [-38.5, -31.5] {
            dashes.move(to: CGPoint(x: -33, y: dy))
            dashes.addLine(to: CGPoint(x: -28, y: dy))
        }
        piece(dashes, in: bodyHolder, fill: 0.6, stroke: 2.8)
        let lamp = CGMutablePath()
        lamp.addEllipse(in: CGRect(x: 37.5 - 2.2, y: -15 - 2.2, width: 4.4, height: 4.4))
        piece(lamp, in: bodyHolder)

        func wheelHolder() -> CALayer {
            let layer = holder(in: clipper)
            let disc = CGMutablePath()
            disc.addEllipse(in: CGRect(x: -78, y: -78, width: 156, height: 156))
            piece(disc, in: layer, fill: 0.22)
            let spokes = CGMutablePath()
            for d in VanModel.wheelData { spokes.addPath(Self.vanSegments(d, centre: CGPoint(x: 288, y: 538))) }
            piece(spokes, in: layer, stroke: 24)
            let bolts = CGMutablePath()
            for i in 0..<3 {
                let a = Double(i) * 120 * .pi / 180
                bolts.addEllipse(in: CGRect(x: 26 * cos(a) - 7, y: 26 * sin(a) - 7, width: 14, height: 14))
            }
            piece(bolts, in: layer)
            return layer
        }
        let wheelA = wheelHolder()
        let wheelB = wheelHolder()
        wheelA.transform = place(frames[0].wheelA)
        wheelB.transform = place(frames[0].wheelB)

        guard animating else { return }
        run(group([discrete(frames.map { screen($0.hiddenMask) })], duration: duration), on: hiddenMask)
        run(group([discrete(frames.map { screen($0.bodyMask) })], duration: duration), on: bodyMask)
        run(group([discrete(frames.map { screen($0.doorMask) })], duration: duration), on: doorMask)
        run(group([discrete(frames.map { screen($0.fx) })], duration: duration), on: fx)
        for layer in [doorFill, doorLine] { run(group([discrete(frames.map { screen($0.door) })], duration: duration), on: layer) }
        run(group([discrete(frames.map { screen($0.doorKnob) })], duration: duration), on: doorKnob)
        run(group([xforms { $0.doorT }], duration: duration), on: doorHolder)
        run(group([xforms { $0.parcelT }], duration: duration), on: parcelHolder)
        run(group([xforms { $0.bodyT }], duration: duration), on: bodyHolder)
        run(group([xforms { $0.wheelA }], duration: duration), on: wheelA)
        run(group([xforms { $0.wheelB }], duration: duration), on: wheelB)
    }

    fileprivate static func vanSegments(_ d: String, centre: CGPoint) -> CGPath {
        let path = CGMutablePath()
        let tokens = d.split(separator: " ").map(String.init)
        var numbers: [Double] = []
        var command = "M"
        func at(_ i: Int) -> CGPoint { CGPoint(x: numbers[i] - centre.x, y: numbers[i + 1] - centre.y) }
        func flush() {
            switch command {
            case "M" where numbers.count >= 2: path.move(to: at(0))
            case "L" where numbers.count >= 2: path.addLine(to: at(0))
            case "Q" where numbers.count >= 4: path.addQuadCurve(to: at(2), control: at(0))
            default: break
            }
            numbers = []
        }
        for token in tokens {
            var body = Substring(token)
            if let first = body.first, first.isLetter {
                flush()
                command = String(first)
                body = body.dropFirst()
            }
            if let value = Double(body) { numbers.append(value) }
        }
        flush()
        return path
    }
}
