import Image
import random
import numarray

from numarray import *

class Point:
    xy = (0, 0)
    c = ( 255, 255, 255 );

    def __init__(self, xy, color):
        self.xy = xy
        self.c = color

    def midpoint(self, p2, buffer):
        tmpxy = array(self.xy) + (array(p2.xy) - array(self.xy))/2

        tmpc = buffer.data[buffer.dim[0] * tmpxy[1] + tmpxy[0]]
        
        if tmpc == None:
            s1 = random.random()
            s2 = 1.0 - s1

            dc = ((s1 * array(p2.c)) - (s2 * array(self.c))) / 2
            tmpc = array(self.c) + dc
            tmpc = ( int(tmpc[0]+.5), int(tmpc[1]+.5), int(tmpc[2]+.5) )

        return Point((tmpxy[0], tmpxy[1]), tmpc)

class Buffer:
    pass

# p1  s1  p2 
# s2  s3  s4
# p3  s5  p4
def draw(p1, p2, p3, p4, buffer):

    if p1.xy[0] + 1 >= p4.xy[0] and p1.xy[1] + 1 >= p4.xy[1]:
        buffer.data[buffer.dim[0] * p1.xy[1] + p1.xy[0]] = p1.c
        buffer.data[buffer.dim[0] * p2.xy[1] + p2.xy[0]] = p2.c
        buffer.data[buffer.dim[0] * p3.xy[1] + p3.xy[0]] = p3.c
        buffer.data[buffer.dim[0] * p4.xy[1] + p4.xy[0]] = p4.c
        return
 
    s1 = p1.midpoint(p2, buffer)
    s2 = p1.midpoint(p3, buffer)
    s3 = p1.midpoint(p4, buffer)
    s4 = p2.midpoint(p4, buffer)
    s5 = p3.midpoint(p4, buffer)

    draw (p1, s1, s2, s3, buffer)
    draw (s2, s3, p3, s5, buffer)
    draw (s1, p2, s3, s4, buffer)
    draw (s3, s4, s5, p4, buffer)

    return

(width, height) = 800, 800
img = Image.new("RGB", (width, height))

s = Point((0, 0), ( 255, 255, 0 ) )
t = Point((width-1, 0), ( 0, 255, 255 ) )
u = Point((0, height-1), ( 255, 0,   0 ) )
v = Point((width-1, height-1), ( 0,  110, 255 ) )

buf = Buffer()
buf.data = [None for x in range(height * width)]
buf.dim = (width, height)

draw(s, t, u, v, buf)

img.putdata(buf.data)
img.save("out.png", None)

