Skip to content

Commit

Permalink
Add Vectors app
Browse files Browse the repository at this point in the history
  • Loading branch information
titzer committed Aug 30, 2024
1 parent 454a941 commit 38fc092
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions apps/VectorND/DEPS
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

59 changes: 59 additions & 0 deletions apps/VectorND/Vectors.v3
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// 2-dimension single-precision vector.
type Vector2(x: float, y: float) #unboxed {
def add(that: Vector2) -> Vector2 {
return Vector2(this.x + that.x, this.y + that.y);
}
def sub(that: Vector2) -> Vector2 {
return Vector2(this.x - that.x, this.y - that.y);
}
def scale(factor: float) -> Vector2 {
return Vector2(this.x * factor, this.y * factor);
}
def inverse() -> Vector2 {
return Vector2(0f - this.x, 0f - this.y);
}
def dot(that: Vector2) -> float {
return this.x * that.x + this.y * that.y;
}
def unit() -> Vector2 {
var len = length();
return if(len == 1f, this, scale(1f / len));
}
def length() -> float {
return float.sqrt(this.x * this.x + this.y * this.y);
}
def cross(that: Vector2) -> float {
return this.x * that.y - this.y * that.x;
}
}

// 3-dimension single-precision vector.
type Vector3(x: float, y: float, z: float) #unboxed {
def add(that: Vector3) -> Vector3 {
return Vector3(this.x + that.x, this.y + that.y, this.z + that.z);
}
def sub(that: Vector3) -> Vector3 {
return Vector3(this.x - that.x, this.y - that.y, this.z - that.z);
}
def scale(factor: float) -> Vector3 {
return Vector3(this.x * factor, this.y * factor, this.z * factor);
}
def inverse() -> Vector3 {
return Vector3(0f - this.x, 0f - this.y, 0f - this.z);
}
def dot(that: Vector3) -> float {
return this.x * that.x + this.y * that.y + this.z * that.z;
}
def unit() -> Vector3 {
var len = length();
return if(len == 1f, this, scale(1f / len));
}
def length() -> float {
return float.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
}
def cross(that: Vector3) -> Vector3 {
return Vector3(this.y * that.z - this.z * that.y,
0f - (this.x * that.z - this.z * that.x),
this.x * that.y - this.y * that.x);
}
}

0 comments on commit 38fc092

Please sign in to comment.