12#include <Common/assertion.h>
13#include <Common/primitive_type.h>
24template<
typename To,
typename From, std::
size_t N>
25inline std::array<To, N>
sample_cast(
const std::array<From, N>& sample)
27 std::array<To, N> casted;
28 for(std::size_t i = 0; i < N; ++i)
30 casted[i] =
static_cast<To
>(sample[i]);
41inline bool pick(
const T pickProbability,
const T sample)
43 PH_ASSERT_IN_RANGE_INCLUSIVE(sample, T(0), T(1));
44 PH_ASSERT_IN_RANGE_INCLUSIVE(pickProbability, T(0), T(1));
46 return sample < pickProbability;
55 if(
pick(pickProbability, sample))
57 sample = pickProbability != T(0) ?
58 math::clamp(sample / pickProbability, T(0), T(1)) : sample;
65 PH_ASSERT_NE(pickProbability != T(1) ? (T(1) - pickProbability) : T(1), T(0));
67 sample = pickProbability != T(1) ?
68 math::clamp((sample - pickProbability) / (T(1) - pickProbability), T(0), T(1)) : sample;
79template<
typename T,
typename BitsType>
82 static_assert(CHAR_BIT == 8);
84 T normalizer =
static_cast<T
>(0);
85 if constexpr(std::is_same_v<BitsType, uint8>)
87 normalizer =
static_cast<T
>(0x1p-8);
89 else if constexpr(std::is_same_v<BitsType, uint16>)
91 normalizer =
static_cast<T
>(0x1p-16);
93 else if constexpr(std::is_same_v<BitsType, uint32>)
95 normalizer =
static_cast<T
>(0x1p-32);
97 else if constexpr(std::is_same_v<BitsType, uint64>)
99 normalizer =
static_cast<T
>(0x1p-64);
103 PH_STATIC_ASSERT_DEPENDENT_FALSE(T,
104 "No existing implementation can do `BitsType` -> sample type `T`.");
107 const T sample = bits * normalizer;
108 PH_ASSERT_IN_RANGE_INCLUSIVE(sample,
static_cast<T
>(0.0),
static_cast<T
>(1.0));
Miscellaneous math utilities.
Math functions and utilities.
Definition TransformInfo.h:10
T bits_to_sample(const BitsType &bits)
Converts input bits to a sample. For standard unsigned integral types, this is effectively normalizin...
Definition sample.h:80
bool pick(const T pickProbability, const T sample)
Randomly pick a branch with some probability.
Definition sample.h:41
std::array< To, N > sample_cast(const std::array< From, N > &sample)
Definition sample.h:25
bool reused_pick(const T pickProbability, T &sample)
Definition sample.h:50
T clamp(const T value, const T lowerBound, const T upperBound)
Clamps a value to [lowerBound, upperBound]. None of value, lowerBound and upperBound can be NaN,...
Definition math.h:77