00001 ## @package gradient 00002 # Functions for handling colour gradients. 00003 00004 from math import floor 00005 from enhanced_grid import Grid2D 00006 from image import mix_color 00007 00008 ## A gradient without any interpolation. 00009 class DiscreteGradient: 00010 def __init__(self, colors): 00011 self.colors = [] 00012 00013 for color in colors: 00014 self.colors.append(color) 00015 00016 self.color_count = len(colors) 00017 00018 def get_color(self, t): #assumes 0 <= t < 1 00019 col_index = int(floor(t * self.color_count)) 00020 00021 if (col_index >= self.color_count): 00022 col_index = self.color_count - 1 00023 00024 return self.colors[col_index] 00025 00026 ## A gradient between two colours with linear interpolation. 00027 class SimpleGradient: 00028 def __init__(self, color0, color1): 00029 self.color0 = color0 00030 self.color1 = color1 00031 00032 def get_color(self, t): 00033 return mix_color(self.color0, self.color1, t) 00034 00035 ## Maps a gradient to a grid, and returns the result as a new grid. 00036 # @grid A grid containing values in the range [0 1] 00037 def map_gradient(gradient, grid): 00038 color_grid = Grid2D(grid.dims) 00039 00040 for index in grid.index_iter(): 00041 color_grid[index] = gradient.get_color(grid[index]) 00042 00043 return color_grid