From c498be6597f316c93ed6b9f0c13838802fb23123 Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Thu, 14 Sep 2023 18:29:10 -0700 Subject: [PATCH] add LinearRgb --- LinearRgb.zig | 26 ++++++++++++++++++++++++++ mod.zig | 1 + sRGB.zig | 18 ++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 LinearRgb.zig diff --git a/LinearRgb.zig b/LinearRgb.zig new file mode 100644 index 0000000000000000000000000000000000000000..07b9c9c806f96fddb3374a3ee0761ccfbf6faa2a --- /dev/null +++ b/LinearRgb.zig @@ -0,0 +1,26 @@ +//! object representing a single color in the Linear RGB colorspace with channel values from 0-1 + +const std = @import("std"); +const Self = @This(); + +r: f32, +g: f32, +b: f32, +a: f32, + +pub fn initRGBA(r: u8, g: u8, b: u8, a: u8) Self { + std.debug.assert(r >= 0.0 and r <= 1.0); + std.debug.assert(g >= 0.0 and g <= 1.0); + std.debug.assert(b >= 0.0 and b <= 1.0); + std.debug.assert(a >= 0.0 and a <= 1.0); + return Self{ + .r = r, + .g = g, + .b = b, + .a = a, + }; +} + +pub fn eql(x: Self, y: Self) bool { + return x.r == y.r and x.g == y.g and x.b == y.b; +} diff --git a/mod.zig b/mod.zig index 57ad889c6ce4d4b1c786cfc962819e770258c28b..3068e2b407e22eb6c28394df90b3f90ffba82e36 100644 --- a/mod.zig +++ b/mod.zig @@ -2,3 +2,4 @@ const std = @import("std"); const color = @This(); pub const sRGB = @import("./sRGB.zig"); +pub const LinearRgb = @import("./LinearRgb.zig"); diff --git a/sRGB.zig b/sRGB.zig index f52c17efbc3fdce8532a34bea39ff6fecb62210d..d62e5c38e6ebd063d8a924b4e4d93244f3d08b35 100644 --- a/sRGB.zig +++ b/sRGB.zig @@ -2,6 +2,7 @@ const std = @import("std"); const Self = @This(); +const color = @import("./mod.zig"); r: u8, // red value g: u8, // green value @@ -63,3 +64,20 @@ pub fn format(x: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, std.fmt.fmtSliceHexLower(&.{x.b}), }); } + +pub fn to_linear_rgb(x: Self) color.LinearRgb { + const lut = comptime blk: { + var res: [256]f32 = undefined; + for (0..256) |i| { + const c = @as(f32, @floatFromInt(i)) / 255.0; + res[i] = if (c <= 0.04045) c / 12.92 else std.math.pow(f32, (c + 0.055) / 1.055, 2.4); + } + break :blk res; + }; + return color.LinearRgb.initRGBA( + lut[x.r], + lut[x.g], + lut[x.b], + lut[x.a], + ); +} -- 2.54.0