Skip to content

Instantly share code, notes, and snippets.

@erikbasargin
Forked from mecid/AnimatableVector.swift
Created June 17, 2020 11:26
Show Gist options
  • Select an option

  • Save erikbasargin/b531f815fac68e9344c47759cb077dae to your computer and use it in GitHub Desktop.

Select an option

Save erikbasargin/b531f815fac68e9344c47759cb077dae to your computer and use it in GitHub Desktop.
High-performance Animatable Vector for SwiftUI
import SwiftUI
import enum Accelerate.vDSP
struct AnimatableVector: VectorArithmetic {
static var zero = AnimatableVector(values: [0.0])
static func + (lhs: AnimatableVector, rhs: AnimatableVector) -> AnimatableVector {
let count = min(lhs.values.count, rhs.values.count)
return AnimatableVector(values: vDSP.add(lhs.values[0..<count], rhs.values[0..<count]))
}
static func += (lhs: inout AnimatableVector, rhs: AnimatableVector) {
let count = min(lhs.values.count, rhs.values.count)
vDSP.add(lhs.values[0..<count], rhs.values[0..<count], result: &lhs.values[0..<count])
}
static func - (lhs: AnimatableVector, rhs: AnimatableVector) -> AnimatableVector {
let count = min(lhs.values.count, rhs.values.count)
return AnimatableVector(values: vDSP.subtract(lhs.values[0..<count], rhs.values[0..<count]))
}
static func -= (lhs: inout AnimatableVector, rhs: AnimatableVector) {
let count = min(lhs.values.count, rhs.values.count)
vDSP.subtract(lhs.values[0..<count], rhs.values[0..<count], result: &lhs.values[0..<count])
}
var values: [Double]
mutating func scale(by rhs: Double) {
vDSP.multiply(rhs, values, result: &values)
}
var magnitudeSquared: Double {
vDSP.sum(vDSP.multiply(values, values))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment