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

#pragma once

#include "rkcommon/math/math.ih"

OSPRAY_BEGIN_ISPC_NAMESPACE

// input: importance in 'cdf'
// output: cdf of importance in 'cdf'
//         return sum
SYCL_EXTERNAL export uniform float Distribution1D_create(
    const uniform int size, uniform float *uniform cdf);

struct Sample1D
{
  int idx; // relative sample index to start
  float frac; // relative prosition of the random sample inside
              // the selected bin (useful for random sample re-using)
  float pdf; // the pdf of sampling the position idx+frac
             // when frac is sampled uniformly inside the idx^th bin
  float prob; // the probability of sampling the idx^th bin
};

inline Sample1D Distribution1D_sample(const uniform int size,
    const uniform float *uniform cdf,
    // we may sample different rows within one gang: use a varying offset
    // 'start' instead of a varying pointer 'cdf'
    const int start,
    const float s)
{
  // find minimum index where cdf[i-1] <= s < cdf[i]
  int first = start;
  int len = size;

  while (len > 0) {
    const int half = len >> 1;
    const int mid = first + half;
    if (s < cdf[mid]) {
      len = half;
    } else {
      first = mid + 1;
      len -= half + 1;
    }
  }

  Sample1D ret;
  ret.idx = first - start;
  const float bef = first == start ? 0.0f : cdf[first - 1];
  const float dpdf = cdf[first] - bef;
  ret.prob = dpdf;
  ret.pdf = dpdf * size;
  ret.frac = (s - bef) * rcp(dpdf); // rescale

  return ret;
}
OSPRAY_END_ISPC_NAMESPACE
