#
# Python script to create a color spline 
#
# Author: Alex V. Boreskoff <alexboreskoff@mtu-net.ru>, <steps3d@narod.ru>
#

import os, os.path, math, Image, PIL

						# this function takes a sorted set of (color,param) pairs, texture 
						# width and a filename of file where this texture must be saved
def colorspline ( data, width, fileName ):
	im    = Image.new ( "RGB", (width, 1) )
	n     = len ( data )
	start = 0
	end   = 1

	for i in range ( width ):		# process every pixel
									# locate a pair of adjacent data entries containing i
		x = float ( i ) / float ( width )

		if x > data [end][1]:
			start = end
			end   = end + 1

		if end >= n:
			end = start
			
		end = start + 1
		
		if end > n - 1:
			end = start
			
		c0 = data [start][0]
		c1 = data [end  ][0]
		t0 = float ( data [start][1] )
		t1 = float ( data [end  ][1] )
		t  = (x - t0) / (t1 - t0)

		r = int ( (1-t) * c0 [0] + t * c1 [0] + 0.5 )
		g = int ( (1-t) * c0 [1] + t * c1 [1] + 0.5 )
		b = int ( (1-t) * c0 [2] + t * c1 [2] + 0.5 )

		im.putpixel ( (i,0), (r, g, b) )

	ext = os.path.splitext ( fileName ) [1][1:]		# extract extension
	im.show ()
	im.save ( fileName, ext )


if __name__ == "__main__":
	print "Testing"
	dat = []
	dat.append ( ( ( 255, 255, 0  ), 0 ) )
	dat.append ( ( ( 255, 128, 10 ), 0.1 ) )
	dat.append ( ( ( 255, 0,   128), 0.2 ) )
	dat.append ( ( ( 255, 0,   128), 0.7 ) )
	dat.append ( ( ( 255, 0,   255), 1.0 ) )

	colorspline ( dat, 256, "spline.bmp" )
