SPB Git

Repository Public

VQSVGPath.swift 9.4 KB 178 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Support/VQSVGPath.swift3// Description: SVG path data ("d" attribute) → SwiftUI Path. Complete for the path grammar: M L H V C S Q T A Z,4//              absolute and relative, implicit repeats, compact numbers ("1.5.5", "1-2", "1e-3") and arc flags.5import SwiftUI67public enum VQSVGPath {8    /// Parses SVG path data. Unknown commands end the parse: what was read so far is returned.9    public static func path(_ d: String) -> Path {10        var p = Path()11        var s = Scanner(Array(d.utf8))12        var current = CGPoint.zero, start = CGPoint.zero13        var lastControl: CGPoint?       // of the previous C/S (for S) or Q/T (for T)14        var lastCommand: UInt8 = 015        var command: UInt8 = 01617        while true {18            s.skipSeparators()19            guard let c = s.peek() else { break }20            if isCommand(c) { command = c; s.advance() }21            else if command == 0 { break }22            else if command == UInt8(ascii: "M") { command = UInt8(ascii: "L") }          // implicit lineto after a moveto23            else if command == UInt8(ascii: "m") { command = UInt8(ascii: "l") }24            let relative = command >= 9725            func pt(_ x: CGFloat, _ y: CGFloat) -> CGPoint { relative ? CGPoint(x: current.x + x, y: current.y + y) : CGPoint(x: x, y: y) }2627            switch command | 0x20 {28            case UInt8(ascii: "m"):29                guard let x = s.number(), let y = s.number() else { return p }30                current = pt(x, y); start = current31                p.move(to: current)32                lastControl = nil33            case UInt8(ascii: "l"):34                guard let x = s.number(), let y = s.number() else { return p }35                current = pt(x, y); p.addLine(to: current); lastControl = nil36            case UInt8(ascii: "h"):37                guard let x = s.number() else { return p }38                current = CGPoint(x: relative ? current.x + x : x, y: current.y); p.addLine(to: current); lastControl = nil39            case UInt8(ascii: "v"):40                guard let y = s.number() else { return p }41                current = CGPoint(x: current.x, y: relative ? current.y + y : y); p.addLine(to: current); lastControl = nil42            case UInt8(ascii: "c"):43                guard let x1 = s.number(), let y1 = s.number(), let x2 = s.number(), let y2 = s.number(), let x = s.number(), let y = s.number() else { return p }44                let c1 = pt(x1, y1), c2 = pt(x2, y2), end = pt(x, y)45                p.addCurve(to: end, control1: c1, control2: c2)46                lastControl = c2; current = end47            case UInt8(ascii: "s"):48                guard let x2 = s.number(), let y2 = s.number(), let x = s.number(), let y = s.number() else { return p }49                let wasCubic = (lastCommand | 0x20) == UInt8(ascii: "c") || (lastCommand | 0x20) == UInt8(ascii: "s")50                let c1 = wasCubic ? reflect(lastControl ?? current, about: current) : current51                let c2 = pt(x2, y2), end = pt(x, y)52                p.addCurve(to: end, control1: c1, control2: c2)53                lastControl = c2; current = end54            case UInt8(ascii: "q"):55                guard let x1 = s.number(), let y1 = s.number(), let x = s.number(), let y = s.number() else { return p }56                let c1 = pt(x1, y1), end = pt(x, y)57                p.addQuadCurve(to: end, control: c1)58                lastControl = c1; current = end59            case UInt8(ascii: "t"):60                guard let x = s.number(), let y = s.number() else { return p }61                let wasQuad = (lastCommand | 0x20) == UInt8(ascii: "q") || (lastCommand | 0x20) == UInt8(ascii: "t")62                let c1 = wasQuad ? reflect(lastControl ?? current, about: current) : current63                let end = pt(x, y)64                p.addQuadCurve(to: end, control: c1)65                lastControl = c1; current = end66            case UInt8(ascii: "a"):67                guard let rx = s.number(), let ry = s.number(), let rotation = s.number(), let large = s.flag(), let sweep = s.flag(), let x = s.number(), let y = s.number() else { return p }68                let end = pt(x, y)69                addArc(&p, from: current, to: end, rx: rx, ry: ry, rotationDegrees: rotation, largeArc: large, sweep: sweep)70                current = end; lastControl = nil71            case UInt8(ascii: "z"):72                p.closeSubpath()73                current = start; lastControl = nil74            default:75                return p76            }77            lastCommand = command78        }79        return p80    }8182    private static func isCommand(_ c: UInt8) -> Bool {83        switch c | 0x20 {84        case UInt8(ascii: "m"), UInt8(ascii: "l"), UInt8(ascii: "h"), UInt8(ascii: "v"), UInt8(ascii: "c"), UInt8(ascii: "s"),85             UInt8(ascii: "q"), UInt8(ascii: "t"), UInt8(ascii: "a"), UInt8(ascii: "z"): return true86        default: return false87        }88    }8990    private static func reflect(_ p: CGPoint, about c: CGPoint) -> CGPoint { CGPoint(x: 2 * c.x - p.x, y: 2 * c.y - p.y) }9192    /// Endpoint arc → centre parameterisation → cubic Béziers (SVG 1.1 implementation notes F.6).93    private static func addArc(_ p: inout Path, from p0: CGPoint, to p1: CGPoint, rx rxIn: CGFloat, ry ryIn: CGFloat, rotationDegrees: CGFloat, largeArc: Bool, sweep: Bool) {94        var rx = abs(rxIn), ry = abs(ryIn)95        if p0 == p1 { return }96        if rx == 0 || ry == 0 { p.addLine(to: p1); return }97        let phi = rotationDegrees * .pi / 18098        let cosPhi = cos(phi), sinPhi = sin(phi)99        let dx = (p0.x - p1.x) / 2, dy = (p0.y - p1.y) / 2100        let x1 = cosPhi * dx + sinPhi * dy, y1 = -sinPhi * dx + cosPhi * dy101        let lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry)102        if lambda > 1 { rx *= sqrt(lambda); ry *= sqrt(lambda) }103        let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1104        let den = rx * rx * y1 * y1 + ry * ry * x1 * x1105        var coef = den == 0 ? 0 : sqrt(max(0, num / den))106        if largeArc == sweep { coef = -coef }107        let cxp = coef * rx * y1 / ry, cyp = -coef * ry * x1 / rx108        let cx = cosPhi * cxp - sinPhi * cyp + (p0.x + p1.x) / 2109        let cy = sinPhi * cxp + cosPhi * cyp + (p0.y + p1.y) / 2110        func angle(_ ux: CGFloat, _ uy: CGFloat, _ vx: CGFloat, _ vy: CGFloat) -> CGFloat {111            let dot = ux * vx + uy * vy, len = sqrt(ux * ux + uy * uy) * sqrt(vx * vx + vy * vy)112            var a = acos(min(1, max(-1, len == 0 ? 1 : dot / len)))113            if ux * vy - uy * vx < 0 { a = -a }114            return a115        }116        let theta1 = angle(1, 0, (x1 - cxp) / rx, (y1 - cyp) / ry)117        var delta = angle((x1 - cxp) / rx, (y1 - cyp) / ry, (-x1 - cxp) / rx, (-y1 - cyp) / ry)118        if !sweep && delta > 0 { delta -= 2 * .pi } else if sweep && delta < 0 { delta += 2 * .pi }119        let segments = max(1, Int(ceil(abs(delta) / (.pi / 2) - 1e-9)))120        let step = delta / CGFloat(segments)121        let k = 4 / 3 * tan(step / 4)122        func point(_ t: CGFloat) -> CGPoint {123            let x = rx * cos(t), y = ry * sin(t)124            return CGPoint(x: cosPhi * x - sinPhi * y + cx, y: sinPhi * x + cosPhi * y + cy)125        }126        func derivative(_ t: CGFloat) -> CGPoint {127            let x = -rx * sin(t), y = ry * cos(t)128            return CGPoint(x: cosPhi * x - sinPhi * y, y: sinPhi * x + cosPhi * y)129        }130        var t = theta1131        for _ in 0..<segments {132            let a = point(t), b = point(t + step), da = derivative(t), db = derivative(t + step)133            p.addCurve(to: b, control1: CGPoint(x: a.x + k * da.x, y: a.y + k * da.y), control2: CGPoint(x: b.x - k * db.x, y: b.y - k * db.y))134            t += step135        }136    }137138    private struct Scanner {139        let bytes: [UInt8]140        var i = 0141        init(_ bytes: [UInt8]) { self.bytes = bytes }142        func peek() -> UInt8? { i < bytes.count ? bytes[i] : nil }143        mutating func advance() { i += 1 }144        mutating func skipSeparators() {145            while i < bytes.count, bytes[i] == 32 || bytes[i] == 44 || bytes[i] == 9 || bytes[i] == 10 || bytes[i] == 13 { i += 1 }146        }147        /// A single 0/1 (arc flags may be glued to the next number: "0 01-.5").148        mutating func flag() -> Bool? {149            skipSeparators()150            guard i < bytes.count, bytes[i] == 48 || bytes[i] == 49 else { return nil }151            defer { i += 1 }152            return bytes[i] == 49153        }154        mutating func number() -> CGFloat? {155            skipSeparators()156            let begin = i157            if i < bytes.count, bytes[i] == 43 || bytes[i] == 45 { i += 1 }158            var digits = 0, dot = false159            while i < bytes.count {160                let c = bytes[i]161                if c >= 48 && c <= 57 { digits += 1; i += 1 }162                else if c == 46 && !dot { dot = true; i += 1 }163                else { break }164            }165            guard digits > 0 else { i = begin; return nil }166            if i < bytes.count, bytes[i] == 101 || bytes[i] == 69 {167                var j = i + 1168                if j < bytes.count, bytes[j] == 43 || bytes[j] == 45 { j += 1 }169                if j < bytes.count, bytes[j] >= 48, bytes[j] <= 57 {170                    while j < bytes.count, bytes[j] >= 48, bytes[j] <= 57 { j += 1 }171                    i = j172                }173            }174            return Double(String(decoding: bytes[begin..<i], as: UTF8.self)).map { CGFloat($0) }175        }176    }177}178
Files main
Menu

Theme