Last active
July 22, 2021 12:23
-
-
Save hadiidbouk/e3dc6c9bcdfead361acaebb4498826c6 to your computer and use it in GitHub Desktop.
De Casteljau's algorithm implementation in Swift 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CoreGraphics | |
class Casteljau { | |
let count: Int | |
let x: [CGFloat] | |
let y: [CGFloat] | |
var b: [[CGFloat]] | |
init(p0: CGPoint, p1: CGPoint, p2: CGPoint, p3: CGPoint) { | |
let points = [p0, p1, p2, p3] | |
x = points.map(\.x) | |
y = points.map(\.y) | |
count = points.count | |
let nanArray = Array(repeating: CGFloat.nan, count: count) | |
b = Array(repeating: nanArray, count: count) | |
} | |
func point(at t: CGFloat) -> CGPoint { | |
return .init(x: evaluate(t: t, initialValues: x), | |
y: evaluate(t: t, initialValues: y)) | |
} | |
} | |
private extension Casteljau { | |
func initialize(_ initialValues: [CGFloat]) { | |
for i in 0..<count { | |
b[0][i] = initialValues[i] | |
} | |
} | |
func evaluate(t: CGFloat, initialValues: [CGFloat]) -> CGFloat { | |
initialize(initialValues) | |
for j in 1..<count { | |
for i in 0..<count-j { | |
b[j][i] = b[j-1][i] * (1-t) + b[j-1][i+1] * t | |
} | |
} | |
return b[count-1][0] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment