namespace Titano.Core.Mathematics;
/// CIE 1931 chromaticity coordinates (lower-case x, y in the literature).
public readonly record struct Chromaticity(double X, double Y)
{
/// CIE standard illuminant D65 (2° observer).
public static Chromaticity D65 { get; } = new(0.3127, 0.3290);
/// CIE standard illuminant D50 (2° observer), the ICC/DNG profile connection white.
public static Chromaticity D50 { get; } = new(0.3457, 0.3585);
/// Tristimulus values with luminance : X = x·Y/y, Z = (1 − x − y)·Y/y.
public Vector3D ToXyz(double luminance = 1)
{
if (!(Y > 0)) throw new InvalidOperationException("Chromaticity y must be positive.");
return new Vector3D(X * luminance / Y, luminance, (1 - X - Y) * luminance / Y);
}
/// Chromaticity of tristimulus values; NaN coordinates when X + Y + Z is not positive.
public static Chromaticity FromXyz(Vector3D xyz)
{
var sum = xyz.X + xyz.Y + xyz.Z;
return sum > 0 ? new Chromaticity(xyz.X / sum, xyz.Y / sum) : new Chromaticity(double.NaN, double.NaN);
}
/// CIE 1960 UCS coordinates u = 4x/(−2x + 12y + 3), v = 6y/(−2x + 12y + 3).
public (double U, double V) ToUv1960()
{
var d = -2 * X + 12 * Y + 3;
return (4 * X / d, 6 * Y / d);
}
/// Chromaticity from CIE 1960 UCS coordinates.
public static Chromaticity FromUv1960(double u, double v)
{
var d = 2 * u - 8 * v + 4;
return new Chromaticity(3 * u / d, 2 * v / d);
}
}