基于物理的渲染引擎
我写过的注释:
待分类…
Starting with C++11, the behavior of % has been specified to return a negative value or zero in this case, so that the identity (a/b)*b + a%b == a holds.
C++的Mod是可能取到负数的,要保证取模的结果一定是非负的,pbrt是这样实现的:
template <typename T> inline T Mod(T a, T b) { T result = a - (a/b) * b; return (T)((result < 0) ? result + b : result); }
浮点数也可以取模,使用std::fmod()(浮点数的取模规则是什么?)
如何计算前导0的位数:
有了以上的函数,那么整数取以2为底的对数,可以这样写:
inline int Log2Int(uint32_t v) { return 31 - __builtin_clz(v); }
判断一个数字是否是2的整数次方:
template <typename T> inline bool IsPowerOf2(T v) { return v && !(v & (v - 1)); }
将一个整数,向上取整到2的整数次方,比如511变成512:
inline int32_t RoundUpPow2(int32_t v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return v+1; }
计算尾部连续0的个数:
inline int CountTrailingZeros(uint32_t v) { return __builtin_ctz(v); }