Vec3 sample implementation
This commit is contained in:
parent
c4d10a42df
commit
8d0420e478
2 changed files with 50 additions and 0 deletions
|
@ -2,8 +2,14 @@
|
||||||
//! you are building an executable. If you are making a library, the convention
|
//! you are building an executable. If you are making a library, the convention
|
||||||
//! is to delete this file and start with root.zig instead.
|
//! is to delete this file and start with root.zig instead.
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const Vec3 = @import("vector.zig").Vec3;
|
||||||
|
|
||||||
pub fn main() !void {
|
pub fn main() !void {
|
||||||
|
const a = Vec3.new(1.0, 2.0, 3.0);
|
||||||
|
const b = Vec3.new(4.0, 5.0, 6.0);
|
||||||
|
const c = a.dot(b);
|
||||||
|
std.debug.print("a dot b = {d}\n", .{c});
|
||||||
|
|
||||||
// Prints to stderr (it's a shortcut based on `std.io.getStdErr()`)
|
// Prints to stderr (it's a shortcut based on `std.io.getStdErr()`)
|
||||||
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
|
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
|
||||||
|
|
||||||
|
|
44
src/vector.zig
Normal file
44
src/vector.zig
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
const expect = @import("std").testing.expect;
|
||||||
|
|
||||||
|
/// A 3D vector.
|
||||||
|
pub const Vec3 = struct {
|
||||||
|
x: f32,
|
||||||
|
y: f32,
|
||||||
|
z: f32,
|
||||||
|
|
||||||
|
/// Creates a new vector with the given components.
|
||||||
|
pub fn new(x: f32, y: f32, z: f32) Vec3 {
|
||||||
|
return Vec3{ .x = x, .y = y, .z = z };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the dot product of this vector and another.
|
||||||
|
pub fn dot(self: Vec3, other: Vec3) f32 {
|
||||||
|
return self.x * other.x + self.y * other.y + self.z * other.z;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the cross product of this vector and another.
|
||||||
|
pub fn cross(self: Vec3, other: Vec3) Vec3 {
|
||||||
|
return Vec3{
|
||||||
|
.x = self.y * other.z - self.z * other.y,
|
||||||
|
.y = self.z * other.x - self.x * other.z,
|
||||||
|
.z = self.x * other.y - self.y * other.x,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns true if this vector is equal to another.
|
||||||
|
pub fn equals(self: *const Vec3, other: *const Vec3) bool {
|
||||||
|
return self.x == other.x and self.y == other.y and self.z == other.z;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
test "Dot product" {
|
||||||
|
const a = Vec3{ .x = 1, .y = 2, .z = 3 };
|
||||||
|
const b = Vec3{ .x = 4, .y = 5, .z = 6 };
|
||||||
|
try expect(a.dot(b) == 32);
|
||||||
|
}
|
||||||
|
|
||||||
|
test "Cross product" {
|
||||||
|
const a = Vec3{ .x = 1, .y = 2, .z = 3 };
|
||||||
|
const b = Vec3{ .x = 4, .y = 5, .z = 6 };
|
||||||
|
try expect(a.cross(b).equals(&Vec3{ .x = -3, .y = 6, .z = -3 }));
|
||||||
|
}
|
Loading…
Reference in a new issue