/* ColorInterpolator.C: ColorInterpolator nodes (public source) */

#include <math.h>
#include "ColorInterpolator.H"

namespace xrml {

static SFColor SFColor_interpolate(const SFColor& v1, const SFColor& v2, float t)
{
  // TODO: should interpolate in HSV space rather than RGB
  float s = 1.-t;
  return SFColor(v1.r * s + v2.r * t,
		 v1.g * s + v2.g * t,
		 v1.b * s + v2.b * t);
}

SFColor ColorInterpolator::interpolate(float t)
{
  int i = (int)floor(t);
  int ip1 = (int)ceil(t);
  if (i == ip1)
    return keyValue[i];
  else
    return SFColor_interpolate(keyValue[i], keyValue[ip1], t - floor(t));
}

void ColorInterpolator::set_fraction(const SFFloat& t)
{
  if (!initialised)
    return;
  float index = get_index(t);
  if (index >= 0. && index <= (float)(keyValue.size-1))
    post_value_changed(interpolate(index));
}

void ColorInterpolator::render(void)
{
  if (key.size != keyValue.size) {
    Error(NULL, "%s: number of key frames and values doesn't match", name());
    return;
  }

  if (!initialised) {
    if (keyValue.size > 0)
      value_changed = keyValue[0];
    initialised = true;
  }
}

}  // namespace xrml
