X-Git-Url: http://de.git.xonotic.org/?a=blobdiff_plain;f=qcsrc%2Flib%2Fmath.qh;h=d8f19906a3eb26b1d9003e74f4493450f4b018d8;hb=7bdede86f899ea03fbf67bc1a367dd20390e113c;hp=8ba31516dda7fecffca459d112cbb4affaa92a76;hpb=67410278136b3bf6c5437027ab2f39d0da49753c;p=xonotic%2Fxonotic-data.pk3dir.git diff --git a/qcsrc/lib/math.qh b/qcsrc/lib/math.qh index 8ba31516d..d8f19906a 100644 --- a/qcsrc/lib/math.qh +++ b/qcsrc/lib/math.qh @@ -322,3 +322,25 @@ vector solve_quadratic(float a, float b, float c) } return v; } + +/// Maps values between the src and dest range: src_min to dest_min, src_max to dest_max, values between them +/// to the corresponding values between and extrapolates for values outside the range. +/// +/// src_min and src_max must not be the same or division by zero occurs. +/// +/// dest_max can be smaller than dest_min if you want the resulting range to be inverted, all values can be negative. +ERASEABLE +float map_ranges(float value, float src_min, float src_max, float dest_min, float dest_max) { + float src_diff = src_max - src_min; + float dest_diff = dest_max - dest_min; + float ratio = (value - src_min) / src_diff; + return dest_min + dest_diff * ratio; +} + +/// Same as `map_ranges` except that values outside the source range are clamped to min or max. +ERASEABLE +float map_bound_ranges(float value, float src_min, float src_max, float dest_min, float dest_max) { + if (value <= src_min) return dest_min; + if (value >= src_max) return dest_max; + return map_ranges(value, src_min, src_max, dest_min, dest_max); +}