##################################
#tree
#using Lsystem
#spring system
#bezier curve
##################################

#dependency
##################################
import math
import bezier, Lsystem, ball, spring
#from physik import *

#function
##################################

def build_L(chien,lon=15.0):
    stack = []
    a,b = ball.ball(250,510),ball.ball(250,490)
    ballLst = []
    springLst = [spring.new(a,b)]
    r = 0.0
    x,y = 250,490
    bezLst = []
    bezone = [a,b]
    for i in chien:
        if i == "+":
            r = r - (math.pi/7)
        elif i == "-":
            r = r + (math.pi/7)
        elif i == "[":
            stack.append((x,y,r,a,b))
            bezLst.append(bezone)
            bezone = [a,b]
        elif i == "]":
            x,y,r,a,b = stack.pop()
            bezLst.append(bezone)
            bezone = [a,b]
        elif (i=="F") or (i =="E"):
            y = y - (lon * math.cos(r))
            x = x + (lon * math.sin(r))
            c = ball.ball(x,y)
            ballLst.append(c)
            springLst.append(spring.new(c,b))
            springLst.append(spring.new(c,a))
            a = b
            b = c
            bezone.append(c)
    bezLst.append(bezone)
    return bezLst,ballLst,springLst


#test code
##################################
if __name__ == "__main__":
    import pyg

    tree = "X"
    rule = [("X" , "F-[[X]+X]+F[+FX]-X"), ("F" , "FF")]
    #~ tree = "E"
    #~ rule = [("F", "FF"), ("E", "F[+E]-E")]
    tree = "F"
    rule = [("F","F[-F]F[+F][F]")]
    tree = "F"
    rule = [("F","FF-[-F+F+F]+[+F-F-F]")]
    tree = "F"
    rule = [("F", "F[+F]F[-F]F")]

    for i in range(3):
        tree=Lsystem.iterate(tree,rule)
        print tree

    bezLst,ballLst,springLst = build_L(tree,15)
    windr = 0.0
    while pyg.main():
        for i in ballLst:
            ball.reset_force(i)
        for i in springLst:
            #pyg.line(i.b1.x, i.b1.y, i.b2.x, i.b2.y)
            spring.force(i)
        for i in ballLst:
            #pyg.circle(int(i.x),int(i.y))
            
            #gravity
            ball.gravity(i)
            ball.viscous_drag(i)
            ball.terminal_force(i)
            #wind
            #i.vx +=0.1
##            windr = math.fabs(math.pi/360)
            i.fx += 50
            ball.wall(i,pyg.width,pyg.height)
        for i in ballLst:
            ball.move(i)
            ball.terminal_velocity(i)
            
        for i in bezLst:
            n= []
            for p in i:
                n.append((p.x,p.y))
            for (x,y) in bezier.bezier(n):
                pyg.plot(x,y)


