From 6fd6a8fa67166bd56b654a2d553b8e335e73a8a6 Mon Sep 17 00:00:00 2001 From: msg-programs Date: Thu, 23 Jan 2025 19:46:50 +0100 Subject: [PATCH] Add format function for vector and matrix types. --- src/math/mat.zig | 23 +++++++++++++++++++++++ src/math/vec.zig | 13 +++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/math/mat.zig b/src/math/mat.zig index 5a31a32d90..da5fbc07f6 100644 --- a/src/math/mat.zig +++ b/src/math/mat.zig @@ -1,3 +1,5 @@ +const std = @import("std"); + const mach = @import("../main.zig"); const testing = mach.testing; const math = mach.math; @@ -118,6 +120,7 @@ pub fn Mat2x2( pub const mul = Shared.mul; pub const mulVec = Shared.mulVec; + pub const format = Shared.format; }; } @@ -258,6 +261,7 @@ pub fn Mat3x3( pub const mul = Shared.mul; pub const mulVec = Shared.mulVec; + pub const format = Shared.format; }; } @@ -485,6 +489,7 @@ pub fn Mat4x4( pub const mulVec = Shared.mulVec; pub const eql = Shared.eql; pub const eqlApprox = Shared.eqlApprox; + pub const format = Shared.format; }; } @@ -542,6 +547,24 @@ pub fn MatShared(comptime RowVec: type, comptime ColVec: type, comptime Matrix: } return true; } + + /// Custom format function for all matrix types. + pub inline fn format( + self: Matrix, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) @TypeOf(writer).Error!void { + const rows = @TypeOf(self).rows; + try writer.print("{{", .{}); + inline for (0..rows) |r| { + try std.fmt.formatType(self.row(r), fmt, options, writer, 1); + if (r < rows - 1) { + try writer.print(", ", .{}); + } + } + try writer.print("}}", .{}); + } }; } diff --git a/src/math/vec.zig b/src/math/vec.zig index 90aaa034cc..914846bf87 100644 --- a/src/math/vec.zig +++ b/src/math/vec.zig @@ -67,6 +67,7 @@ pub fn Vec2(comptime Scalar: type) type { pub const minScalar = Shared.minScalar; pub const eqlApprox = Shared.eqlApprox; pub const eql = Shared.eql; + pub const format = Shared.format; }; } @@ -190,6 +191,7 @@ pub fn Vec3(comptime Scalar: type) type { pub const minScalar = Shared.minScalar; pub const eqlApprox = Shared.eqlApprox; pub const eql = Shared.eql; + pub const format = Shared.format; }; } @@ -269,6 +271,7 @@ pub fn Vec4(comptime Scalar: type) type { pub const minScalar = Shared.minScalar; pub const eqlApprox = Shared.eqlApprox; pub const eql = Shared.eql; + pub const format = Shared.format; }; } @@ -519,6 +522,16 @@ pub fn VecShared(comptime Scalar: type, comptime VecN: type) type { pub inline fn eql(a: *const VecN, b: *const VecN) bool { return a.eqlApprox(b, math.eps(Scalar)); } + + /// Custom format function for all vector types. + pub inline fn format( + self: VecN, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) @TypeOf(writer).Error!void { + try std.fmt.formatType(self.v, fmt, options, writer, 1); + } }; }