# remap.py python 3.2 blender 2.57 r37243
# GPL2 license
# Author Dealga McArdle
import bpy
from mathutils import Vector
def remap(current, lower_old, upper_old, lower_new, upper_new):
'''
Remaps one range of values to another range of values, types must be float
arguments : Description
----------------------------------------------------------
current : Value to fit within the destination range
lower_old : Lowest value of the original range
upper_old : Highest value of the original range
lower_new : Lowest value of the destination range
upper_new : Highest value of the destination range
'''
# type checking, if any of the arguments are not float then return None.
lcheck = current, lower_old, upper_old, lower_new, upper_new
lstr = "current", "lower_old", "upper_old", "lower_new", "upper_new"
for i in range(len(lcheck)):
if lcheck[i].__class__ is not float:
print(lstr[i], "is not a float")
return None
# before calculations we can deal with some possible errors
if current <= lower_old: return lower_new
if current >= upper_old: return upper_new
# reusing a nicely coded Vector math utility :)
old_min = Vector((0.0, 0.0, lower_old))
old_max = Vector((0.0, 0.0, upper_old))
new_min = Vector((0.0, 0.0, lower_new))
new_max = Vector((0.0, 0.0, upper_new))
# calculate spread, fast and saves room!
spread_old = (old_max-old_min).length
spread_new = (new_max-new_min).length
factor_remap = spread_new / spread_old
current_vector = Vector((0.0, 0.0, current))
remap_temp = (current_vector-old_min).length
remapped = (remap_temp * factor_remap) + new_min[2]
# clamp output when rounding creates values beyond new range
if remapped < lower_new: return lower_new
if remapped > upper_new: return upper_new
# value seems alright!
return remapped
June 06, 2011
remap with input error checking
some thoughts on the remap function, this includes some invalid input checking.