//	GGVRColor.swift
//
//	© 2026 by Jeff Weeks
//	See TermsOfUse.txt

func HSVtoRGB(
	hue: Double,
	saturation: Double,
	value: Double
) -> simd_half3 {

	let theBaseColors: [SIMD3<Double>] = [
							SIMD3<Double>(1.0, 0.0, 0.0),	//	red
							SIMD3<Double>(1.0, 1.0, 0.0),	//	yellow
							SIMD3<Double>(0.0, 1.0, 0.0),	//	green
							SIMD3<Double>(0.0, 1.0, 1.0),	//	cyan
							SIMD3<Double>(0.0, 0.0, 1.0),	//	blue
							SIMD3<Double>(1.0, 0.0, 1.0)	//	magenta
						]

	let theHue        = max(0.0, min(1.0, hue       ))
	let theSaturation = max(0.0, min(1.0, saturation))
	let theValue      = max(0.0, min(1.0, value     ))

	//	Divide the color circle into six equal segments, to be delimited
	//	by the colors {red, yellow, green, cyan, blue, magenta, red}.
	let theHue6 = 6.0 * theHue		//	∈ [0.0, 6.0]
	let theSegment = floor(theHue6)	//	∈ {0,1,2,3,4,5,6}
	let theInterpolator	= theHue6 - theSegment

	let theLeftHue	= theBaseColors[   Int(theSegment)   % 6 ]	//	cast from Double to Int
	let theRightHue	= theBaseColors[ Int(theSegment + 1) % 6 ]

	var theRGBColor: simd_half3 = simd_half3.zero
	for i in 0...2 {	//	iterate over r,g,b components
	
		let theRawColor			= (1.0 - theInterpolator) * theLeftHue [i]
								+     theInterpolator     * theRightHue[i]
		
		let theDesaturatedColor	=     theSaturation     * theRawColor
								+ (1.0 - theSaturation) *     1.0
		
		let theDarkenedColor	= theValue * theDesaturatedColor
		
		theRGBColor[i] = Float16(theDarkenedColor)
	}
	
	return theRGBColor
}
