package Shiar_Sheet::Colour;

use strict;
use warnings;
use List::Util qw( min max );

our $VERSION = '1.02';

# ITU-R recommendation 601 luma co-efficients
our $kr = .299;
our $kb = .114;
our $kg = 1 - $kb - $kr;

my $PI = 2 * atan2 1, 0;

sub new {
	my $class = shift;
	my @rgb = @_ >= 3 ? @_ : (map {hex} $_[0] =~ /(..)/g);
	bless \@rgb, $class;
}

sub newyuv {
	# convert from YPbPr values 0..255 (or hex string)
	my $class = shift;
	my ($y, $cb, $cr) = @_ >= 3 ? @_ : (map {hex} $_[0] =~ /(..)/g);

	$_ -= 128 for $cb, $cr;
	$_ /= 255 for $y, $cb, $cr;

	my @rgb = map { max(0, min(255, $_ * 255)) } (
		$y                             + $cr,
		$y - $cb * (1 - $kb) * $kb/$kg - $cr * $kr/$kg,
		$y + $cb * (1 - $kb)           ,
	);
	bless \@rgb, $class;
}

sub luminance {
	# perceived brightness
	my ($r, $g, $b) = @{ $_[0] };
	return $r*$kr + $g*$kg + $b*$kb;
}

sub hue {
	my ($r, $g, $b) = @{ $_[0] };
	my $hue = atan2 sqrt(3) * ($g - $b), $r*2 - $g - $b;
	return ($hue + $PI) / $PI / 2; # 0 .. 1
}

sub rgb24 {
	my $str = '';
	$str .= sprintf '%X', min($_ / 17 + .5, 15) for @{ $_[0] };
	return $str;
}

sub rgb48 {
	my $str = '';
	$str .= sprintf '%02X', $_ for @{ $_[0] };
	return $str;
}

1;

