Files
CavesOfSwift/Sources/Maths/FloatExtensions.swift

63 lines
1.5 KiB
Swift

import Foundation
public extension FloatingPoint
{
@inline(__always) var saturate: Self { min(max(self , 0), 1) }
@inline(__always) static func lerp(_ a: Self, _ b: Self, _ x: Self) -> Self { a * (1 - x) + b * x }
@inline(__always) static func deg(fromRad: Self) -> Self { fromRad * (180 / Self.pi) }
@inline(__always) static func rad(fromDeg: Self) -> Self { fromDeg * (Self.pi / 180) }
@inline(__always) func smoothStep() -> Self
{
let x = self.saturate
return x * x * (3 - 2 * x)
}
func smoothStep(_ a: Self, _ b: Self) -> Self
{
let x = self.smoothStep()
return b * x + a * (1 - x)
}
@inline(__always) func smootherStep() -> Self
{
let x = self.saturate
return x * x * x * (x * (x * 6 - 15) + 10)
}
func smootherStep(_ a: Self, _ b: Self) -> Self
{
let x = self.smootherStep()
return b * x + a * (1 - x)
}
func sqrInterp(_ a: Self, _ b: Self) -> Self
{
let x = self.saturate, xx = x * x
return a * (1 - xx) + b * xx
}
func invSqrInterp(_ a: Self, _ b: Self) -> Self
{
let x = 1 - self.saturate, xx = x * x
return a * xx + b * (1 - xx)
}
}
extension FloatingPoint where Self == Double
{
@inline(__always) var sine: Self { sin(self) }
@inline(__always) var cosine: Self { cos(self) }
@inline(__always) var tangent: Self { tan(self) }
}
extension FloatingPoint where Self == Float
{
@inline(__always) var sine: Self { sinf(self) }
@inline(__always) var cosine: Self { cosf(self) }
@inline(__always) var tangent: Self { tanf(self) }
}