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

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

namespace xrml {

SFFloat ScalarInterpolator::interpolate(float t)
{
  int i = (int)floor(t);
  int ip1 = (int)ceil(t);
  if (i == ip1)
    return keyValue[i];
  else {
    t = t - floor(t);
    float s = 1 - t;
    return (keyValue[i] * s + keyValue[ip1] * t);
  }
}

void ScalarInterpolator::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 ScalarInterpolator::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
