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

#pragma once

#include "math/sampling.ih"
#include "rkcommon/math/LinearSpace.ih"

OSPRAY_BEGIN_ISPC_NAMESPACE

/*! Reflects a viewing vector I at a normal N. Cosine between I
 *  and N is given as input. */
inline vec3f reflect(const vec3f &I, const vec3f &N, float cosI)
{
  return (2.0f * cosI) * N - I;
}

/*! Reflects a viewing vector I at a normal N. */
inline vec3f reflect(const vec3f &I, const vec3f &N)
{
  return reflect(I, N, dot(I, N));
}

// helper function which computes cosT^2 from cosI and eta
inline float sqrCosT(const float cosI, const float eta)
{
  return 1.0f - sqr(eta) * (1.0f - sqr(cosI));
}

//! \brief Refracts a viewing vector I at a normal N
/*! \detailed Refracts a viewing vector I at a normal N using the
 *  relative refraction index eta. Eta is refraction index of outside
 *  medium (where N points into) divided by refraction index of the
 *  inside medium. The vectors I and N have to point towards the same
 *  side of the surface. The cosine between I and N, and the cosine of -N and
 *  the refracted ray is given as input */
inline vec3f refract(
    const vec3f &I, const vec3f &N, float cosI, float cosT, float eta)
{
  return eta * (cosI * N - I) - cosT * N;
}

inline vec3f refract(const vec3f &I, const vec3f &N, float cosI, float eta)
{
  const float sqrcost = sqrCosT(cosI, eta);
  if (sqrcost < 0.0f)
    return make_vec3f(0.f);
  return refract(I, N, cosI, sqrt(sqrcost), eta);
}

inline float refract(float cosI, float eta)
{
  const float sqrcost = sqrCosT(cosI, eta);
  return sqrt(max(sqrcost, 0.0f));
}

OSPRAY_END_ISPC_NAMESPACE
