From 1af3b0a4f587b3ae4c25fad867decc2fbcfdc4af Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Wed, 11 Oct 2023 22:40:57 -0700 Subject: [PATCH] add YCbCr -> sRGB conversion --- YCbCr.zig | 15 +++++++++++++++ _x.zig | 28 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 _x.zig diff --git a/YCbCr.zig b/YCbCr.zig index e62464eac452553eefd8deda3de2dda1df7381ac..8e87e6e848b5de016f60d8b6d767cb7f38f136fa 100644 --- a/YCbCr.zig +++ b/YCbCr.zig @@ -3,6 +3,7 @@ const std = @import("std"); const Self = @This(); const color = @import("./mod.zig"); +const _x = @import("./_x.zig"); y: u8, cb: u8, @@ -25,3 +26,17 @@ pub fn initYCbCr(y: u8, cb: u8, cr: u8) Self { pub fn eql(x: Self, y: Self) bool { return x.y == y.y and x.cb == y.cb and x.cr == y.cr and x.a == y.a; } + +pub usingnamespace _x.mixin(@This(), .y, .cb, .cr); + +pub fn to_srgb(x: Self) color.sRGB { + // zig fmt: off + const f = x.to_vec(); + return color.sRGB.from_vec(.{ + @max(0, @min(255, f[0] + 1.402 * (f[2]-128))), + @max(0, @min(255, f[0] - 0.34414 * (f[1]-128) - 0.71414 * (f[2]-128))), + @max(0, @min(255, f[0] + 1.772 * (f[1]-128))), + @max(0, @min(255, f[3])), + }); + // zig fmt: on +} diff --git a/_x.zig b/_x.zig new file mode 100644 index 0000000000000000000000000000000000000000..28c4f726cecc159a01f9a9fb7d76ee6f6c6a3424 --- /dev/null +++ b/_x.zig @@ -0,0 +1,28 @@ +const std = @import("std"); + +pub fn mixin( + comptime T: type, + comptime f1: std.meta.FieldEnum(T), + comptime f2: std.meta.FieldEnum(T), + comptime f3: std.meta.FieldEnum(T), +) type { + return struct { + pub fn to_vec(x: T) @Vector(4, f32) { + return .{ + @floatFromInt(@field(x, @tagName(f1))), + @floatFromInt(@field(x, @tagName(f2))), + @floatFromInt(@field(x, @tagName(f3))), + @floatFromInt(x.a), + }; + } + + pub fn from_vec(in: @Vector(4, f32)) T { + var x: T = undefined; + @field(x, @tagName(f1)) = @intFromFloat(in[0]); + @field(x, @tagName(f2)) = @intFromFloat(in[1]); + @field(x, @tagName(f3)) = @intFromFloat(in[2]); + x.a = @intFromFloat(in[3]); + return x; + } + }; +} -- 2.54.0