Repository navigation
Expand file tree
/
Copy pathCoreGraphicsPolyfill.swift
More file actions
612 lines (490 loc) · 21.8 KB
/
Copy pathCoreGraphicsPolyfill.swift
File metadata and controls
612 lines (490 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//
// CoreGraphicsPolyfills.swift
// SVGView
//
// Created by khoi on 10/5/25.
//
#if os(Linux) || os(WASI)
import Foundation
#elseif canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#if os(WASI)
import WASILibc
#elseif os(Linux) || os(Android)
import Glibc
#endif
#if os(Linux) || os(WASI)
public typealias CGFloat = Foundation.CGFloat
public typealias CGPoint = Foundation.CGPoint
public typealias CGSize = Foundation.CGSize
public typealias CGRect = Foundation.CGRect
#elseif !canImport(CoreGraphics)
public typealias CGFloat = Double
public struct CGPoint: Equatable {
public static let zero = CGPoint()
public var x: CGFloat
public var y: CGFloat
public init(x: CGFloat = 0, y: CGFloat = 0) {
self.x = x
self.y = y
}
}
public struct CGSize: Equatable {
public static let zero = CGSize()
public var width: CGFloat
public var height: CGFloat
public init(width: CGFloat = 0, height: CGFloat = 0) {
self.width = width
self.height = height
}
}
public struct CGRect: Equatable {
public static let zero = CGRect()
public var origin: CGPoint
public var size: CGSize
public init(origin: CGPoint = .zero, size: CGSize = CGSize()) {
self.origin = origin
self.size = size
}
public init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
self.init(
origin: CGPoint(x: x, y: y),
size: CGSize(width: width, height: height)
)
}
public var width: CGFloat { maxX - minX }
public var height: CGFloat { maxY - minY }
public var minX: CGFloat { Swift.min(origin.x, origin.x + size.width) }
public var minY: CGFloat { Swift.min(origin.y, origin.y + size.height) }
public var maxX: CGFloat { Swift.max(origin.x, origin.x + size.width) }
public var maxY: CGFloat { Swift.max(origin.y, origin.y + size.height) }
public func union(_ other: CGRect) -> CGRect {
let minX = Swift.min(self.minX, other.minX)
let minY = Swift.min(self.minY, other.minY)
let maxX = Swift.max(self.maxX, other.maxX)
let maxY = Swift.max(self.maxY, other.maxY)
return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY)
}
}
#endif
#if os(WASI) || os(Linux) || os(Android)
private let KAPPA: CGFloat = 0.5522847498 // 4 *(sqrt(2) -1)/3
public struct CGAffineTransform: Equatable {
public var a, b, c, d, tx, ty: CGFloat
public init(a: CGFloat, b: CGFloat, c: CGFloat, d: CGFloat, tx: CGFloat, ty: CGFloat) {
self.a = a
self.b = b
self.c = c
self.d = d
self.tx = tx
self.ty = ty
}
}
public enum CGLineJoin: UInt32 {
case miter
case round
case bevel
public init() { self = .miter }
}
public enum CGLineCap: UInt32 {
case butt
case round
case square
public init() { self = .butt }
}
/// A graphics path is a mathematical description of a series of shapes or lines.
public class CGPath {
public typealias Element = PathElement
public var elements: [Element]
public init(elements: [Element] = []) {
self.elements = elements
}
}
// MARK: - Supporting Types
/// A path element.
public enum PathElement {
/// The path element that starts a new subpath. The element holds a single point for the destination.
case moveToPoint(CGPoint)
/// The path element that adds a line from the current point to a new point.
/// The element holds a single point for the destination.
case addLineToPoint(CGPoint)
/// The path element that adds a quadratic curve from the current point to the specified point.
/// The element holds a control point and a destination point.
case addQuadCurveToPoint(CGPoint, CGPoint)
/// The path element that adds a cubic curve from the current point to the specified point.
/// The element holds two control points and a destination point.
case addCurveToPoint(CGPoint, CGPoint, CGPoint)
/// The path element that closes and completes a subpath. The element does not contain any points.
case closeSubpath
}
extension CGPath {
public var boundingBoxOfPath: CGRect {
var minX = CGFloat.infinity
var minY = CGFloat.infinity
var maxX = -CGFloat.infinity
var maxY = -CGFloat.infinity
for element in elements {
switch element {
case .moveToPoint(let point),
.addLineToPoint(let point):
minX = min(minX, point.x)
minY = min(minY, point.y)
maxX = max(maxX, point.x)
maxY = max(maxY, point.y)
case .addQuadCurveToPoint(let control, let point):
minX = min(minX, control.x, point.x)
minY = min(minY, control.y, point.y)
maxX = max(maxX, control.x, point.x)
maxY = max(maxY, control.y, point.y)
case .addCurveToPoint(let control1, let control2, let point):
minX = min(minX, control1.x, control2.x, point.x)
minY = min(minY, control1.y, control2.y, point.y)
maxX = max(maxX, control1.x, control2.x, point.x)
maxY = max(maxY, control1.y, control2.y, point.y)
case .closeSubpath:
break
}
}
return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY)
}
public func applyWithBlock(_ block: (UnsafePointer<CGPathElement>) -> Void) {
for element in elements {
let cgPathElement: CGPathElement
switch element {
case .moveToPoint(let point):
cgPathElement = CGPathElement(
type: .moveToPoint,
points: (point, CGPoint.zero, CGPoint.zero)
)
case .addLineToPoint(let point):
cgPathElement = CGPathElement(
type: .addLineToPoint,
points: (point, CGPoint.zero, CGPoint.zero)
)
case .addQuadCurveToPoint(let control, let point):
cgPathElement = CGPathElement(
type: .addQuadCurveToPoint,
points: (control, point, CGPoint.zero)
)
case .addCurveToPoint(let control1, let control2, let point):
cgPathElement = CGPathElement(
type: .addCurveToPoint,
points: (control1, control2, point)
)
case .closeSubpath:
cgPathElement = CGPathElement(
type: .closeSubpath,
points: (CGPoint.zero, CGPoint.zero, CGPoint.zero)
)
}
withUnsafePointer(to: cgPathElement) { pointer in
block(pointer)
}
}
}
public func addRect(_ rect: CGRect) {
let newElements: [Element] = [
.moveToPoint(CGPoint(x: rect.minX, y: rect.minY)),
.addLineToPoint(CGPoint(x: rect.maxX, y: rect.minY)),
.addLineToPoint(CGPoint(x: rect.maxX, y: rect.maxY)),
.addLineToPoint(CGPoint(x: rect.minX, y: rect.maxY)),
.closeSubpath,
]
elements.append(contentsOf: newElements)
}
public func addEllipse(in rect: CGRect) {
var p = CGPoint()
var p1 = CGPoint()
var p2 = CGPoint()
let hdiff = rect.width / 2 * KAPPA
let vdiff = rect.height / 2 * KAPPA
p = CGPoint(x: rect.origin.x + rect.width / 2, y: rect.origin.y + rect.height)
elements.append(.moveToPoint(p))
p = CGPoint(x: rect.origin.x, y: rect.origin.y + rect.height / 2)
p1 = CGPoint(x: rect.origin.x + rect.width / 2 - hdiff, y: rect.origin.y + rect.height)
p2 = CGPoint(x: rect.origin.x, y: rect.origin.y + rect.height / 2 + vdiff)
elements.append(.addCurveToPoint(p1, p2, p))
p = CGPoint(x: rect.origin.x + rect.size.width / 2, y: rect.origin.y)
p1 = CGPoint(x: rect.origin.x, y: rect.origin.y + rect.size.height / 2 - vdiff)
p2 = CGPoint(x: rect.origin.x + rect.size.width / 2 - hdiff, y: rect.origin.y)
elements.append(.addCurveToPoint(p1, p2, p))
p = CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height / 2)
p1 = CGPoint(x: rect.origin.x + rect.size.width / 2 + hdiff, y: rect.origin.y)
p2 = CGPoint(
x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height / 2 - vdiff)
elements.append(.addCurveToPoint(p1, p2, p))
p = CGPoint(x: rect.origin.x + rect.size.width / 2, y: rect.origin.y + rect.size.height)
p1 = CGPoint(
x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height / 2 + vdiff)
p2 = CGPoint(
x: rect.origin.x + rect.size.width / 2 + hdiff, y: rect.origin.y + rect.size.height)
elements.append(.addCurveToPoint(p1, p2, p))
}
public func move(to point: CGPoint) {
elements.append(.moveToPoint(point))
}
public func addLine(to point: CGPoint) {
elements.append(.addLineToPoint(point))
}
public func addCurve(to endPoint: CGPoint, control1: CGPoint, control2: CGPoint) {
elements.append(.addCurveToPoint(control1, control2, endPoint))
}
public func addQuadCurve(to endPoint: CGPoint, control: CGPoint) {
elements.append(.addQuadCurveToPoint(control, endPoint))
}
public func closeSubpath() {
elements.append(.closeSubpath)
}
}
public struct CGPathElement {
public var type: CGPathElementType
public var points: [CGPoint]
public init(type: CGPathElementType, points: (CGPoint, CGPoint, CGPoint)) {
self.type = type
self.points = [points.0, points.1, points.2]
}
}
/// Rules for determining which regions are interior to a path.
///
/// When filling a path, regions that a fill rule defines as interior to the path are painted.
/// When clipping with a path, regions interior to the path remain visible after clipping.
public enum CGPathFillRule: Int {
/// A rule that considers a region to be interior to a path based on the number of times it is enclosed by path elements.
case evenOdd
/// A rule that considers a region to be interior to a path if the winding number for that region is nonzero.
case winding
}
/// The type of element found in a path.
public enum CGPathElementType {
/// The path element that starts a new subpath. The element holds a single point for the destination.
case moveToPoint
/// The path element that adds a line from the current point to a new point.
/// The element holds a single point for the destination.
case addLineToPoint
/// The path element that adds a quadratic curve from the current point to the specified point.
/// The element holds a control point and a destination point.
case addQuadCurveToPoint
/// The path element that adds a cubic curve from the current point to the specified point.
/// The element holds two control points and a destination point.
case addCurveToPoint
/// The path element that closes and completes a subpath. The element does not contain any points.
case closeSubpath
}
extension CGPoint {
@inline(__always)
public func applying(_ t: CGAffineTransform) -> CGPoint {
return CGPoint(
x: t.a * x + t.c * y + t.tx,
y: t.b * x + t.d * y + t.ty)
}
}
extension CGAffineTransform {
public var isIdentity: Bool {
self == CGAffineTransform.identity
}
public static var identity: CGAffineTransform {
CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0)
}
public init(translationX tx: CGFloat, y ty: CGFloat) {
self.init(a: 1, b: 0, c: 0, d: 1, tx: tx, ty: ty)
}
public init(scaleX sx: CGFloat, y sy: CGFloat) {
self.init(a: sx, b: 0, c: 0, d: sy, tx: 0, ty: 0)
}
public init(rotationAngle angle: CGFloat) {
self.init(a: cos(angle), b: sin(angle), c: -sin(angle), d: cos(angle), tx: 0, ty: 0)
}
public func translatedBy(x: CGFloat, y: CGFloat) -> CGAffineTransform {
return CGAffineTransform(translationX: x, y: y).concatenating(self)
}
public func concatenating(_ t: CGAffineTransform) -> CGAffineTransform {
return CGAffineTransform(
a: a * t.a + b * t.c,
b: a * t.b + b * t.d,
c: c * t.a + d * t.c,
d: c * t.b + d * t.d,
tx: tx * t.a + ty * t.c + t.tx,
ty: tx * t.b + ty * t.d + t.ty
)
}
public func scaledBy(x: CGFloat, y: CGFloat) -> CGAffineTransform {
return CGAffineTransform(scaleX: x, y: y).concatenating(self)
}
public func rotated(by angle: CGFloat) -> CGAffineTransform {
return CGAffineTransform(rotationAngle: angle).concatenating(self)
}
}
public class MBezierPath {
public var cgPath: CGPath
public init() {
self.cgPath = CGPath()
}
public init?(rect: CGRect) {
self.cgPath = CGPath()
self.cgPath.addRect(rect)
}
public init?(ovalIn rect: CGRect) {
self.cgPath = CGPath()
self.cgPath.addEllipse(in: rect)
}
public init(
arcCenter: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat,
clockwise: Bool
) {
self.cgPath = CGPath()
MBezierPath.addArcTo(
path: self.cgPath, center: arcCenter, radius: radius, startAngle: startAngle,
endAngle: endAngle, clockwise: clockwise)
}
public func move(to point: CGPoint) {
cgPath.move(to: point)
}
public func addLine(to point: CGPoint) {
cgPath.addLine(to: point)
}
public func addCurve(
to endPoint: CGPoint, controlPoint1: CGPoint, controlPoint2: CGPoint
) {
cgPath.addCurve(to: endPoint, control1: controlPoint1, control2: controlPoint2)
}
public func addQuadCurve(to endPoint: CGPoint, controlPoint: CGPoint) {
cgPath.addQuadCurve(to: endPoint, control: controlPoint)
}
public func addArc(
withCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat,
clockwise: Bool
) {
MBezierPath.addArcTo(
path: self.cgPath, center: center, radius: radius, startAngle: startAngle,
endAngle: endAngle, clockwise: clockwise)
}
public func append(_ path: MBezierPath) {
cgPath.elements.append(contentsOf: path.cgPath.elements)
}
public func close() {
cgPath.closeSubpath()
}
public func apply(_ transform: CGAffineTransform) {
var newElements: [CGPath.Element] = []
for element in cgPath.elements {
switch element {
case .moveToPoint(let point):
newElements.append(.moveToPoint(point.applying(transform)))
case .addLineToPoint(let point):
newElements.append(.addLineToPoint(point.applying(transform)))
case .addQuadCurveToPoint(let control, let point):
newElements.append(
.addQuadCurveToPoint(control.applying(transform), point.applying(transform))
)
case .addCurveToPoint(let control1, let control2, let point):
newElements.append(
.addCurveToPoint(
control1.applying(transform), control2.applying(transform),
point.applying(transform)))
case .closeSubpath:
newElements.append(.closeSubpath)
}
}
self.cgPath.elements = newElements
}
public var isEmpty: Bool {
return cgPath.elements.isEmpty
}
public var bounds: CGRect {
return cgPath.boundingBoxOfPath
}
static func addArcTo(
path: CGPath, center: CGPoint, radius: CGFloat, startAngle: CGFloat,
endAngle: CGFloat, clockwise: Bool
) {
var deltaAngle: CGFloat
if clockwise {
deltaAngle = endAngle - startAngle
while deltaAngle < 0 { deltaAngle += 2 * .pi }
} else { // Counter-clockwise
deltaAngle = endAngle - startAngle
while deltaAngle > 0 { deltaAngle -= 2 * .pi }
}
if abs(deltaAngle) < 1e-6 { return } // Essentially no arc
let numSegments = Swift.max(1, Int(ceil(abs(deltaAngle) / (.pi / 2.0)))) // Max 90deg segments
let segmentAngleSweep = deltaAngle / CGFloat(numSegments)
var currentAngle = startAngle
let initialPoint = CGPoint(
x: center.x + radius * cos(currentAngle), y: center.y + radius * sin(currentAngle))
// `UIBezierPath.addArc(withCenter:…)` documents that it implicitly
// sets the current point to the arc's starting point before
// emitting any cubics. With a non-empty path whose previous
// segment ends elsewhere, that "set current point" is a `move`,
// i.e. it opens a NEW subpath at the arc's start — Apple does not
// stitch the previous subpath to the arc with an implicit line.
//
// The original polyfill emitted `addLine(to: initialPoint)` here,
// which fuses the previous subpath and the arc into a single big
// subpath. When the SVG fixture uses evenodd-rule fills built up
// from many `M…A…` subpaths (animal-music body outlines stitched
// from 15+ arcs), that fusion flips which regions the fill rule
// considers "inside", which is exactly the cream/white blob over
// the pelican beak and otter forelock on Web. Always `move` to
// match Apple's UIBezierPath semantics.
if path.elements.isEmpty || (path.elements.last?.isCloseSubpath ?? false) {
path.move(to: initialPoint)
} else if let lastElement = path.elements.last, let lastPoint = lastElement.lastPoint,
lastPoint != initialPoint
{
path.move(to: initialPoint)
}
for _ in 0..<numSegments {
let nextAngle = currentAngle + segmentAngleSweep
// L's sign must follow the sweep so the cubic handles point in
// the direction the arc is traversed. `abs(segmentAngleSweep)`
// here orients the handles as if the sweep were CW, which
// mirrors counter-clockwise arcs and yields self-intersecting
// cubic approximations. The downstream fill rule then flips
// inside/outside on those self-intersections, producing the
// "white blob" we see on pelican beak / otter forelock fills.
let L = radius * (4.0 / 3.0) * tan(segmentAngleSweep / 4.0)
let cp1_centerRelative = CGPoint(
x: radius * cos(currentAngle) - L * sin(currentAngle),
y: radius * sin(currentAngle) + L * cos(currentAngle)
)
let cp2_centerRelative = CGPoint(
x: radius * cos(nextAngle) + L * sin(nextAngle),
y: radius * sin(nextAngle) - L * cos(nextAngle)
)
let endPoint_abs = CGPoint(
x: center.x + radius * cos(nextAngle), y: center.y + radius * sin(nextAngle))
let cp1_abs = CGPoint(
x: center.x + cp1_centerRelative.x, y: center.y + cp1_centerRelative.y)
let cp2_abs = CGPoint(
x: center.x + cp2_centerRelative.x, y: center.y + cp2_centerRelative.y)
path.addCurve(to: endPoint_abs, control1: cp1_abs, control2: cp2_abs)
currentAngle = nextAngle
}
}
}
extension CGPath.Element {
var lastPoint: CGPoint? {
switch self {
case .moveToPoint(let p): return p
case .addLineToPoint(let p): return p
case .addQuadCurveToPoint(_, let p): return p
case .addCurveToPoint(_, _, let p): return p
case .closeSubpath: return nil
}
}
var isCloseSubpath: Bool {
if case .closeSubpath = self { return true }
return false
}
}
#else
import CoreGraphics
public typealias CGLineJoin = CoreGraphics.CGLineJoin
public typealias CGLineCap = CoreGraphics.CGLineCap
public typealias CGPathFillRule = CoreGraphics.CGPathFillRule
public typealias CGPath = CoreGraphics.CGPath
public typealias CGAffineTransform = CoreGraphics.CGAffineTransform
#endif