// Copyright 2009 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include "rkcommon/math/math.ih"

OSPRAY_BEGIN_ISPC_NAMESPACE

// x should be between [0..size-1]
inline float interp1DLinear(
    float x, const uniform float *uniform f, uniform int size)
{
  float xc = clamp(x, 0.f, (float)(size - 1));
  float s = xc - floor(xc);

  int x0 = min((int)xc, size - 1);
  int x1 = min(x0 + 1, size - 1);

  return lerp(s, f[x0], f[x1]);
}

// p should be between [0..size-1]
inline float interp2DLinear(
    vec2f p, const uniform float *uniform f, uniform vec2i size)
{
  float xc = clamp(p.x, 0.f, (float)(size.x - 1));
  float yc = clamp(p.y, 0.f, (float)(size.y - 1));

  float sx = xc - floor(xc);
  float sy = yc - floor(yc);

  int x0 = min((int)xc, size.x - 1);
  int x1 = min(x0 + 1, size.x - 1);

  int y0 = min((int)yc, size.y - 1);
  int y1 = min(y0 + 1, size.y - 1);

  int ny = size.x;

  float f0 = lerp(sx, f[x0 + y0 * ny], f[x1 + y0 * ny]);
  float f1 = lerp(sx, f[x0 + y1 * ny], f[x1 + y1 * ny]);

  return lerp(sy, f0, f1);
}

// p should be between [0..size-1]
inline float interp3DLinear(
    vec3f p, const uniform float *uniform f, uniform vec3i size)
{
  float xc = clamp(p.x, 0.f, (float)(size.x - 1));
  float yc = clamp(p.y, 0.f, (float)(size.y - 1));
  float zc = clamp(p.z, 0.f, (float)(size.z - 1));

  float sx = xc - floor(xc);
  float sy = yc - floor(yc);
  float sz = zc - floor(zc);

  int x0 = min((int)xc, size.x - 1);
  int x1 = min(x0 + 1, size.x - 1);

  int y0 = min((int)yc, size.y - 1);
  int y1 = min(y0 + 1, size.y - 1);

  int z0 = min((int)zc, size.z - 1);
  int z1 = min(z0 + 1, size.z - 1);

  int ny = size.x;
  int nz = size.x * size.y;

  float f00 = lerp(sx, f[x0 + y0 * ny + z0 * nz], f[x1 + y0 * ny + z0 * nz]);
  float f01 = lerp(sx, f[x0 + y1 * ny + z0 * nz], f[x1 + y1 * ny + z0 * nz]);

  float f10 = lerp(sx, f[x0 + y0 * ny + z1 * nz], f[x1 + y0 * ny + z1 * nz]);
  float f11 = lerp(sx, f[x0 + y1 * ny + z1 * nz], f[x1 + y1 * ny + z1 * nz]);

  float f0 = lerp(sy, f00, f01);
  float f1 = lerp(sy, f10, f11);

  return lerp(sz, f0, f1);
}
OSPRAY_END_ISPC_NAMESPACE
