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

#pragma once

#include "../math/vec.isph"

Vec3f closestPointTriangle(Vec3f const& p, Vec3f const& a, Vec3f const& b, Vec3f const& c)
{
  const Vec3f ab = b - a;
  const Vec3f ac = c - a;
  const Vec3f ap = p - a;

  const float d1 = dot(ab, ap);
  const float d2 = dot(ac, ap);
  if (d1 <= 0.f && d2 <= 0.f) return a;

  const Vec3f bp = p - b;
  const float d3 = dot(ab, bp);
  const float d4 = dot(ac, bp);
  if (d3 >= 0.f && d4 <= d3) return b;

  const Vec3f cp = p - c;
  const float d5 = dot(ab, cp);
  const float d6 = dot(ac, cp);
  if (d6 >= 0.f && d5 <= d6) return c;

  const float vc = d1 * d4 - d3 * d2;
  if (vc <= 0.f && d1 >= 0.f && d3 <= 0.f)
  {
      const float v = d1 / (d1 - d3);
      return a + v * ab;
  }
  
  const float vb = d5 * d2 - d1 * d6;
  if (vb <= 0.f && d2 >= 0.f && d6 <= 0.f)
  {
      const float v = d2 / (d2 - d6);
      return a + v * ac;
  }
  
  const float va = d3 * d6 - d5 * d4;
  if (va <= 0.f && (d4 - d3) >= 0.f && (d5 - d6) >= 0.f)
  {
      const float v = (d4 - d3) / ((d4 - d3) + (d5 - d6));
      return b + v * (c - b);
  }

  const float denom = 1.f / (va + vb + vc);
  const float v = vb * denom;
  const float w = vc * denom;
  return a + v * ab + w * ac;
}

uniform Vec3f closestPointTriangle(uniform Vec3f& p, uniform Vec3f& a, uniform Vec3f& b, uniform Vec3f& c)
{
  const uniform Vec3f ab = b - a;
  const uniform Vec3f ac = c - a;
  const uniform Vec3f ap = p - a;

  const uniform float d1 = dot(ab, ap);
  const uniform float d2 = dot(ac, ap);
  if (d1 <= 0.f && d2 <= 0.f) return a;

  const uniform Vec3f bp = p - b;
  const uniform float d3 = dot(ab, bp);
  const uniform float d4 = dot(ac, bp);
  if (d3 >= 0.f && d4 <= d3) return b;

  const uniform Vec3f cp = p - c;
  const uniform float d5 = dot(ab, cp);
  const uniform float d6 = dot(ac, cp);
  if (d6 >= 0.f && d5 <= d6) return c;

  const uniform float vc = d1 * d4 - d3 * d2;
  if (vc <= 0.f && d1 >= 0.f && d3 <= 0.f)
  {
      const uniform float v = d1 / (d1 - d3);
      return a + v * ab;
  }
  
  const uniform float vb = d5 * d2 - d1 * d6;
  if (vb <= 0.f && d2 >= 0.f && d6 <= 0.f)
  {
      const uniform float v = d2 / (d2 - d6);
      return a + v * ac;
  }
  
  const uniform float va = d3 * d6 - d5 * d4;
  if (va <= 0.f && (d4 - d3) >= 0.f && (d5 - d6) >= 0.f)
  {
      const uniform float v = (d4 - d3) / ((d4 - d3) + (d5 - d6));
      return b + v * (c - b);
  }

  const uniform float denom = 1.f / (va + vb + vc);
  const uniform float v = vb * denom;
  const uniform float w = vc * denom;
  return a + v * ab + w * ac;
}