Skip to content

Instantly share code, notes, and snippets.

@codelynx
Last active November 7, 2015 14:35
Show Gist options
  • Save codelynx/93ba6cabc245a7dfe305 to your computer and use it in GitHub Desktop.
Save codelynx/93ba6cabc245a7dfe305 to your computer and use it in GitHub Desktop.
Swift 2.0: Vector3D Vector2D
//
// Geometry.swift
// ZKit
//
// Created by Kaz Yoshikawa on 11/6/15.
//
//
import Foundation
import CoreGraphics
infix operator ⨯ { associativity left precedence 150 }
infix operator • { associativity left precedence 150 }
//
// Vector3D
//
struct Vector3D {
var x: Float
var y: Float
var z: Float
init(_ x: Float, _ y: Float, _ z: Float) {
self.x = x; self.y = y; self.z = z
}
func length²() -> Float {
return (x * x) + (y * y) + (z * z)
}
func length() -> Float {
return sqrtf(self.length²())
}
func normalized() -> Vector3D {
let l = self.length()
return Vector3D(x/l, y/l, z/l)
}
}
func + (l: Vector3D, r: Vector3D) -> Vector3D {
return Vector3D(l.x + r.x, l.y + r.y, l.z + r.z)
}
func - (l: Vector3D, r: Vector3D) -> Vector3D {
return Vector3D(l.x - r.x, l.y - r.y, l.z - r.z)
}
func * (l: Vector3D, r: Float) -> Vector3D {
return Vector3D(l.x * r, l.y * r, l.z * r)
}
func / (l: Vector3D, r: Float) -> Vector3D {
return Vector3D(l.x / r, l.y / r, l.z / r)
}
func • (a: Vector3D, b: Vector3D) -> Float { // dot product
return (a.x * b.x) + (a.y * b.y) + (a.z + b.z)
}
func ⨯ (a: Vector3D, b: Vector3D) -> Vector3D { // cross product
return Vector3D(
a.y * b.z - b.y * a.z,
a.z * b.x - b.z * a.x,
a.x * b.y - b.x * a.y)
}
func length²(lhs: Vector3D, _ rhs: Vector3D) -> Float {
return powf(rhs.x - lhs.x, 2.0) + powf(rhs.y - lhs.y, 2.0) + powf(rhs.z - lhs.z, 2.0)
}
func length(lhs: Vector3D, _ rhs: Vector3D) -> Float {
return sqrtf(length²(lhs, rhs))
}
//
// Vector2D
//
struct Vector2D {
var x: Float
var y: Float
init(_ x: Float, _ y: Float) {
self.x = x; self.y = y
}
func length²() -> Float {
return (x * x) + (y * y)
}
func length() -> Float {
return sqrtf(self.length²())
}
func normalized() -> Vector2D {
let l = self.length()
return Vector2D(x/l, y/l)
}
}
func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
return Vector2D(lhs.x + rhs.x, lhs.y + rhs.y)
}
func - (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
return Vector2D(lhs.x - rhs.x, lhs.y - rhs.y)
}
func * (lhs: Vector2D, rhs: Float) -> Vector2D {
return Vector2D(lhs.x * rhs, lhs.y * rhs)
}
func / (lhs: Vector2D, rhs: Float) -> Vector2D {
return Vector2D(lhs.x / rhs, lhs.y / rhs)
}
func • (lhs: Vector2D, rhs: Vector2D) -> Float { // dot product
return lhs.x * rhs.y - lhs.y * rhs.x
}
func ⨯ (lhs: Vector2D, rhs: Vector2D) -> Float { // cross product
return lhs.x * rhs.y - lhs.y * rhs.x
}
func length²(lhs: Vector2D, _ rhs: Vector2D) -> Float {
return pow(rhs.x - lhs.x, 2.0) + pow(rhs.y - lhs.y, 2.0)
}
func length(lhs: Vector2D, _ rhs: Vector2D) -> Float {
return sqrt(length²(lhs, rhs))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment