示例#1
0
def game_loop():
	speed = [10, 0]
	invader = Invader(width-48, height-48, "graphics/character/boss/boss1/InvaderA_00.png", "graphics/character/boss/boss1/InvaderA_01.png", "graphics/character/boss/boss1/InvaderA_01.png", speed)

	# Idem, on cree notre hero en tant qu'objet MyHero
	my_hero = MyHero(width/2, height/2, "graphics/character/hero/heror.png", "graphics/character/hero/herowr.png", "graphics/character/hero/hero.png")

	# Boucle de jeu
	while 1:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()

		# Deplacement
		invader.movement(width, height)
		my_hero.movement(width, height)

		# Test de collision
		# On utilise 'collidepoint', qui test si le centre de
		# My_Hero est convenu dans le rectangle de l'Invader
		if invader.get_rect().colliderect(my_hero.get_rect()):
			display_game_over(screen, background_image, background_position)
			sys.exit()
		else:
			# Affichage
			display(screen, background_image, background_position, invader, my_hero)
示例#2
0
def parse_file( fname, points, transform, screen, color ):
    f = open( fname )
    data = f.read()
    data = data.split("\n")
    i = 0
    while i < len(data):
        if data[i] == "line":
            param = data[i+1].split(' ')
            add_edge( points, float(param[0]), float(param[1]), float(param[2]), float(param[3]), float(param[4]), float(param[5]) )
            i += 2
        elif data[i] == "circle":
            param = data[i+1].split(' ')
            add_circle( points, float(param[0]), float(param[1]), 0, float(param[2]), 1 )
            i += 2
        elif data[i] == "hermite":
            param = data[i+1].split(' ')
            add_curve( points, float(param[0]), float(param[1]), float(param[2]), float(param[3]), float(param[4]), float(param[5]), float(param[6]), float(param[7]), 0.001, "hermite" )
            i += 2
        elif data[i] == "bezier":
            param = data[i+1].split(' ')
            add_curve( points, float(param[0]), float(param[1]), float(param[2]), float(param[3]), float(param[4]), float(param[5]), float(param[6]), float(param[7]), 0.001, "bezier" )
            i += 2
        elif data[i] == "xrotate":
            param = data[i+1]
            trans = make_rotX(math.radians(float(param)))
            matrix_mult(trans, transform)
            i += 2
        elif data[i] == "yrotate":
            param = data[i+1]
            trans = make_rotY(math.radians(float(param)))
            i += 2
        elif data[i] == "zrotate":
            param = data[i+1]
            trans = make_rotZ(math.radians(float(param)))
            i += 2
        elif data[i] == "ident":
            ident( transform )
        elif data[i] == "apply":
            matrix_mult( transform, points )
        elif data[i] == "scale":
            param = data[i+1].split( " " )
            m = make_scale(float(prama[0]), float(param[1]), float(param[2]), transform )
            matrix_mult( m, transform )
        elif data[i] == "translate":
            param = data[i+1].split(' ')
            matrix_mult( make_translate(float(param[0]), float(param[1]), float(param[2]), transform ) )
        elif data[i] == "display":
            clear_screen(screen)
            draw_lines(points, screen, color)
            display( screen )
            i += 1
        elif data[i] == "save":
            fname = data[i+1]
            save_ppm( screen, fname )
            i += 2
        elif data[i] == "quit":
            return

        else:
            print ""
示例#3
0
def parse_file( fname, points, transform ):
	f = open(fname, 'r')
	screen = new_screen()
	while 1:
		l = f.readline()
		if len(l) == 0:
			break
		if l[0] == 'l':
			s = map(float, f.readline().split(' '))
			add_edge(points, s[0], s[1], s[2], s[3], s[4], s[5])
		elif l[0] == 'i':
			transform = ident(transform)
		elif l[0] == 's':
			s = map(float, f.readline().split(' '))
			transform = matrix_mult(make_scale(s[0], s[1], s[2]), transform)
		elif l[0] == 't':
			s = map(float, f.readline().split(' '))
			transform = matrix_mult(make_translate(s[0], s[1], s[2]), transform)
		elif l[0] == 'x' or l[0] == 'y' or l[0] == 'z':
			func = [make_rotX, make_rotY, make_rotZ][ord(l[0])-ord('x')]
			s = float(f.readline())
			transform = matrix_mult(func(s*math.pi / 180.0), transform)
		elif l[0] == 'a':
			points = matrix_mult(points, transpose(transform))
		elif l[0] == 'v':
		#	print points
			draw_lines(points, screen, [255, 255, 255])
			display(screen)
		elif l[0] == 'g':
			s = f.readline().strip()
			draw_lines(points, screen, [255, 255, 255])
			save_extension(screen, s)
			clear_screen(screen)
示例#4
0
def parse_file( fname, points, transform ):
    transform = ident(new_matrix())
    screen = new_screen()
    f=open(fname)
    lines = f.read().split('\n')
    n = 0

    #******* IMPORTANT NOTE ***********#

    # I have note gotten image magic to work (there is a piazza question evidencing this)
    # As a result, I have created an alternative where i just create a new image, from 0 to n, each time a or v is entered. I will try and fix my problems (with image magic, not the ones stemming from divorce and an uninterested mother) 

    
    for  i in range(0,len(lines)):
        line= lines[i]
        line.strip()

        i = i + 1
        #print_matrix(transform)
        
        if line == "l":
            p = lines[i].split(' ')
            for x in range(0,len(p)):
                p[x]=int(p[x])
            add_edge(points,p[0],p[1],p[2],p[3],p[4],p[5])
        elif line == "s":
            args = lines[i].split(' ')
            r = make_scale(float(args[0]),float(args[1]),float(args[2]))
            transform = matrix_mult(r,transform)
        elif line == "t":
            args = lines[i].split(' ')
            r = make_translate(float(args[0]),float(args[1]),float(args[2]))
            transform = matrix_mult(r,transform)
        elif line == "x":
            arg = lines[i]
            r = make_rotX(int(arg))
            transform = matrix_mult(r,transform)
        elif line == "y":
            arg = lines[i]
            r = make_rotY(int(arg))
            transform = matrix_mult(r,transform)
        elif line == "z":
            arg = lines[i]
            r = make_rotZ(int(arg))
            transform = matrix_mult(r,transform)
        elif line == "g":
            #save_extension(screen,lines[i])
            display(screen, str(n))
            n = n+1
        else:
            i = i - 1
            if line == "i":
                transform = ident(transform)
            elif line == "a":
                points = matrix_mult(transform,points)
            elif line == "v":
                clear_screen(screen)
                draw_lines( points, screen, [255,0,0] )
                display(screen, str(n))
                n = n+1
示例#5
0
def parse_file( fname, points, transform ):
    data = open(fname, 'r')
    data = data.read()
    data = data.splitlines()
    screen = new_screen()
    color = [0, 0, 255]
    for x in data:
        if (data[x] == 'l'):
            p = data[i+1].split()
            add_edge(points, float(p[0]), float(p[1]), float(p[2]), float(p[3]), float(p[4]), float(p[5]))
	elif (data[x] == 'i'):
            transform = ident()
        elif (data[x] == 's'):
            p = data[x+1].split()
            transform = matrix_mult(make_scale(float(p[0]), float(p[1]), float(p2[0])), transform)
        elif (data[x] == 't'):
            p = data[x+1].split()
            transform = matrix_mult(make_translate(float(p[0]), float(p[1]), float(p[2])), transform)
        elif (data[x] == 'x'):
            transform = matrix_mult(make_rotX(float(data[x+1])), transform)
        elif (data[x] == 'y'):
            transform = matrix_mult(make_rotY(float(data[x+1])), transform)
        elif (data[x] == 'z'):
            transform = matrix_mult(make_rotZ(float(data[x+1])), transform)
        elif (data[x] == 'a'):
            points = matrix_mult(transform, points)
        elif (data[x] == 'v'):
            draw_lines(points, screen, color)
            display(screen)
            clear_screen(screen)
        elif (data[x] == 'g'):
            draw_lines(points, screen, color)
            display(screen)
        else:
示例#6
0
def run(filename):
    """
    This function runs an mdl script
    """
    color = [255, 255, 255]
    tmp = new_matrix()
    ident(tmp)
    p = mdl.parseFile(filename)
    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    stack = [ tmp ]
    screen = new_screen()
        
    for command in commands:
        #print command
        matrix = []
        if command[0] == "push":
            stack.append(copy.deepcopy(stack[-1]))
        elif command[0] == "pop":
            stack.pop()
        elif command[0] == "line":
            add_edge(matrix, command[1],command[2],command[3],command[4], command[5],command[6])
            draw_lines( matrix, screen, color )
            matrix=[];
        elif command[0] in ["sphere","box","torus"]:
            if command[0] == "sphere":
                add_sphere(matrix,command[1],command[2],command[3],command[4],5)
            elif command[0] == "box":
                add_box(matrix, command[1],command[2],command[3],command[4], command[5],command[6])
            else:
                add_torus(matrix, command[1],command[2],command[3],command[4], command[5],5)
            matrix_mult(stack[-1],matrix)
            draw_polygons( matrix, screen, color )
            matrix=[];
        elif command[0] in ["move","scale","rotate"]:
            if command[0] == "move":
                t= make_translate(command[1],command[2],command[3])
            elif command[0] == "scale":
                t = make_scale(command[1],command[2],command[3])
            else:
                r = command[2]*(math.pi/180.0)
                if command[1] == "x":
                    t = make_rotX(r)
                elif command[1] == "y":
                    t = make_rotY(r)
                elif command[1] == "z":
                    t = make_rotZ(r)
            matrix_mult(stack[-1],t)
            stack[-1]=t
        elif command[0] == "display":
            display( screen )
        elif command[0] == "save":
            save_extension( screen, command[1] )
示例#7
0
def parse_file( fname, points, transform ):
    f = open(fname, 'r')
    file = f.readlines()
    #print file
    f.close()

    i = 0
    while (i<len(file)):
        line = file[i].strip('\n')
        if line == 'g':
            draw_lines(points, screen, color)
            save_extension(screen, file[i+1].strip('\n'))
            i += 2
        elif line == 'a':
            matrix_mult(transform, points)
            i += 1
        elif line == 'v':
            draw_lines(points, screen, color)
            display(screen)
            i += 1
        elif line == 'l':
            pts = file[i+1].strip('\n').split(" ")
            add_edge(points,
                     float(pts[0]),
                     float(pts[1]),
                     float(pts[2]),
                     float(pts[3]),
                     float(pts[4]),
                     float(pts[5]))
            i += 2
        elif line == 's':
            ps = file[i+1].strip('\n').split(" ")
            s = make_scale(float(ps[0]), float(ps[1]), float(ps[2]))
            transform = matrix_mult(s, transform)
            i += 2
        elif line == 't':
            ps = file[i+1].strip('\n').split(" ")
            t = make_translation(float(ps[0]), float(ps[1]), float(ps[2]))
            transform = matrix_mult(t, transform)
            i+=2
        elif line == 'x':
            theta = file[i+1].strip('\n')
            x = make_rotX(theta)
            transform = matrix_mult (x, transform)
            i += 2
        elif line == 'y':
            theta = file[i+1].strip('\n')
            y = make_rotY(theta)
            transform = matrix_mult (y, transform)
            i += 2
        elif line == 'z':
            theta = file[i+1].strip('\n')
            z = make_rotZ(theta)
            transform = matrix_mult(z, transform)
            i += 2
        else:
            i += 1
示例#8
0
def parse_file( fname, points, transform, screen, color ):
    filer = open(fname, 'r')
    data = filer.read()
    filer.close()
    lines = data.split("\n")
    counter = 0
    while counter < len(lines):
        print lines[counter]
        if lines[counter] == "line":
            counter += 1
            parameters = lines[counter].split(" ")
            add_edge(points, int(parameters[0]), int(parameters[1]), int(parameters[2]), int(parameters[3]), int(parameters[4]), int(parameters[5]))
        elif lines[counter] == "circle" or lines[counter] == "c":
            counter += 1
            parameters = lines[counter].split(" ")
            add_circle(points, int(parameters[0]), int(parameters[1]), 0, int(parameters[2]), 64)
        elif lines[counter] == "hermite" or lines[counter] == "h":
            counter += 1
            parameters = lines[counter].split(" ")
            add_curve(points, int(parameters[0]), int(parameters[1]), int(parameters[2]), int(parameters[3]), int(parameters[4]), int(parameters[5]), int(parameters[6]), int(parameters[7]), 32, 0)
        elif lines[counter] == "bezier" or lines[counter] == "b":
            counter += 1
            parameters = lines[counter].split(" ")
            add_curve(points, int(parameters[0]), int(parameters[1]), int(parameters[2]), int(parameters[3]), int(parameters[4]), int(parameters[5]), int(parameters[6]), int(parameters[7]), 32, 1)
        elif lines[counter] == "ident":
            ident(transform)
        elif lines[counter] == "scale":
            counter += 1
            parameters = lines[counter].split(" ")
            matrix_mult(make_scale(float(parameters[0]), float(parameters[1]), float(parameters[2])), transform)
        elif lines[counter] == "translate":
            counter += 1
            parameters = lines[counter].split(" ")
            matrix_mult(make_translate(int(parameters[0]), int(parameters[1]), int(parameters[2])), transform)
        elif lines[counter] == "xrotate":
            counter += 1
            matrix_mult(make_rotX(int(lines[counter])), transform)
        elif lines[counter] == "yrotate":
            counter += 1
            matrix_mult(make_rotY(int(lines[counter])), transform)
        elif lines[counter] == "zrotate":
            counter += 1
            matrix_mult(make_rotZ(int(lines[counter])), transform)
        elif lines[counter] == "apply":
            matrix_mult(transform, points)
        elif lines[counter] == "display":
            color = [0, 255, 0]
            screen = new_screen()
            draw_lines(points, screen, color)
            display(screen)
        elif lines[counter] == "save":
            counter += 1
            save_extension(screen, lines[counter])
        else:
            print "Invalid command: " + lines[counter]
        counter += 1
示例#9
0
def parse_file( fname, points, transform ):
    f = open(fname,"r")
    lines = f.readlines()
    f.close()
    i = 0
    while i < len(lines):
        l = lines[i].replace("\n","")
        if l == "l":
            coor = lines[i+1].replace("\n","").split(" ")
            coor = [float(q) for q in coor]
            add_edge(points, coor[0], coor[1], coor[2], coor[3], coor[4], coor[5])
        elif l == "c":
            values = [float(q) for q in lines[i+1].replace("\n","").split(" ")]
            add_circle(points, values[0], values[1], 0, values[2], 0.01)
        elif l == "h":
            values = [float(q) for q in lines[i+1].replace("\n","").split(" ")]
            add_curve(points,values[0],values[1],values[2],values[3],values[4],
                      values[5],values[6],values[7],0.01,"hermite")
        elif l == "b":
            values = [float(q) for q in lines[i+1].replace("\n","").split(" ")]
            add_curve(points,values[0],values[1],values[2],values[3],values[4],
                      values[5],values[6],values[7],0.01,"bezier")
        elif l == "i":
            ident(transform)
        elif l == "s":
            values = lines[i+1].replace("\n","").split(" ")
            values = [float(q) for q in values]
            matrix_mult(make_scale(values[0], values[1], values[2]),transform)
        elif l == "t":
            values = lines[i+1].replace("\n","").split(" ")
            values = [float(q) for q in values]
            matrix_mult(make_translate(values[0], values[1], values[2]),transform)
        elif l == "x":
            theta = float(lines[i+1].replace("\n",""))
            matrix_mult(make_rotX(theta),transform)
        elif l == "y":
            theta = float(lines[i+1].replace("\n",""))
            matrix_mult(make_rotY(theta),transform)
        elif l == "z":
            theta = float(lines[i+1].replace("\n",""))
            matrix_mult(make_rotZ(theta),transform)
        elif l == "a":
            matrix_mult(transform,points)
        elif l == "v":
            screen = new_screen()
            draw_lines(points, screen, color)
            display(screen)
        elif l == "g":
            fname = lines[i+1].replace("\n","")
            screen = new_screen()
            draw_lines(points, screen, color)
            save_ppm(screen, fname)
        i += 1
示例#10
0
def run(filename):
    color = [255, 255, 255]
    tmp = new_matrix()
    ident( tmp )

    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    stack = [ tmp ]
    screen = new_screen()
        
    for command in commands:
        points = []
        print command
        cmd = command[0]
        args = command[1:]
        top = stack[-1]
        if cmd == "push":
            stack.append(copy.deepcopy(top))
        elif cmd == "pop":
            stack.pop()
        elif cmd in ["move","rotate","scale"]:
            if cmd == "move":
                x = make_translate(args[0], args[1], args[2])
            elif cmd == "rotate":
                x = get_rot(args[0],args[1]*(math.pi/180))
            elif cmd == "scale":
                x = make_scale(args[0], args[1], args[2])
            matrix_mult(top, x)
            stack[-1] = x
        elif cmd in ["box","sphere","torus"]:
            if cmd == "box":
                add_box(points, args[0], args[1], args[2], args[3], args[4], args[5])
            elif cmd == "sphere":
                add_sphere(points, args[0], args[1], args[2], args[3], 5)
            elif cmd == "torus":
                add_torus(points, args[0], args[1], args[2], args[3], args[4], 5)
            matrix_mult(top, points)
            draw_polygons(points, screen, color)
        elif cmd == "line":
            add_edge(points, args[0], args[1], args[2], args[3], args[4], args[5])
            matrix_mult(top, points)
            draw_lines(points, screen, color)
        elif cmd == "save":
            save_extension(screen, args[0])
        elif cmd == "display":
            display(screen)
示例#11
0
文件: parser.py 项目: esqu1/graphics
def parse_file( fname, points, transform, screen, color ):
    f = open(fname, 'r').read()
    l = f.split('\n')
    i = 0
    while i < len(l):
        cmd = l[i].strip()
        print cmd
        if cmd in commands:
            i += 1
            args = l[i].split()
            j = 0
            while j < len(args):
                args[j] = float(args[j])
                j+= 1
            if cmd == 'line':
                add_edge( points, args[0], args[1], args[2], args[3], args[4], args[5] )
            elif cmd == 'circle':
                add_circle( points, args[0], args[1], 0, args[2], 0.01 )
            elif cmd == 'hermite':
                add_curve( points, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], 0.01, HERMITE )
            elif cmd == 'bezier':
                add_curve( points, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], 0.01, BEZIER )
            elif cmd == 'scale':
                matrix_mult(make_scale(args[0], args[1], args[2]), transform)
            elif cmd == 'translate':
                matrix_mult(make_translate(args[0], args[1], args[2]), transform)
            elif cmd == 'xrotate':
                matrix_mult(make_rotX(args[0]), transform)
            elif cmd == 'yrotate':
                matrix_mult(make_rotY(args[0]), transform)
            elif cmd == 'zrotate':
                matrix_mult(make_rotZ(args[0]), transform)
        else:
            if cmd == 'ident':
                ident(transform)
            elif cmd == 'apply':
                matrix_mult(transform,points)
            elif cmd == 'display':
                screen = new_screen()
                draw_lines( points, screen, color )
                display(screen)
            elif cmd == 'save':
                screen = new_screen()
                draw_lines( points, screen, color )
                i += 1
                out = l[i]
                save_extension(screen,out)
            elif cmd[0] == '#':
                pass
            else:
                print "Invalid command."
        i += 1
示例#12
0
def parse_file( filename, points, transform ):
    screen = new_screen()
    f = open(filename, 'r')

    while 1:
        l = f.readline()
        if len(l) == 0:
            break
        elif l[0] == 'l':
            s = map(float, f.readline().split(' '))
            add_edge(points, s[0],s[1],s[2],s[3],s[4],s[5])
        elif l[0] == 'i':
            transform = ident(transform)
        elif l[0] == 's':
            s = map(float, f.readline().split(' '))
            transform = matrix_mult(scale(s[0],s[1],s[2]),transform)
        elif l[0] == 't':
            s = map(float, f.readline().split(' '))
            transform = matrix_mult(translate(s[0],s[1],s[2]),transform)
        elif l[0] == 'x':
            s = map(float, f.readline().split(' '))
            transform = matrix_mult(rotateX(s[0]),transform)
        elif l[0] == 'y':
            s = map(float, f.readline().split(' '))
            transform = matrix_mult(rotateY(s[0]),transform)
        elif l[0] == 'z':
            s = map(float, f.readline().split(' '))
            transform = matrix_mult(rotateZ(s[0]),transform)
        elif l[0] == 'a':
            points = matrix_mult(points, transform)
        elif l[0] == 'v':
            screen = new_screen()
            draw_lines(points, screen, [255,255,255])
            display(screen)
        elif l[0] == 'g':
            s = f.readline().split()
            draw_lines(points, screen, [255,255,255])
            save_extension(screen, s)
            clear_screen(screen)
        elif l[0] == 'c':
            s = map(float, f.readline().split(' '))
            addCircle(points, s[0], s[1], 0, s[2], .01)
        elif l[0] == 'b':
            s = map(float, f.readline().split(' '))
            print s
            addCurve(points, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7],
                     .01, "bezier")
        elif l[0] == 'h':
            s = map(float, f.readline().split(' '))
            addCurve(points, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7],
                     .01, "hermite")
示例#13
0
def run(filename):
    """
    This function runs an mdl script
    """

    p = mdl.parseFile(filename)
    
    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    for command in commands:
        cmd = command[0]
        if cmd == "push":
            stack.append(copy.deepcopy(stack[len(stack)-1]))
        if cmd == "pop":
            stack.pop()
        if cmd == "move":
            mult(make_translate(command[1], command[2], command[3]))
        if cmd == "rotate":
            t = command[2]*math.pi/180
            axis = command[1]
            if axis == 'x':
                mult(make_rotX(t))
            if axis == 'y':
                mult(make_rotY(t))
            if axis == 'z':
                mult(make_rotZ(t))
        if cmd == "scale":
            mult(make_scale(command[1], command[2], command[3]))
        if cmd in ["box", "sphere", "torus"]:
            polygons = []
            if cmd == "box":
                add_box(polygons, command[1],command[2],command[3],command[4],command[5],command[6])
            if cmd == "sphere":
                add_sphere(polygons, command[1],command[2],command[3],command[4],5)
            if cmd == "torus":
                add_torus(polygons, command[1],command[2],command[3],command[4],command[5],5)
            matrix_mult(stack[len(stack)-1], polygons)
            draw_polygons(polygons, screen, color)
        if cmd == "line":
            points = []
            add_edge(points, command[1],command[2],command[3],command[4],command[5],command[6])
            matrix_mult(stack[len(stack)-1], points)
            draw_lines(polygons, screen, color)
        if cmd == "save":
            save_extension(screen, cmd[1])
        if cmd == "display":
            display(screen)
示例#14
0
def run(filename):
    """
    This function runs an mdl script
    """
    color = [255, 255, 255]
    tmp = new_matrix()
    ident( tmp )

    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    stack = [ tmp ]
    screen = new_screen()

    for command in commands:
        print command
        points = []
        cmd = command[0]
        arg = command[1:]
        if cmd == "push":
            stack.append(copy.deepcopy(stack[-1]))
        elif cmd == "pop":
            stack.pop()
        elif cmd in ["move", "rotate", "scale"]:
            if cmd == "move":
                matrix = make_translate(arg[0], arg[1], arg[2])
            elif cmd == "rotate":
                matrix = make_rot(arg[0], arg[1]*(math.pi/180))
            else:
                matrix = make_scale(arg[0], arg[1], arg[2])
            matrix_mult(stack[-1], matrix)
            stack[-1] = matrix
        elif cmd in ["box", "sphere", "torus"]:
            if cmd == "box":
                add_box(points, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5])
            elif cmd == "sphere":
                add_sphere(points, arg[0], arg[1], arg[2], arg[3], 5)
            else:
                add_torus(points, arg[0], arg[1], arg[2], arg[3], arg[4], 5)
            matrix_mult(stack[-1], points)
            draw_polygons(points, screen, color)
        elif cmd == "save":
            save_extension(screen, arg[0])
        elif cmd == "display":
            display(screen)
示例#15
0
def parse_file( fname, points, transform ):
    screen = new_screen()
    color = [ 0, 255, 0 ]
    f = open(fname, "r")
    line = f.readline().strip()
    while line:
        if line == "l":
            p = []
            for x in f.readline().strip().split(' '):
                p.append(int(x))
            add_edge(points, p[0], p[1], p[2], p[3], p[4], p[5])
        elif line == "i":
            for x in range(4):
                for y in range(4):
                    transform[x][y] = 0
                transform[x][x] = 1
        elif line == "s":
            p = []
            for x in f.readline().strip().split():
                p.append(float(x))
            for n in range(3):
                transform[n][n] *= p[n]
        elif line == "t":
            p = []
            for x in f.readline().strip().split():
                p.append(int(x))
            for n in range(3):
                transform[3][n] += p[n]
                
        elif line == "x":
            transform = rotate("x", f.readline().strip(), points,  transform)
        elif line == "y":
            transform = rotate("y", f.readline().strip(), points,  transform)
        elif line == "z":
            transform = rotate("z", f.readline().strip(), points,  transform)
        elif line == "a":
            #print "transform: "
            #print_matrix(transform)
            points = mult(points, transform, True)
        elif line == "v":
            clear_screen(screen)
            draw_lines( points, screen, color )
            display(screen)
        elif line == "g":
            save_ppm(screen, f.readline().strip().strip())
            display(screen)
        line = f.readline().strip()
        #print_matrix( points)
    f.close()
示例#16
0
def parse_file(fname, points, matrix):
    f = open(fname, "r")
    script = f.read()
    # read in each line and parse and do specific transformation
    commands = script.split("\n")
    line = 0
    length = len(commands)
    master = ident(new_matrix())
    while line < length:
        if commands[line] == "":
            line += 1
        # six arguments all in one list
        if commands[line] in "lstxyzg":
            ele = commands[line + 1].split()
            if commands[line] == "l":
                add_edge(points, ele[0], ele[1], ele[2], ele[3], ele[4], ele[5])

            # three arguments all in one list
            elif commands[line] == "s":
                master = matrix_mult(master, make_scale(float(ele[0]), float(ele[1]), float(ele[2])))
            elif commands[line] == "t":
                master = matrix_mult(master, make_translate(float(ele[0]), float(ele[1]), float(ele[2])))
            elif commands[line] == "x":
                master = matrix_mult(master, make_rotX(float(ele[0])))
            elif commands[line] == "y":
                master = matrix_mult(master, make_rotY(float(ele[0])))
            elif commands[line] == "z":
                master = matrix_mult(master, make_rotZ(float(ele[0])))
            elif commands[line] == "g":
                el = ele[0]  # ele.split(".")[0] + "."
                screen = new_screen()
                draw_lines(points, screen, randcolor())
                save_extension(screen, el)

            line += 2
        # one argument-> as in one element in the list
        else:
            if commands[line] == "i":
                master = ident(master)
            elif commands[line] == "a":
                points = matrix_mult(master, points)
                master = ident(master)
            elif commands[line] == "v":
                screen = new_screen()
                draw_lines(points, screen, randcolor())
                display(screen)

            line = line + 1
示例#17
0
def parse_file( fname, points, transform ):
    screen = new_screen()
    color = [255, 255, 255]
    f = open(fname) 
    commands = [c.strip('\n') for c in f.readlines()]
    for i in range(len(commands)):
        c = commands[i]
        if c[0] in ('l','s','t','x','y','z'):

            args = commands[i+1].split()
            for i in range(len(args)):
                if '.' in args[i]:
                    args[i] = float(args[i])
                else:
                    args[i] = int(args[i])

            if c[0] == 'l':
                add_edge(points,*args)
            else:
                if c[0] == 's':
                    m = make_scale(*args)
                elif c[0] == 't':
                    m = make_translate(*args)
                elif c[0] == 'x':
                    m = make_rotX(*args)
                elif c[0] == 'y':
                    m = make_rotY(*args)
                elif c[0] == 'z':
                    m = make_rotZ(*args)
                
                transform = matrix_mult(m,transform)
                
        elif c[0] == 'g':  
            fname = commands[i+1]
            draw_lines(points, screen, color)
            save_extension(screen, fname)

        elif c[0] == 'i':
            transform = ident(transform)

        elif c[0] == 'a':
            points = matrix_mult(transform, points)
            
        elif c[0] == 'v':
            screen = new_screen()
            draw_lines(points, screen, color)
            display(screen)
示例#18
0
def game_loop():
    #declaration du personnage
    my_hero = MyHero(200, 200, "data/char_hero/face_hero.jpg", "data/char_hero/latD_hero.jpg", "data/char_hero/latG_hero.jpg")
# Boucle de jeu
    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                os._exit(1)

        #######################################################################
        #instruction de jeu
        #######################################################################
        # mouvement des entitées
        my_hero.movement()
        #affichage de la fenetre
        # Affichage
        display(screen, background_image, background_position,my_hero)
示例#19
0
文件: parser.py 项目: JaredBeh/curve
def parse_file( fname, points, transform, screen, color ):
    f = open(fname,'r')
    text = f.read()
    lines = text.split('\n')
    n = 0
    while(n < len(lines)):
        if(lines[n] == "ident"):
            ident(transform)
        elif(lines[n] == "apply"):
            matrix_mult(transform,points)
        elif(lines[n] == "display"):
            clear_screen(screen)
            draw_lines(points,screen,color)
            display(screen)
        else:
            func = lines[n]
            n += 1
            argstring = lines[n].split(' ')
            args = map(float,argstring)
            argsint = map(int,args)
            if(func == "scale"):
                matrix_mult(make_scale(args[0],args[1],args[2]),transform)
            elif(func == "translate"):
                matrix_mult(make_translate(args[0],args[1],args[2]),transform)
            elif(func == "xrotate"):
                matrix_mult(make_rotX(args[0]),transform)
            elif(func == "yrotate"):
                matrix_mult(make_rotY(args[0]),transform)
            elif(func == "zrotate"):
                matrix_mult(make_rotZ(args[0]),transform)
            elif(func == "line"):
                add_edge(points,argsint[0],argsint[1],argsint[2],argsint[3],argsint[4],argsint[5])
            elif(func == "circle"):
                add_circle(points,argsint[0],argsint[1],0,argsint[2],STEP)
            elif(func == "hermite"):
                add_curve(points,argsint[0],argsint[1],argsint[2],argsint[3],
                          argsint[4],argsint[5],argsint[6],argsint[7],
                          STEP,HERMITE)
            elif(func == "bezier"):
                add_curve(points,argsint[0],argsint[1],argsint[2],argsint[3],
                          argsint[4],argsint[5],argsint[6],argsint[7],
                          STEP,BEZIER)
            elif(func == "save"):
                save_ppm(screen,argstring[0])
        n += 1
    f.close()
示例#20
0
文件: parser.py 项目: MGRiv/CurveHW
def parse_file( fname, points, transform, screen, color ):
    f = open(fname, 'r')
    r = f.read()
    l = r.split('\n')
    c = 0
    while(c < len(l)):
        print str(c + 1) +"\n"
        if(l[c] == "ident"):
            ident(transform)
        elif(l[c] == "apply"):
            matrix_mult(transform,points)
        elif(l[c] == "display"):
            clear_screen(screen)
            draw_lines(points,screen,color)
            display(screen)
        else:
            c += 1
            t = l[c].split(' ')
            if(l[c - 1] == "line"):
                add_edge(points,int(t[0]),int(t[1]),int(t[2]),int(t[3]),int(t[4]),int(t[5]))
            elif(l[c - 1] == "circle"):
                add_circle(points,int(t[0]),int(t[1]),0,int(t[2]),0.02)
            elif(l[c - 1] == "hermite"):
                add_curve(points,int(t[0]),int(t[1]),int(t[2]),int(t[3]),int(t[4]),int(t[5]),int(t[6]),int(t[7]),0.02,0)
            elif(l[c - 1] == "bezier"):
                add_curve(points,int(t[0]),int(t[1]),int(t[2]),int(t[3]),int(t[4]),int(t[5]),int(t[6]),int(t[7]),0.02,1)
            elif(l[c - 1] == "scale"):
                q = make_scale(float(t[0]),float(t[1]),float(t[2]))
                matrix_mult(q,transform)
            elif(l[c - 1] == "translate"):
                q = make_translate(int(t[0]),int(t[1]),int(t[2]))
                matrix_mult(q,transform)
            elif(l[c - 1] == "xrotate"):
                q = make_rotX(float(t[0]))
                matrix_mult(q,transform)
            elif(l[c - 1] == "yrotate"):
                q = make_rotY(float(t[0]))
                matrix_mult(q,transform)
            elif(l[c - 1] == "zrotate"):
                q = make_rotZ(float(t[0]))
                matrix_mult(q,transform)
            elif(l[c - 1] == "save"):
                save_ppm(screen,t[0])
        c+=1
    f.close()    
示例#21
0
def parse_file( fname, points, transform ):
	f = open(fname, 'r')
	screen = new_screen()
	while 1:
		l = f.readline()
		if len(l) == 0:
			break
		if l[0] in 'lchbpmdstxyz':
			s = map(float, f.readline().split(' '))
		if l[0] == 'l':
			add_edge(points, *s)
		elif l[0] == 'c':
			add_circle(points, *s)
		elif l[0] == 'h':
			add_hermite(points, *s)
		elif l[0] == 'b':
			add_bezier(points, *s)
		elif l[0] == 'p':
			add_prism(points, *s)
		elif l[0] == 'm':
			add_sphere(points, *s)
		elif l[0] == 'd':
			add_torus(points, *s)
		elif l[0] == 'i':
			transform = ident(transform)
		elif l[0] == 's':
			transform = matrix_mult(make_scale(*s), transform)
		elif l[0] == 't':
			transform = matrix_mult(make_translate(*s), transform)
		elif l[0] == 'x' or l[0] == 'y' or l[0] == 'z':
			func = [make_rotX, make_rotY, make_rotZ][ord(l[0])-ord('x')]
			transform = matrix_mult(func(s[0]*math.pi / 180.0), transform)
		elif l[0] == 'a':
			points = matrix_mult(points, transpose(transform))
		elif l[0] == 'w':
			points = []
		elif l[0] == 'v':
			draw_lines(points, screen, [255, 255, 255])
			display(screen)
		elif l[0] == 'g':
			s = f.readline().strip()
			draw_lines(points, screen, [255, 255, 255])
			save_extension(screen, s)
			clear_screen(screen)
示例#22
0
def parse_file( fname, points, transform ):
	screen = new_screen()
	with open(fname) as script:
		for line in script:
			line = line[:-1]

			if not line.replace(" ","").isdigit():	
				comm = line.strip()
				if comm == 'i':
					transform = ident(points)
				elif comm == 'a':
					points = matrix_mult(transform, points)
					transform = ident(transform)
				elif comm == 'v':
					clear_screen(screen)
					draw_lines(points, screen, [0,225,0])
					display(screen)
					sleep(0.5)
				elif comm == 'q':
					return
			else:
				args = [float(x) for x in line.split()]
				if comm == 'l':
					# params = [points].extend([x for x in args])
					add_edge(points, *[x for x in args])
				elif comm == 'i':
					transform = ident(points)
				elif comm == 's':
					transform = trans(make_scale, transform)
				elif comm == 't':
					transform = trans(make_translate, transform)
				elif comm == 'x':
					args = [deg2rad(x) for x in args]
					transform = trans(make_rotX, transform)	
				elif comm == 'y':
					args = [deg2rad(x) for x in args]
					transform = trans(make_rotY, transform)
				elif comm == 'z':
					args = [deg2rad(x) for x in args]
					transform = trans(make_rotZ, transform)
				elif comm == 'g':
					draw_lines(points, screen, [0,225,0] )
					save_ppm(screen, args[0])
示例#23
0
def run(filename):
    """
    This function runs an mdl script
    """
    color = [255, 255, 255]
    tmp = new_matrix()
    ident( tmp )
    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    stack = [ tmp ] #initializes origin stack with identity matrix pushed on
    screen = new_screen()
        
    for command in commands:
        if command[0] == 'push':
            push(stack)
        elif command[0] == 'pop':
            pop(stack)
        elif command[0] == 'move':
            stack[-1] = move(stack[-1], command[1], command[2], command[3])
        elif command[0] == 'rotate':
            stack[-1] = rotate(stack[-1], command[1], command[2])
        elif command[0] == 'scale':
            stack[-1] = scale(stack[-1], command[1], command[2], command[3])
        elif command[0] == 'box':
            box(stack[-1], command[1], command[2], command[3], command[4], command[5], command[6], screen, color)
        elif command[0] == 'torus':
            torus(stack[-1], command[1], command[2], command[3], command[4], screen, color)
        elif command[0] == 'sphere':
            sphere(stack[-1], command[1], command[2], command[3], command[4], screen, color)
        elif command[0] == 'line':
            line(stack[-1], command[1], command[2], command[3], command[4], command[5], command[6], screen, color)
        elif command[0] == 'save':
            save_extension(screen, command[1])
        elif command[0] == 'display':
            display(screen)
        else:
            pass
示例#24
0
def main():
    global GameGlobals

    currentArea = testArea()
    initDisplay()

    message("Welcome to RowanRPG!",libtcod.red)
    while not libtcod.console_is_window_closed():
        GameGlobals.ticks += 1
        key = libtcod.console_check_for_keypress(True)
        if(key.vk != libtcod.KEY_NONE):
            shouldQuit,currentArea = handle_keys(key,currentArea)
            if shouldQuit:
                break
            for e in currentArea.entities:
                currentArea.map[e.y][e.x] = currentArea.map[e.y][e.x]._replace(changed = True)
            currentArea = currentArea._replace(entities=map(lambda e: moveEntity(e,currentArea),currentArea.entities))

        #render the screen
        display(currentArea)
示例#25
0
def parse_file( fname, points, transform ):
    f = open(fname, 'r')
    cmd = f.readline().rstrip()

    while(cmd):
        if cmd in cmds_args:
            args = f.readline().rstrip()
            if cmd == 'g':
                #print args
                draw_lines(points, screen, [0,255,0])
                #save_extension(screen,args)
                save_ppm(screen,args)
            else:
                #print args
                args = map(float,args.split(" "))
                #print args
                i = ident(new_matrix()) #in case bad things happen
                if cmd == 'l':
                    add_edge(points, args[0],args[1],args[2],args[3],args[4],args[5])
                elif cmd == 's':
                    i = make_scale(args[0],args[1],args[2])
                elif cmd == 't':
                    i = make_translate(args[0],args[1],args[2])
                elif cmd == 'x':
                    i = make_rotX(args[0])
                elif cmd == 'y':
                    i = make_rotY(args[0])
                elif cmd == 'z':
                    i = make_rotZ(args[0])
                transform = matrix_mult(i, transform)

        elif cmd in cmds_noargs:
            if cmd == 'i':
                transform = ident(transform)
            elif cmd == 'a':
                points = matrix_mult(transform,points)
            elif cmd == 'v':
                draw_lines(points,screen,[0,255,0])
                display(screen)
        cmd = f.readline().rstrip()
    f.close()
示例#26
0
    def play_game(self, Q_VALUES_1, Q_VALUES_2):
        tk = Tk()
        canvas = Canvas(tk, width=window_size + 200, height=window_size)
        canvas.grid(row=0, column=0)

        player1_turn = True
        q_val = 0

        exists_winner = True

        def update():
            display(canvas, self.state, q_val)
            tk.update()
            sleep(sleep_time)

        print("---\nGame Start")

        while not self.state.is_game_over():
            previous_state = self.state
            if player1_turn:
                (self.state, self.move_info), q_val = player1.move(
                    True, self.state, Q_VALUES_1)
                player1_turn = False
            else:
                (self.state, self.move_info), q_val = player2.move(
                    False, self.state, Q_VALUES_2)
                player1_turn = True
            if ENABLE_GUI:
                update()
            if (clock() - self.start_time) > (sleep_time * 160):
                exists_winner = False
                break
        display(canvas, self.state, q_val)
        winner = "no winner"
        if exists_winner:
            winner = self.state.get_winner()
        canvas.create_text(window_size + 100, 20,
                           text="Winner: " + winner)
        print("Winner: " + winner)
示例#27
0
def parse_file( fname, points, transform ):
  f = open(fname, 'r')
  lines = f.readlines()
  f.close
  for i in range(len(lines)):
    line = lines[i].replace("\n","")
    if i+1 in range(len(lines)):
      n = lines[i+1].replace("\n","").split(" ")
    if line == 'l':
      for j in range(len(n)):
        n[j] = float(n[j])
        print n[j]
      add_edge(points,n[0],n[1],n[2],n[3],n[4],n[5])
    elif line == 'i':
      ident(transform)  
    elif line == 's':
      for j in range(len(n)):
        n[j] = float(n[j])
      matrix_mult(make_scale(n[0],n[1],n[2]),transform)      
    elif line == 't':
      for j in range(len(n)):
        n[j] = float(n[j])
      matrix_mult(make_translate(n[0],n[1],n[2]),transform)
    elif line == 'x':
      matrix_mult(make_rotX(n[0]),transform)
    elif line == 'y':
      matrix_mult(make_rotY(n[0]),transform)
    elif line == 'z':
      matrix_mult(make_rotZ(n[0]),transform)
    elif line == 'a':
      matrix_mult(transform,points)
    elif line == 'v':
      screen = new_screen()
      draw_lines(points,screen,color)
      display(screen)
    elif line == 'g':
      screen = new_screen()
      draw_lines(points,screen,color)
      save_ppm(screen,n[0])
示例#28
0
def parse_file( fname, points, transform ):
    screen = new_screen()
    color = [255, 255, 0]

    f = open(fname, 'r')
    fs = []
    for line in f.readlines():
        fs.append(line[:-1])

    i = 0
    while i < len(fs):
        if (fs[i] == "l"):
            ps = fs[i+1].split(" ")
            add_edge(points, float(ps[0]), float(ps[1]), float(ps[2]), float(ps[3]), float(ps[4]),float(ps[5]))
        elif (fs[i] == "i"):
            transform = ident()
        elif (fs[i] == "s"):
            ps = fs[i+1].split()
            transform = matrix_mult(make_scale(float(ps[0]), float(ps[1]), float(ps[2])), transform)
        elif (fs[i] == "t"):
            ps = fs[i+1].split()
            transform = matrix_mult(make_translate(float(ps[0]), float(ps[1]), float(ps[2])), transform)
        elif (fs[i] == "x"):
            transform = matrix_mult(make_rotX(float(fs[i+1])), transform)
        elif (fs[i] == "y"):
            transform = matrix_mult(make_rotY(float(fs[i+1])), transform)
        elif (fs[i] == "z"):
            transform = matrix_mult(make_rotZ(float(fs[i+1])), transform)
        elif (fs[i] == "a"):
            points = matrix_mult(transform, points)
        elif (fs[i] == "v"):
            draw_lines(points, screen, color)
            display(screen)
            clear_screen(screen)
        elif (fs[i] == "g"):
            print str(i) + fs[i]
            draw_lines(points, screen, color)
            display(screen)
        i=i+1
示例#29
0
def parse_file( fname, points, transform ):
	f = open('script_c', 'r')
	cmd = f.readline().rstrip()
	while (cmd):
		if cmd in commands_a:
			args = f.readline().rstrip()
			try:
				args = map(float, args.rsplit(" "))
			except ValueError:
				fname = args
                        m = ident(new_matrix())
                        if cmd == "g":
				draw_lines(points, screen, BLUE)
				save_ppm(screen, fname)
				save_extension(screen, fname)
			elif cmd == "l":
				add_edge(points, args[0], args[1], args[2], args[3], args[4], args[5])
			elif cmd == "s":
				m = make_scale(args[0], args[1], args[2])
			elif cmd == "t":
				m = make_translate(args[0], args[1], args[2])
			elif cmd == "x":
				m = make_rotX(args[0])
			elif cmd == "y":
				m = make_rotY(args[0])
			elif cmd == "z":
				m = make_rotZ(args[0])
                        transform = matrix_mult(transform, m)
                                
		elif cmd in commands_b:
			if cmd == "i":
				transform = ident(transform)
			elif cmd == "a":
				points = matrix_mult(transform, points)
			elif cmd == "v":
				screen = new_screen()
				draw_lines(points, screen, BLUE)
				display(screen)
		cmd = f.readline().rstrip()		
示例#30
0
def parse(filename, edges, transform, img, color):
    f = open(filename, "r")
    script = f.read().split("\n")
    f.close()
    i = 0
    while i < len(script):
        if script[i] == "line":
            coords = script[i + 1].split(" ")
            for k in range(len(coords)):
                coords[k] = int(coords[k])
            addEdge(edges, coords[0], coords[1], coords[2], coords[3],
                    coords[4], coords[5])
            i += 1
        elif script[i] == "ident":
            transform = I(4)
        elif script[i] == "apply":
            edges = multMatrix(transform, edges)
        elif script[i] == "quit":
            return
        elif script[i] == "move":
            coords = script[i + 1].split(" ")
            for k in range(len(coords)):
                coords[k] = int(coords[k])
            transform = multMatrix(translate(coords[0], coords[1], coords[2]),
                                   transform)
            i += 1
        elif script[i] == "scale":
            coords = script[i + 1].split(" ")
            for k in range(len(coords)):
                coords[k] = float(coords[k])
            transform = multMatrix(scale(coords[0], coords[1], coords[2]),
                                   transform)
            i += 1
        elif script[i] == "rotate":
            coords = script[i + 1].split(" ")
            transform = multMatrix(rotate(coords[0], float(coords[1])),
                                   transform)
            i += 1
        elif script[i] == "save":
            clear(img)
            drawLines(img, edges, color)
            if homeTest:
                save_ppm(img, script[i + 1])
            else:
                save_extension(img, script[i + 1])
            i += 1
        elif script[i] == "circle":
            coords = script[i + 1].split(" ")
            for k in range(len(coords)):
                coords[k] = int(coords[k])
            circle(edges, coords[0], coords[1], coords[2], coords[3])
            i += 1
        elif script[i] == "hermite":
            coords = script[i + 1].split(" ")
            for k in range(len(coords)):
                coords[k] = int(coords[k])
            hermite(edges, coords[0], coords[1], coords[2], coords[3],
                    coords[4], coords[5], coords[6], coords[7])
            i += 1
        elif script[i] == "bezier":
            coords = script[i + 1].split(" ")
            for k in range(len(coords)):
                coords[k] = int(coords[k])
            bezier(edges, coords[0], coords[1], coords[2], coords[3],
                   coords[4], coords[5], coords[6], coords[7])
            i += 1
        elif script[i] == "box":
            coords = script[i + 1].split(" ")
            for k in range(len(coords)):
                coords[k] = int(coords[k])
            box(edges, coords[0], coords[1], coords[2], coords[3], coords[4],
                coords[5])
            i += 1
        elif script[i] == "sphere":
            coords = script[i + 1].split(" ")
            for k in range(len(coords)):
                coords[k] = int(coords[k])
            sphere(edges, coords[0], coords[1], coords[2], coords[3])
            i += 1
        elif script[i] == "torus":
            coords = script[i + 1].split(" ")
            for k in range(len(coords)):
                coords[k] = int(coords[k])
            torus(edges, coords[0], coords[1], coords[2], coords[3], coords[4])
            i += 1
        elif script[i] == "clear":
            edges[0] = []
            edges[1] = []
            edges[2] = []
            edges[3] = []
        elif script[i] == "display" and not homeTest:
            clear(img)
            drawLines(img, edges, color)
            display(img)
        i += 1
示例#31
0
draw_line(XRES - 1, YRES - 1, 0, YRES / 2, s, c)

#octants 8 and 4
c[BLUE] = 255
draw_line(0, YRES - 1, XRES - 1, 0, s, c)
draw_line(0, YRES - 1, XRES - 1, YRES / 2, s, c)
draw_line(XRES - 1, 0, 0, YRES / 2, s, c)

#octants 2 and 6
c[RED] = 255
c[GREEN] = 0
c[BLUE] = 0
draw_line(0, 0, XRES / 2, YRES - 1, s, c)
draw_line(XRES - 1, YRES - 1, XRES / 2, 0, s, c)

#octants 7 and 3
c[BLUE] = 255
draw_line(0, YRES - 1, XRES / 2, 0, s, c)
draw_line(XRES - 1, 0, XRES / 2, YRES - 1, s, c)

#horizontal and vertical
c[BLUE] = 0
c[GREEN] = 255
draw_line(0, YRES / 2, XRES - 1, YRES / 2, s, c)
draw_line(XRES / 2, 0, XRES / 2, YRES - 1, s, c)

display(s)
save_ppm(s, 'binary.ppm')
save_ppm_ascii(s, 'ascii.ppm')
save_extension(s, 'img.png')
示例#32
0
def parse_file(fname, points, transform, screen, color):
    points = new_matrix()
    f = open(fname, 'r')
    lines = f.readlines()

    for i in range(len(lines)):
        if (lines[i] == "line\n"):
            coors = lines[i + 1].split(" ")
            x0 = int(coors[0])
            y0 = int(coors[1])
            z0 = int(coors[2])
            x1 = int(coors[3])
            y1 = int(coors[4])
            z1 = int(coors[5])
            add_edge(points, x0, y0, z0, x1, y1, z1)
            print "========== line =========="
            print_matrix(points)
        elif (lines[i] == "ident\n"):
            ident(transform)
            print "========== ident =========="
            print_matrix(transform)
        elif (lines[i] == "scale\n"):
            factor = lines[i + 1].split(" ")
            x = int(factor[0])
            y = int(factor[1])
            z = int(factor[2])
            scale = make_scale(x, y, z)
            matrix_mult(scale, transform)
            print "========== scale =========="
            print_matrix(transform)
        elif (lines[i] == "move\n"):
            factor = lines[i + 1].split(" ")
            x = int(factor[0])
            y = int(factor[1])
            z = int(factor[2])
            translate = make_translate(x, y, z)
            matrix_mult(translate, transform)
            print "========== move =========="
            print_matrix(transform)
        elif (lines[i] == "rotate\n"):
            param = lines[i + 1].split(" ")
            direct = param[0]
            angle = int(param[1]) * math.pi / 180
            if (direct == "x"):
                rotate = make_rotX(angle)
            elif (direct == "y"):
                rotate = make_rotY(angle)
            else:
                rotate = make_rotZ(angle)
            matrix_mult(rotate, transform)
            print "========== rotate =========="
            print_matrix(transform)
        elif (lines[i] == "apply\n"):
            print "========== before apply =========="
            print_matrix(points)
            matrix_mult(transform, points)
            for c in range(len(points)):
                for r in range(len(points[0])):
                    points[c][r] = int(points[c][r])
            print "========== apply =========="
            print_matrix(points)
        elif (lines[i] == "display\n"):
            clear_screen(screen)
            draw_lines(points, screen, color)
            display(screen)
        elif (lines[i] == "save\n"):
            image = lines[i + 1].split()
            save_extension(screen, image[0])
        else:
            pass
示例#33
0
def parse_file( fname, points, transform, screen, color ):
    f = open(fname, "r", 1)
    buffer = f.read()
    buffer = buffer.split("\n")
    print buffer
    index = 0
    while (index < len(buffer)):
        if (buffer[index] == "line"):
            print "drawing line"
            temp = parseArgs(buffer[index+1])
            add_edge(points,temp[0],temp[1],temp[2],temp[3],temp[4],temp[5])
            index+=2
        elif (buffer[index] == "circle"):
            print "drawing circle"
            temp = parseArgs(buffer[index+1])
            add_circle(points,temp[0],temp[1],0,temp[3],0.001)
            index+=2
        elif (buffer[index] == "hermite"):
            print "drawing hermite"
            temp = parseArgs(buffer[index+1])
            add_curve(points,temp[0],temp[1],temp[2],temp[3],temp[4],temp[5],temp[6],temp[7],0.001,"h")
            index+=2
        elif (buffer[index] == "bezier"):
            temp = parseArgs(buffer[index+1])
            add_curve(points,temp[0],temp[1],temp[2],temp[3],temp[4],temp[5],temp[6],temp[7],0.001,"b")
            index+=2
        elif (buffer[index] == "ident"):
            ident(transform)
            index+=1
        elif (buffer[index] == "scale"):
            print "scaling"
            temp = parseArgs(buffer[index+1])
            transform = make_scale(temp[0],temp[1],temp[2])
            index+=2
        elif (buffer[index] == "translate"):
            print "translating"
            temp = parseArgs(buffer[index+1])
            transform = make_translate(temp[0],temp[1],temp[2])                
            index+=2
        elif (buffer[index] == "xrotate"):
            print "xrot"
            temp = parseArgs(buffer[index+1])
            transform = make_rotX(temp[0])
            index+=2
        elif (buffer[index] == "yrotate"):
            print "yrot"
            temp = parseArgs(buffer[index+1])
            transform = make_rotY(temp[0])
            index+=2
        elif (buffer[index] == "zrotate"):
            print "zrot"
            temp = parseArgs(buffer[index+1])
            transform = make_rotZ(temp[0])
            index+=2
        elif (buffer[index] == "apply"):
            print "apply"
            matrix_mult(transform,points)
            index+=1
        elif (buffer[index] == "display"):
            print "displaying"
            draw_lines(points,screen,color)
            display(screen)
            index+=1
        elif (buffer[index] == "save"):
            draw_lines(points,screen,color)
            save_ppm(screen,temp[0])
            index+=1
        else:
            index+=1
示例#34
0
def run(filename):
    """
    This function runs an mdl script
    """
    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    view = [0, 0, 1]
    ambient = [50, 50, 50]
    light = [[0.5, 0.75, 1], [255, 255, 255]]

    color = [0, 0, 0]
    tmp = new_matrix()
    ident(tmp)

    stack = [[x[:] for x in tmp]]
    screen = new_screen()
    zbuffer = new_zbuffer()
    tmp = []
    step_3d = 100
    consts = ''
    polygons = []
    edges = []
    symbols['.white'] = [
        'constants', {
            'red': [0.2, 0.5, 0.5],
            'green': [0.2, 0.5, 0.5],
            'blue': [0.2, 0.5, 0.5]
        }
    ]

    for command in commands:
        op = command['op']

        if op == 'push':
            stack.append([x[:] for x in stack[-1]])

        elif op == 'pop':
            stack.pop()

        elif op == 'sphere':
            #print 'SPHERE\t' + str(args)
            if (command['constants'] == None):
                reflect = '.white'
            else:
                reflect = command['constants']

            args = command['args']
            add_sphere(polygons, float(args[0]), float(args[1]),
                       float(args[2]), float(args[3]), step_3d)
            matrix_mult(stack[-1], polygons)
            draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                          symbols, reflect)
            polygons = []

        elif op == 'torus':
            #print 'TORUS\t' + str(args)
            if (command['constants'] == None):
                reflect = '.white'
            else:
                reflect = command['constants']

            args = command['args']
            add_torus(polygons, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), step_3d)
            matrix_mult(stack[-1], polygons)
            draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                          symbols, reflect)
            polygons = []

        elif op == 'box':
            #print 'BOX\t' + str(args)
            if (command['constants'] == None):
                reflect = '.white'
            else:
                reflect = command['constants']

            args = command['args']
            add_box(polygons, float(args[0]), float(args[1]), float(args[2]),
                    float(args[3]), float(args[4]), float(args[5]))
            matrix_mult(stack[-1], polygons)
            draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                          symbols, reflect)
            polygons = []

        elif op == 'line':
            args = command['args']
            add_edge(edges, float(args[0]), float(args[1]), float(args[2]),
                     float(args[3]), float(args[4]), float(args[5]))
            matrix_mult(stack[-1], edges)
            draw_lines(edges, screen, zbuffer, color)
            edges = []

        elif op == 'scale':
            #print 'SCALE\t' + str(args)

            args = command['args']
            t = make_scale(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(stack[-1], t)
            stack[-1] = [x[:] for x in t]

        elif op == 'move':
            #print 'MOVE\t' + str(args)

            args = command['args']
            t = make_translate(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(stack[-1], t)
            stack[-1] = [x[:] for x in t]

        elif op == 'rotate':
            #print 'ROTATE\t' + str(args)

            args = command['args']

            theta = float(args[1]) * (math.pi / 180)

            if args[0] == 'x':
                t = make_rotX(theta)
            elif args[0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            matrix_mult(stack[-1], t)
            stack[-1] = [x[:] for x in t]

        elif op == 'clear':
            clear_screen(screen)
            clear_zbuffer(zbuffer)

        elif op == 'display' or op == 'save':

            args = command['args']
            #clear_screen(screen)
            args = command['args']
            if op == 'display':
                display(screen)
            else:
                save_extension(screen, args[0])
示例#35
0
def parse_file(fname, edges, transform, screen, color):

    f = open(fname)
    lines = f.readlines()

    c = 0
    while c < len(lines):
        line = lines[c].strip()
        #print ':' + line + ':'

        if line in ARG_COMMANDS:
            c += 1
            args = lines[c].strip().split(' ')

        if line == 'line':
            #print 'LINE\t' + str(args)

            add_edge(edges, float(args[0]), float(args[1]), float(args[2]),
                     float(args[3]), float(args[4]), float(args[5]))

        elif line == 'scale':
            #print 'SCALE\t' + str(args)
            t = make_scale(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(t, transform)

        elif line == 'move':
            #print 'MOVE\t' + str(args)
            t = make_translate(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(t, transform)

        elif line == 'rotate':
            #print 'ROTATE\t' + str(args)
            theta = float(args[1]) * (math.pi / 180)

            if args[0] == 'x':
                t = make_rotX(theta)
            elif args[0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            matrix_mult(t, transform)

        elif line == 'ident':
            ident(transform)

        elif line == 'apply':
            matrix_mult(transform, edges)

        elif line == 'display' or line == 'save':
            clear_screen(screen)
            draw_lines(edges, screen, color)

            if line == 'display':
                display(screen)
            else:
                save_extension(screen, args[0])

        elif line == 'circle':
            x, y, z, r = float(args[0]), float(args[1]), float(args[2]), float(
                args[3])
            t = 0
            increment = 0.0001
            while t + increment <= 1:
                point = make_circle(x, y, z, r, t)
                add_point(edges, point[0], point[1], z)
                t += increment
                point = make_circle(x, y, z, r, t)
                add_point(edges, point[0], point[1], z)
                t += increment

        elif line == 'bezier':
            xcoef = make_bezier(float(args[0]), float(args[2]), float(args[4]),
                                float(args[6]))
            #print(float(args[0]), float(args[2]), float(args[4]), float(args[6]))
            ycoef = make_bezier(float(args[1]), float(args[3]), float(args[5]),
                                float(args[7]))
            #print(float(args[1]), float(args[3]), float(args[5]), float(args[7]))
            # print(xcoef)
            # print(ycoef)
            t = 0
            increment = 0.0001
            while t + increment <= 1:
                add_point(edges, apply_coef(xcoef, t), apply_coef(ycoef, t), 1)
                t += increment
                add_point(edges, apply_coef(xcoef, t), apply_coef(ycoef, t), 1)
                t += increment

        elif line == 'hermite':
            xcoef = make_hermite(float(args[0]), float(args[2]),
                                 float(args[4]), float(args[6]))
            ycoef = make_hermite(float(args[1]), float(args[3]),
                                 float(args[5]), float(args[7]))
            t = 0
            increment = 0.0001
            while t + increment <= 1:
                add_point(edges, apply_coef(xcoef, t), apply_coef(ycoef, t), 1)
                t += increment
                add_point(edges, apply_coef(xcoef, t), apply_coef(ycoef, t), 1)
                t += increment
        c += 1
示例#36
0
文件: parser.py 项目: jliu01298/hw63d
def parse_file(fname, edges, transform, screen, color):

    f = open(fname)
    lines = f.readlines()

    c = 0
    while c < len(lines):
        line = lines[c].strip()
        #print ':' + line + ':'

        if line in ARG_COMMANDS:
            c += 1
            args = lines[c].strip().split(' ')

        if line == 'sphere':
            add_sphere(edges, float(args[0]), float(args[1]), float(args[2]),
                       float(args[3]), 0.05)

        elif line == 'torus':
            add_torus(edges, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), 0.05)

        elif line == 'box':
            add_box(edges, float(args[0]), float(args[1]), float(args[2]),
                    float(args[3]), float(args[4]), float(args[5]))

        elif line == 'clear':
            screen = new_screen()
            edges = []

        elif line == 'circle':
            add_circle(edges, float(args[0]), float(args[1]), float(args[2]),
                       float(args[3]), 0.001)

        elif line == 'hermite':
            add_curve(edges, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), float(args[5]),
                      float(args[6]), float(args[7]), 0.001, 'hermite')

        elif line == 'bezier':
            add_curve(edges, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), float(args[5]),
                      float(args[6]), float(args[7]), 0.001, 'bezier')

        elif line == 'line':
            #print 'LINE\t' + str(args)

            add_edge(edges, float(args[0]), float(args[1]), float(args[2]),
                     float(args[3]), float(args[4]), float(args[5]))

        elif line == 'scale':
            #print 'SCALE\t' + str(args)
            t = make_scale(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(t, transform)

        elif line == 'move':
            #print 'MOVE\t' + str(args)
            t = make_translate(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(t, transform)

        elif line == 'rotate':
            #print 'ROTATE\t' + str(args)
            theta = float(args[1]) * (math.pi / 180)

            if args[0] == 'x':
                t = make_rotX(theta)
            elif args[0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            matrix_mult(t, transform)

        elif line == 'ident':
            ident(transform)

        elif line == 'apply':
            matrix_mult(transform, edges)

        elif line == 'display' or line == 'save':
            clear_screen(screen)
            draw_lines(edges, screen, color)

            if line == 'display':
                display(screen)
            else:
                save_extension(screen, args[0])

        c += 1
示例#37
0
def parse_file(fname, edges, transform, screen, color):

    f = open(fname)
    lines = f.readlines()

    clear_screen(screen)
    t = new_matrix()
    ident(t)
    systems = [t]

    step = 0.1
    c = 0
    while c < len(lines):
        line = lines[c].strip()
        #print ':' + line + ':'

        if line in ARG_COMMANDS:
            c += 1
            args = lines[c].strip().split(' ')
            #print 'args\t' + str(args)

        if line == 'sphere':
            #print 'SPHERE\t' + str(args)
            add_sphere(edges, float(args[0]), float(args[1]), float(args[2]),
                       float(args[3]), step)
            matrix_mult(systems[-1], edges)
            draw_polygons(edges, screen, color)
            edges = []

        elif line == 'torus':
            #print 'TORUS\t' + str(args)
            add_torus(edges, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), step)
            matrix_mult(systems[-1], edges)
            draw_polygons(edges, screen, color)
            edges = []

        elif line == 'box':
            #print 'BOX\t' + str(args)
            add_box(edges, float(args[0]), float(args[1]), float(args[2]),
                    float(args[3]), float(args[4]), float(args[5]))
            matrix_mult(systems[-1], edges)
            draw_polygons(edges, screen, color)
            edges = []

        elif line == 'circle':
            #print 'CIRCLE\t' + str(args)
            add_circle(edges, float(args[0]), float(args[1]), float(args[2]),
                       float(args[3]), step)

        elif line == 'hermite' or line == 'bezier':
            #print 'curve\t' + line + ": " + str(args)
            add_curve(edges, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), float(args[5]),
                      float(args[6]), float(args[7]), step, line)

        elif line == 'line':
            #print 'LINE\t' + str(args)

            add_edge(edges, float(args[0]), float(args[1]), float(args[2]),
                     float(args[3]), float(args[4]), float(args[5]))

        elif line == 'scale':
            #print 'SCALE\t' + str(args)
            t = make_scale(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(systems[-1], t)
            systems[-1] = [x[:] for x in t]

        elif line == 'move':
            #print 'MOVE\t' + str(args)
            t = make_translate(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(systems[-1], t)
            systems[-1] = [x[:] for x in t]

        elif line == 'rotate':
            #print 'ROTATE\t' + str(args)
            theta = float(args[1]) * (math.pi / 180)

            if args[0] == 'x':
                t = make_rotX(theta)
            elif args[0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            matrix_mult(systems[-1], t)
            systems[-1] = [x[:] for x in t]

        elif line == 'clear':
            edges = []

        elif line == 'ident':
            ident(transform)

        elif line == 'apply':
            matrix_mult(transform, edges)

        elif line == 'push':
            systems.append([x[:] for x in systems[-1]])

        elif line == 'pop':
            systems.pop()

        elif line == 'display' or line == 'save':
            if line == 'display':
                display(screen)
            else:
                save_extension(screen, args[0])

        c += 1
示例#38
0
def parse_file(fname, edges, polygons, csystems, screen, color):

    f = open(fname)
    lines = f.readlines()

    step = 100
    step_3d = 20

    c = 0
    while c < len(lines):
        line = lines[c].strip()
        #print ':' + line + ':'

        if line in ARG_COMMANDS:
            c += 1
            args = lines[c].strip().split(' ')

        if line == 'push':
            csystems.append(copy_matrix(csystems[-1]))

        elif line == 'pop':
            csystems.pop()

        elif line == 'sphere':
            #print 'SPHERE\t' + str(args)
            add_sphere(polygons, float(args[0]), float(args[1]),
                       float(args[2]), float(args[3]), step_3d)
            matrix_mult(csystems[-1], polygons)
            draw_polygons(polygons, screen, color)
            polygons = []

        elif line == 'torus':
            #print 'TORUS\t' + str(args)
            add_torus(polygons, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), step_3d)
            matrix_mult(csystems[-1], polygons)
            draw_polygons(polygons, screen, color)
            polygons = []

        elif line == 'box':
            #print 'BOX\t' + str(args)
            add_box(polygons, float(args[0]), float(args[1]), float(args[2]),
                    float(args[3]), float(args[4]), float(args[5]))
            matrix_mult(csystems[-1], polygons)
            draw_polygons(polygons, screen, color)
            polygons = []

        elif line == 'circle':
            #print 'CIRCLE\t' + str(args)
            add_circle(edges, float(args[0]), float(args[1]), float(args[2]),
                       float(args[3]), step)
            matrix_mult(csystems[-1], edges)
            draw_lines(edges, screen, color)
            edges = []

        elif line == 'hermite' or line == 'bezier':
            #print 'curve\t' + line + ": " + str(args)
            add_curve(edges, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), float(args[5]),
                      float(args[6]), float(args[7]), step, line)
            matrix_mult(csystems[-1], edges)
            draw_lines(edges, screen, color)
            edges = []

        elif line == 'line':
            #print 'LINE\t' + str(args)

            add_edge(edges, float(args[0]), float(args[1]), float(args[2]),
                     float(args[3]), float(args[4]), float(args[5]))
            matrix_mult(csystems[-1], edges)
            draw_lines(edges, screen, color)
            edges = []

        elif line == 'scale':
            #print 'SCALE\t' + str(args)
            t = make_scale(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(csystems[-1], t)
            csystems[-1] = copy_matrix(t)

        elif line == 'move':
            #print 'MOVE\t' + str(args)
            t = make_translate(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(csystems[-1], t)
            csystems[-1] = copy_matrix(t)

        elif line == 'rotate':
            #print 'ROTATE\t' + str(args)
            theta = float(args[1]) * (math.pi / 180)

            if args[0] == 'x':
                t = make_rotX(theta)
            elif args[0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            matrix_mult(csystems[-1], t)
            csystems[-1] = copy_matrix(t)

        elif line == 'display' or line == 'save':

            if line == 'display':
                display(screen)
            else:
                save_extension(screen, args[0])
        c += 1
示例#39
0
while x0 < 400:
    color = [0, green, blue]
    draw_line(x0, y0, x1, y1, screen, color)
    x0 += 5
    x1 -= 5
    if green > 100:
        green -= 0.5
    if blue < 255:
        blue += 1

red = 255
x2 = 0
y2 = 0
x3 = 50

x4 = 500
y4 = 500
x5 = 450

while y2 < 500:
    color = [red, 0, 0]
    draw_line(x2, y2, x3, y2, screen, color)
    draw_line(x4, y4, x5, y4, screen, color)
    if red > 100:
        red -= 0.5
    y2 += 2
    y4 -= 2

display(screen)
save_extension(screen, 'img.png')
示例#40
0
def run(filename):
    """
    This function runs an mdl script
    """
    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    view = [0,
            0,
            1];
    ambient = [50,
               50,
               50]
    light = [[0.5,
              0.75,
              1],
             [255,
              255,
              255]]

    color = [0, 0, 0]
    symbols['.white'] = ['constants',
                         {'red': [0.2, 0.5, 0.5],
                          'green': [0.2, 0.5, 0.5],
                          'blue': [0.2, 0.5, 0.5]}]
    reflect = '.white'

    (name, num_frames) = first_pass(commands)
    frames = second_pass(commands, num_frames)

    for i in range(int(num_frames)):
        tmp = new_matrix()
        ident( tmp )

        stack = [ [x[:] for x in tmp] ]
        screen = new_screen()
        zbuffer = new_zbuffer()
        tmp = []
        step_3d = 100
        consts = ''
        coords = []
        coords1 = []

        for command in commands:
            print command
            c = command['op']
            args = command['args']
            knob_value = 1
            if "knob" in command.keys() and command['knob'] != None:
                knob_value = frames[i][command['knob']]

            if c == 'box':
                if command['constants']:
                    reflect = command['constants']
                add_box(tmp,
                        args[0]*knob_value, args[1]*knob_value, args[2]*knob_value,
                        args[3]*knob_value, args[4]*knob_value, args[5]*knob_value)
                matrix_mult( stack[-1], tmp )
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
                reflect = '.white'
            elif c == 'sphere':
                if command['constants']:
                    reflect = command['constants']
                add_sphere(tmp,
                           args[0]*knob_value, args[1]*knob_value, args[2]*knob_value, args[3]*knob_value, step_3d)
                matrix_mult( stack[-1], tmp )
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
                reflect = '.white'
            elif c == 'torus':
                if command['constants']:
                    reflect = command['constants']
                add_torus(tmp,
                          args[0]*knob_value, args[1]*knob_value, args[2]*knob_value, args[3]*knob_value, args[4]*knob_value, step_3d)
                matrix_mult( stack[-1], tmp )
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
                reflect = '.white'
            elif c == 'line':
                add_edge(tmp,
                         args[0]*knob_value, args[1]*knob_value, args[2]*knob_value, args[3]*knob_value, args[4]*knob_value, args[5]*knob_value)
                matrix_mult( stack[-1], tmp )
                draw_lines(tmp, screen, zbuffer, color)
                tmp = []
            elif c == 'move':
                tmp = make_translate(args[0]*knob_value, args[1]*knob_value, args[2]*knob_value)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'scale':
                tmp = make_scale(args[0]*knob_value, args[1]*knob_value, args[2]*knob_value)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'rotate':
                theta = args[1] * (math.pi/180) *knob_value
                if args[0] == 'x':
                    tmp = make_rotX(theta)
                elif args[0] == 'y':
                    tmp = make_rotY(theta)
                else:
                    tmp = make_rotZ(theta)
                matrix_mult( stack[-1], tmp )
                stack[-1] = [ x[:] for x in tmp]
                tmp = []
            elif c == 'push':
                stack.append([x[:] for x in stack[-1]] )
            elif c == 'pop':
                stack.pop()
            elif c == 'display':
                display(screen)
            elif c == 'save':
                save_extension(screen, args[0])
            elif c == 'mesh':
                if command['constants']:
                    reflect = command['constants']
                add_sphere(tmp,
                           args[0]*knob_value, args[1]*knob_value, args[2]*knob_value, args[3]*knob_value, step_3d)
                matrix_mult( stack[-1], tmp )
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
        save_extension(screen,"./anim/" + name + ("0000" + str(i))[-4:])
示例#41
0
def run(filename):
    """
    This function runs an mdl script
    """
    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print("Parsing failed.")
        return

    view = [0, 0, 1]
    ambient = [50, 50, 50]
    light = [[0.5, 0.75, 1], [255, 255, 255]]

    color = [0, 0, 0]
    tmp = new_matrix()
    ident(tmp)

    stack = [[x[:] for x in tmp]]
    screen = new_screen()
    zbuffer = new_zbuffer()
    tmp = []
    step_3d = 100
    consts = ''
    coords = []
    coords1 = []
    symbols['.white'] = [
        'constants', {
            'red': [0.2, 0.5, 0.5],
            'green': [0.2, 0.5, 0.5],
            'blue': [0.2, 0.5, 0.5]
        }
    ]
    reflect = '.white'
    edges = []
    polygons = []
    print(symbols)
    for command in commands:
        #    print (command)
        if command["op"] == "move":
            t = make_translate(float(command["args"][0]),
                               float(command["args"][1]),
                               float(command["args"][2]))
            matrix_mult(stack[-1], t)
            stack[-1] = [x[:] for x in t]
        elif command["op"] == "sphere":
            add_sphere(polygons, float(command["args"][0]),
                       float(command["args"][1]), float(command["args"][2]),
                       float(command["args"][3]), step_3d)
            matrix_mult(stack[-1], polygons)
            if command["constants"] == None:
                draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                              symbols, reflect)
            else:
                draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                              symbols, command["constants"])
            polygons = []
        elif command["op"] == "rotate":
            theta = float(command["args"][1]) * (math.pi / 180)
            if command["args"][0] == 'x':
                t = make_rotX(theta)
            elif command["args"][0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            matrix_mult(stack[-1], t)
            stack[-1] = [x[:] for x in t]
        elif command["op"] == "box":
            add_box(polygons, float(command["args"][0]),
                    float(command["args"][1]), float(command["args"][2]),
                    float(command["args"][3]), float(command["args"][4]),
                    float(command["args"][5]))
            matrix_mult(stack[-1], polygons)
            if command["constants"] == None:
                draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                              symbols, reflect)
            else:
                draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                              symbols, command["constants"])
            polygons = []
        elif command["op"] == "pop":
            stack.pop()
        elif command["op"] == "push":
            stack.append([x[:] for x in stack[-1]])
        elif command["op"] == "scale":
            t = make_scale(float(command["args"][0]),
                           float(command["args"][1]),
                           float(command["args"][2]))
            matrix_mult(stack[-1], t)
            stack[-1] = [x[:] for x in t]
        elif command["op"] == "torus":
            add_torus(polygons, float(command["args"][0]),
                      float(command["args"][1]), float(command["args"][2]),
                      float(command["args"][3]), float(command["args"][4]),
                      step_3d)
            matrix_mult(stack[-1], polygons)
            if command["constants"] == None:
                draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                              symbols, reflect)
            else:
                draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                              symbols, command["constants"])
            polygons = []
        elif command["op"] == "display":
            display(screen)
        elif command["op"] == "save":
            save_extension(screen, command["args"][0] + ".png")
示例#42
0
def parse_file(fname, edges, polygons, transform, screen, color):

    f = open(fname)
    lines = f.readlines()
    step = 100
    step_3d = 20

    start = new_matrix()
    ident(start)
    stack = []
    stack.append(start)

    for c in range(0, len(lines)):
        line = lines[c].strip()
        #print ':' + line + ':'

        if line in ARG_COMMANDS:
            c += 1
            args = lines[c].strip().split(' ')
            #print 'args\t' + str(args)

        if line == 'push':
            top = deepcopy(stack[-1])
            stack.append(top)

        elif line == 'pop':
            stack.pop()

        elif line == 'sphere':
            #print 'SPHERE\t' + str(args)
            add_sphere(polygons, float(args[0]), float(args[1]),
                       float(args[2]), float(args[3]), step_3d)

            matrix_mult(stack[-1], polygons)
            draw_polygons(polygons, screen, color)
            polygons = []

        elif line == 'torus':
            #print 'TORUS\t' + str(args)
            add_torus(polygons, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), step_3d)

            matrix_mult(stack[-1], polygons)
            draw_polygons(polygons, screen, color)
            polygons = []

        elif line == 'box':
            #print 'BOX\t' + str(args)
            add_box(polygons, float(args[0]), float(args[1]), float(args[2]),
                    float(args[3]), float(args[4]), float(args[5]))

            matrix_mult(stack[-1], polygons)
            draw_polygons(polygons, screen, color)
            polygons = []

        elif line == 'circle':
            #print 'CIRCLE\t' + str(args)
            add_circle(edges, float(args[0]), float(args[1]), float(args[2]),
                       float(args[3]), step)

            matrix_mult(stack[-1], edges)
            draw_lines(edges, screen, color)
            edges = []

        elif line == 'hermite' or line == 'bezier':
            #print 'curve\t' + line + ": " + str(args)
            add_curve(edges, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), float(args[5]),
                      float(args[6]), float(args[7]), step, line)

            matrix_mult(stack[-1], edges)
            draw_lines(edges, screen, color)
            edges = []

        elif line == 'line':
            #print 'LINE\t' + str(args)

            add_edge(edges, float(args[0]), float(args[1]), float(args[2]),
                     float(args[3]), float(args[4]), float(args[5]))

            matrix_mult(stack[-1], edges)
            draw_lines(edges, screen, color)
            edges = []

        elif line == 'scale':
            #print 'SCALE\t' + str(args)
            t = make_scale(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(t, transform)
            matrix_mult(stack.pop(), t)
            stack.append(t)

        elif line == 'move':
            #print 'MOVE\t' + str(args)
            t = make_translate(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(stack.pop(), t)
            stack.append(t)

        elif line == 'rotate':
            #print 'ROTATE\t' + str(args)
            theta = float(args[1]) * (math.pi / 180)

            if args[0] == 'x':
                t = make_rotX(theta)
            elif args[0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            matrix_mult(stack.pop(), t)
            stack.append(t)

        elif line == 'display':
            display(screen)

        elif line == 'save':
            save_extension(screen, args[0])
示例#43
0
def parse_file( fname, points, transform, screen, color ):
    CURR_NUM = 0
    file = open(fname, 'r')
    lines = file.readlines()
    for i in range(len(lines)):
        line = lines[i].strip()
        print line
        if line == "line":
            next = lines[i+1].strip().split()
            add_edge( points, int(next[0]), int(next[1]), int(next[2]), int(next[3]), int(next[4]), int(next[5]))
            i += 1
        elif line == "ident":
            ident( transform )
        elif line == "scale":
            next = lines[i+1].strip().split()
            scale = make_scale( float(next[0]), float(next[1]), float(next[2]) )
            matrix_mult(scale, transform)
            i += 1
        elif line == "move":
            next = lines[i+1].strip().split()
            trans = make_translate( int(next[0]), int(next[1]), int(next[2]) )
            matrix_mult( trans, transform )
            i += 1
        elif line == "rotate":
            next = lines[i+1].strip()
            next = next.split()
            if next[0] == 'x':
                rot = make_rotX( int(next[1]) )
            elif next[0] == 'y':
                rot = make_rotY( int(next[1]) )
            else:
                rot = make_rotZ( int(next[1]) )
            matrix_mult( rot, transform )
            i += 1
        elif line == "apply":
            matrix_mult( transform, points )
            for num in range(len(points)):
                for num2 in range(len(points[0])):
                    points[num][num2] = int(points[num][num2])
        elif line == "display":
            CURR_NUM += 1
            clear_screen(screen)
            draw_lines( points, screen, color )
            display(screen)
            print CURR_NUM
        elif line == "save":
            clear_screen( screen )
            next = str(lines[i+1])
            draw_lines( points, screen, color )
            save_extension(screen, next)
        elif line == "quit":
            break
    # file = open(fname,'r')
    # i = file.readline().strip()
    # i2 = []

    # while i != '':
    #     print i
    #     if i == "line": #written, not checked
    #         i2 = file.readline().strip()
    #         i2 = [int(x) for x in i2.split()]
    #         print i2
    #         add_edge( points, i2[0], i2[1], i2[2], i2[3], i2[4], i2[5] )
            
    #     elif i == "ident": #written, not checked
    #         ident( transform )
        
    #     elif i == "scale": #written, not checked
    #         i2 = file.readline().strip()
    #         i2 = [float(x) for x in i2.split()]
    #         mat = make_scale(i2[0], i2[1], i2[2])
    #         matrix_mult( transform, points )
            
    #     elif i == "translate": #written, not checked
    #         i2 = file.readline().strip()
    #         i2 = [int(x) for x in i2.split()]
    #         mat = make_scale(i2[0], i2[1], i2[2])
    #         matrix_mult( transform, points )
            
    #     elif i == "rotate": #not written, not checked
    #         i2 = file.readline().strip()
    #         tmp = i2[2]
    #         if i2[0] == 'x':
    #             make_rotX( int(tmp) )
    #             matrix_mult(make_rotX, points)
    #         elif i2[1] == 'y':
    #             make_rotY( int(tmp) )
    #             matrix_mult(make_rotY, points)
    #         else:
    #             make_rotZ( int(tmp) )
    #             matrix_mult(make_rotZ, points)

    #     elif i == "apply": #not written, not checked
    #         pass
            
    #     elif i == "display": #written, not checked
    #         clear_screen(screen)
    #         draw_lines(points, screen, color)
    #         display(screen)
    #         clear_screen(screen)
            
    #     elif i == "save": #written, not checked
    #         clear_screen(screen)
    #         draw_lines(points, screen, color)
    #         i2 = file.readline().strip()
    #         save_extension( screen, i2[0] )
    #         clear_screen(screen)
            
    #     elif i == "quit": #written, not checked
    #         break

    #     i = file.readline().strip()
    #     file.close()
示例#44
0
def run(filename):
    """
    This function runs an mdl script
    """
    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    view = [0,
            0,
            1];
    ambient = [50,
               50,
               50]
    light = [[0.5,
              0.75,
              1],
             [255,
              255,
              255]]

    color = [0, 0, 0]
    tmp = new_matrix()
    ident( tmp )

    stack = [ [x[:] for x in tmp] ]
    screen = new_screen()
    zbuffer = new_zbuffer()
    tmp = []
    step_3d = 100
    consts = ''
    coords = []
    coords1 = []
    symbols['.white'] = ['constants',
                         {'red': [0.2, 0.5, 0.5],
                          'green': [0.2, 0.5, 0.5],
                          'blue': [0.2, 0.5, 0.5]}]
    reflect = '.white'
    polygons = []
    edges = []
    
    for command in commands:
        if command['op'] == 'push':
            stack.append([row[:] for row in stack[-1]])

        elif command['op'] == 'pop':
            stack.pop()

        elif command['op'] == 'move':
            t = make_translate(command['args'][0],command['args'][1],command['args'][2])
            matrix_mult(stack[-1], t)
            stack[-1] = [r[:] for r in t]

        elif command['op'] == 'scale':
            t = make_scale(command['args'][0],command['args'][1],command['args'][2])
            matrix_mult(stack[-1], t)
            stack[-1] = [r[:] for r in t]

        elif command['op'] == 'rotate':
            t = new_matrix()
            if(command['args'][0] == 'x'):
                t = make_rotX(command['args'][1]*(math.pi / 180))

            elif(command['args'][0] == 'y'):
                t = make_rotY(command['args'][1]*(math.pi / 180))

            elif(command['args'][0] == 'z'):
                t = make_rotZ(command['args'][1]*(math.pi / 180))

            else:
                print("Input axis for rotate is incorrect")

            matrix_mult(stack[-1], t)
            stack[-1] = [r[:] for r in t]

        elif command['op'] in 'sphere box torus':
            if command['op'] == 'sphere':
                add_sphere(polygons, float(command['args'][0]), float(command['args'][1]), float(command['args'][2]), float(command['args'][3]), step_3d)
            elif command['op'] == 'box':
                add_box(polygons, float(command['args'][0]), float(command['args'][1]), float(command['args'][2]), float(command['args'][3]), float(command['args'][4]), float(command['args'][5]))
            elif command['op'] == 'torus':
                add_torus(polygons, float(command['args'][0]), float(command['args'][1]), float(command['args'][2]), float(command['args'][3]), float(command['args'][4]), step_3d)

            matrix_mult( stack[-1], polygons )

            if(command['constants']):
                draw_polygons(polygons, screen, zbuffer, view, ambient, light, symbols, command['constants'])
            else:
                draw_polygons(polygons, screen, zbuffer, view, ambient, light, symbols, reflect)
            polygons = []

        elif command['op'] == 'line':
            add_edge(edges, float(command['args'][0]), float(command['args'][1]), float(command['args'][2]), float(command['args'][3]), float(command['args'][4]), float(command['args'][5]))
            matrix_mult( stack[-1], edges )
            draw_lines(edges, screen, zbuffer, color)
            edges = []

        elif command['op'] == 'constants':
            pass

        elif command['op'] == 'save':
            save_extension(screen, command['args'][0] + ".png")

        elif command['op'] == 'display':
            display(screen)

        else:
            print("Unknown operator", command['op'])
示例#45
0
def run(filename):
    """
    This function runs an mdl script
    """
    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    view = [0, 0, 1]
    ambient = [50, 50, 50]
    light = [[0.5, 0.75, 1], [255, 255, 255]]

    color = [0, 0, 0]
    symbols['.white'] = [
        'constants', {
            'red': [0.2, 0.5, 0.5],
            'green': [0.2, 0.5, 0.5],
            'blue': [0.2, 0.5, 0.5]
        }, {
            'red': [0.7, 0.2, 0],
            'green': [0.2, 0, 0.5],
            'blue': [0, 0.5, 0.5]
        }
    ]
    symbols['shade_type'] = 'flat'
    reflect = '.white'

    (name, num_frames) = first_pass(commands)
    frames = second_pass(commands, num_frames)

    tmp = new_matrix()
    ident(tmp)

    stack = [[x[:] for x in tmp]]
    screen = new_screen()
    zbuffer = new_zbuffer()
    tmp = []
    step_3d = 100
    consts = ''
    coords = []
    coords1 = []

    for command in commands:
        #print command
        c = command['op']
        args = command['args']
        knob_value = 1
        shading = symbols['shade_type']

        if c == 'box':
            if command['constants']:
                reflect = command['constants']
            add_box(tmp, args[0], args[1], args[2], args[3], args[4], args[5])
            matrix_mult(stack[-1], tmp)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols,
                          reflect, shading)
            tmp = []
            reflect = '.white'
        elif c == 'pyramid':
            if command['constants']:
                reflect = command['constants']
            add_pyramid(tmp, args[0], args[1], args[2], args[3], args[4],
                        args[5])
            matrix_mult(stack[-1], tmp)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols,
                          reflect, shading)
            tmp = []
            reflect = '.white'
        elif c == 'cylinder':
            if command['constants']:
                reflect = command['constants']
            add_cylinder(tmp, args[0], args[1], args[2], args[3], args[4],
                         step_3d)
            matrix_mult(stack[-1], tmp)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols,
                          reflect)
            tmp = []
            reflect = '.white'
        elif c == 'sphere':
            if command['constants']:
                reflect = command['constants']
            add_sphere(tmp, args[0], args[1], args[2], args[3], step_3d)
            matrix_mult(stack[-1], tmp)
            print(shading)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols,
                          reflect, shading)
            tmp = []
            reflect = '.white'
        elif c == 'torus':
            if command['constants']:
                reflect = command['constants']
            add_torus(tmp, args[0], args[1], args[2], args[3], args[4],
                      step_3d)
            matrix_mult(stack[-1], tmp)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols,
                          reflect, shading)
            tmp = []
            reflect = '.white'
        elif c == 'line':
            add_edge(tmp, args[0], args[1], args[2], args[3], args[4], args[5])
            matrix_mult(stack[-1], tmp)
            draw_lines(tmp, screen, zbuffer, color)
            tmp = []
        elif c == 'move':
            tmp = make_translate(args[0], args[1], args[2])
            matrix_mult(stack[-1], tmp)
            stack[-1] = [x[:] for x in tmp]
            tmp = []
        elif c == 'scale':
            tmp = make_scale(args[0], args[1], args[2])
            matrix_mult(stack[-1], tmp)
            stack[-1] = [x[:] for x in tmp]
            tmp = []
        elif c == 'rotate':
            theta = args[1] * (math.pi / 180)
            if args[0] == 'x':
                tmp = make_rotX(theta)
            elif args[0] == 'y':
                tmp = make_rotY(theta)
            else:
                tmp = make_rotZ(theta)
            matrix_mult(stack[-1], tmp)
            stack[-1] = [x[:] for x in tmp]
            tmp = []
        elif c == 'mesh':
            file_name = command['cs'] + '.obj'
            f = open(file_name, 'r')

            vectors = []
            polygons = []
            result = []

            line = f.readline()
            while line:
                stuff = line.split()
                if len(stuff) > 0:
                    if 'v' in stuff[0]:
                        vectors.append([
                            float(stuff[1]),
                            float(stuff[2]),
                            float(stuff[3])
                        ])
                    if stuff[0] == 'f':
                        faces = []
                        for i in stuff[1:]:
                            faces.append(int(i) - 1)
                        polygons.append(faces)

                #print(line.strip('\n'))
                line = f.readline()

            for poly in polygons:
                if len(poly) > 3:
                    p0 = vectors[poly[0]]
                    p1 = vectors[poly[1]]
                    p2 = vectors[poly[2]]
                    add_polygon(tmp, p0[0], p0[1], p0[2], p1[0], p1[1], p1[2],
                                p2[0], p2[1], p2[2])
                    p0 = vectors[poly[0]]
                    p1 = vectors[poly[2]]
                    p2 = vectors[poly[3]]
                    add_polygon(tmp, p0[0], p0[1], p0[2], p1[0], p1[1], p1[2],
                                p2[0], p2[1], p2[2])
                else:
                    p0 = vectors[poly[0]]
                    p1 = vectors[poly[1]]
                    p2 = vectors[poly[2]]
                    add_polygon(tmp, p0[0], p0[1], p0[2], p1[0], p1[1], p1[2],
                                p2[0], p2[1], p2[2])
            matrix_mult(stack[-1], tmp)

            if command['constants']:
                reflect = command['constants']
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols,
                          reflect, shading)
        elif c == 'shading':
            symbols['shade_type'] = command['shade_type']
        elif c == 'push':
            stack.append([x[:] for x in stack[-1]])
        elif c == 'pop':
            stack.pop()
        elif c == 'display':
            display(screen)
        elif c == 'save':
            save_extension(screen, args[0])
示例#46
0
def run(filename):
    """
    This function runs an mdl script
    """
    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    view = [0, 0, 1]
    ambient = [50, 50, 50]
    light = [[0.5, 0.75, 1], [255, 255, 255]]

    color = [0, 0, 0]
    tmp = new_matrix()
    ident(tmp)

    systems = [[x[:] for x in tmp]]
    screen = new_screen()
    zbuffer = new_zbuffer()
    tmp = []
    step_3d = 100
    consts = ''
    edges = []
    polygons = []
    symbols['.white'] = [
        'constants', {
            'red': [0.2, 0.5, 0.5],
            'green': [0.2, 0.5, 0.5],
            'blue': [0.2, 0.5, 0.5]
        }
    ]
    reflect = '.white'

    #print symbols
    for command in commands:
        if command['op'] == 'sphere':
            add_sphere(polygons, float(command['args'][0]),
                       float(command['args'][1]), float(command['args'][2]),
                       float(command['args'][3]), step_3d)
            matrix_mult(systems[-1], polygons)

            if command['constants'] == None:
                reflect = '.white'
            else:
                reflect = command['constants']

            draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                          symbols, reflect)
            polygons = []

        elif command['op'] == 'torus':
            #print 'TORUS\t' + str(args)
            add_torus(polygons, float(command['args'][0]),
                      float(command['args'][1]), float(command['args'][2]),
                      float(command['args'][3]), float(command['args'][4]),
                      step_3d)
            matrix_mult(systems[-1], polygons)

            if command['constants'] == None:
                reflect = '.white'
            else:
                reflect = command['constants']

            draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                          symbols, reflect)
            polygons = []

        elif command['op'] == 'box':
            #print 'BOX\t' + str(args)
            add_box(polygons, float(command['args'][0]),
                    float(command['args'][1]), float(command['args'][2]),
                    float(command['args'][3]), float(command['args'][4]),
                    float(command['args'][5]))
            matrix_mult(systems[-1], polygons)

            if command['constants'] == None:
                reflect = '.white'
            else:
                reflect = command['constants']

            draw_polygons(polygons, screen, zbuffer, view, ambient, light,
                          symbols, reflect)
            polygons = []

        elif command['op'] == 'circle':
            #print 'CIRCLE\t' + str(args)
            add_circle(edges, float(command['args'][0]),
                       float(command['args'][1]), float(command['args'][2]),
                       float(command['args'][3]), step)
            matrix_mult(systems[-1], edges)
            draw_lines(edges, screen, zbuffer, color)
            edges = []

        elif command['op'] == 'hermite' or command['op'] == 'bezier':
            #print 'curve\t' + line + ": " + str(args)
            add_curve(edges, float(command['args'][0]),
                      float(command['args'][1]), float(command['args'][2]),
                      float(command['args'][3]), float(command['args'][4]),
                      float(command['args'][5]), float(command['args'][6]),
                      float(command['args'][7]), step, line)
            matrix_mult(systems[-1], edges)
            draw_lines(edges, screen, zbuffer, color)
            edges = []

        elif command['op'] == 'line':
            #print 'LINE\t' + str(args)

            add_edge(edges, float(command['args'][0]),
                     float(command['args'][1]), float(command['args'][2]),
                     float(command['args'][3]), float(command['args'][4]),
                     float(command['args'][5]))
            matrix_mult(systems[-1], edges)
            draw_lines(eges, screen, zbuffer, color)
            edges = []

        elif command['op'] == 'scale':
            #print 'SCALE\t' + str(args)
            t = make_scale(float(command['args'][0]),
                           float(command['args'][1]),
                           float(command['args'][2]))
            matrix_mult(systems[-1], t)
            systems[-1] = [x[:] for x in t]

        elif command['op'] == 'move':
            #print 'MOVE\t' + str(args)
            t = make_translate(float(command['args'][0]),
                               float(command['args'][1]),
                               float(command['args'][2]))
            matrix_mult(systems[-1], t)
            systems[-1] = [x[:] for x in t]

        elif command['op'] == 'rotate':
            #print 'ROTATE\t' + str(args)
            theta = float(command['args'][1]) * (math.pi / 180)
            if command['args'][0] == 'x':
                t = make_rotX(theta)
            elif command['args'][0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            matrix_mult(systems[-1], t)
            systems[-1] = [x[:] for x in t]

        elif command['op'] == 'push':
            systems.append([x[:] for x in systems[-1]])

        elif command['op'] == 'pop':
            systems.pop()

        elif command['op'] == 'display' or command['op'] == 'save':
            if command['op'] == 'display':
                display(screen)
            else:
                save_extension(screen, command['args'][0] + ".png")
        print command
示例#47
0
def run(filename):
    """
    This function runs an mdl script
    """

    view = [0, 0, 1]
    ambient = [50, 50, 50]
    light = [[0.5, 0.75, 1], [0, 255, 255]]
    areflect = [0.1, 0.1, 0.1]
    dreflect = [0.5, 0.5, 0.5]
    sreflect = [0.5, 0.5, 0.5]

    color = [0, 0, 0]
    tmp = new_matrix()
    ident(tmp)

    stack = [[x[:] for x in tmp]]
    screen = new_screen()
    zbuffer = new_zbuffer()
    tmp = []
    step_3d = 20
    consts = ''
    coords = []
    coords1 = []

    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    first_pass(commands)
    second_pass(commands)
    print "Basename:", base
    print "Num Frames: ", num_frames
    print symbols

    for frame in range(int(num_frames)):
        print frame
        print symbols

        for knob in knobs[frame]:
            symbols[knob][1] = knobs[frame][knob]

        for command in commands:
            #print command
            c = command['op']
            args = command['args']

            if (not args == None):
                args = args[:]

            if (c in ["move", "scale", "rotate"]) and (not args == None) and (
                    "knob" in command) and (not command["knob"] == None):
                knob = command["knob"]
                #print command
                for i in range(len(args)):
                    if not isinstance(args[i], basestring):
                        args[i] = args[i] * symbols[knob][1]

            if c == 'box':
                if isinstance(args[0], str):
                    consts = args[0]
                    args = args[1:]
                if isinstance(args[-1], str):
                    coords = args[-1]
                add_box(tmp, args[0], args[1], args[2], args[3], args[4],
                        args[5])
                matrix_mult(stack[-1], tmp)
                draw_polygons(tmp, screen, zbuffer, view, ambient, light,
                              areflect, dreflect, sreflect)
                tmp = []
            elif c == 'sphere':
                add_sphere(tmp, args[0], args[1], args[2], args[3], step_3d)
                matrix_mult(stack[-1], tmp)
                draw_polygons(tmp, screen, zbuffer, view, ambient, light,
                              areflect, dreflect, sreflect)
                tmp = []
            elif c == 'torus':
                add_torus(tmp, args[0], args[1], args[2], args[3], args[4],
                          step_3d)
                matrix_mult(stack[-1], tmp)
                draw_polygons(tmp, screen, zbuffer, view, ambient, light,
                              areflect, dreflect, sreflect)
                tmp = []
            elif c == 'line':
                if isinstance(args[0], str):
                    consts = args[0]
                    args = args[1:]
                if isinstance(args[3], str):
                    coords = args[3]
                    args = args[:3] + args[4:]
                if isinstance(args[-1], str):
                    coords1 = args[-1]
                add_edge(tmp, args[0], args[1], args[2], args[3], args[4],
                         args[5])
                matrix_mult(stack[-1], tmp)
                draw_lines(tmp, screen, zbuffer, color)
                tmp = []
            elif c == 'move':
                tmp = make_translate(args[0], args[1], args[2])
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'scale':
                tmp = make_scale(args[0], args[1], args[2])
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'rotate':
                theta = args[1] * (math.pi / 180)
                if args[0] == 'x':
                    tmp = make_rotX(theta)
                elif args[0] == 'y':
                    tmp = make_rotY(theta)
                else:
                    tmp = make_rotZ(theta)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'push':
                stack.append([x[:] for x in stack[-1]])
            elif c == 'pop':
                stack.pop()
            elif c == 'display':
                display(screen)
            elif c == 'save':
                save_extension(screen, args[0])

        if is_anim:
            save_extension(screen,
                           ("./anim/" + base + ("%03d" % int(frame)) + ".png"))

        tmp = new_matrix()
        ident(tmp)
        stack = [[x[:] for x in tmp]]
        screen = new_screen()
        zbuffer = new_zbuffer()
        tmp = []
        step_3d = 20

    if is_anim:
        make_animation(base)
示例#48
0
def run(filename):
    """
    This function runs an mdl script
    """
    view = [0, 0, 1]
    ambient = [50, 50, 50]
    light = [[0.5, 0.75, 1], [0, 255, 255]]
    areflect = [0.1, 0.1, 0.1]
    dreflect = [0.5, 0.5, 0.5]
    sreflect = [0.5, 0.5, 0.5]

    color = [0, 0, 0]
    tmp = new_matrix()
    ident(tmp)

    stack = [[x[:] for x in tmp]]
    screen = new_screen()
    zbuffer = new_zbuffer()
    tmp = []
    step_3d = 20
    consts = ''
    coords = []
    coords1 = []

    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    for command in commands:
        print command
        c = command['op']
        args = command['args']

        if c == 'box':
            if isinstance(args[0], str):
                consts = args[0]
                args = args[1:]
            if isinstance(args[-1], str):
                coords = args[-1]
            add_box(tmp, args[0], args[1], args[2], args[3], args[4], args[5])
            matrix_mult(stack[-1], tmp)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, areflect,
                          dreflect, sreflect)
            tmp = []
        elif c == 'sphere':
            add_sphere(tmp, args[0], args[1], args[2], args[3], step_3d)
            matrix_mult(stack[-1], tmp)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, areflect,
                          dreflect, sreflect)
            tmp = []
        elif c == 'torus':
            add_torus(tmp, args[0], args[1], args[2], args[3], args[4],
                      step_3d)
            matrix_mult(stack[-1], tmp)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, areflect,
                          dreflect, sreflect)
            tmp = []
        elif c == 'cone':
            add_cone(tmp, args[0], args[1], args[2], args[3], args[4], step_3d)
            matrix_mult(stack[-1], tmp)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, areflect,
                          dreflect, sreflect)
            tmp = []
        elif c == 'coil':
            add_coil(tmp, args[0], args[1], args[2], args[3], args[4], args[5],
                     args[6], step_3d)
            matrix_mult(stack[-1], tmp)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, areflect,
                          dreflect, sreflect)
            tmp = []
        elif c == 'starburst':
            add_starburst(tmp, args[0], args[1], args[2], args[3], args[4],
                          args[5], step_3d)
            matrix_mult(stack[-1], tmp)
            draw_polygons(tmp, screen, zbuffer, view, ambient, light, areflect,
                          dreflect, sreflect)
            tmp = []
        elif c == 'line':
            if isinstance(args[0], str):
                consts = args[0]
                args = args[1:]
            if isinstance(args[3], str):
                coords = args[3]
                args = args[:3] + args[4:]
            if isinstance(args[-1], str):
                coords1 = args[-1]
            add_edge(tmp, args[0], args[1], args[2], args[3], args[4], args[5])
            matrix_mult(stack[-1], tmp)
            draw_lines(tmp, screen, zbuffer, color)
            tmp = []
        elif c == 'move':
            tmp = make_translate(args[0], args[1], args[2])
            matrix_mult(stack[-1], tmp)
            stack[-1] = [x[:] for x in tmp]
            tmp = []
        elif c == 'scale':
            tmp = make_scale(args[0], args[1], args[2])
            matrix_mult(stack[-1], tmp)
            stack[-1] = [x[:] for x in tmp]
            tmp = []
        elif c == 'rotate':
            theta = args[1] * (math.pi / 180)
            if args[0] == 'x':
                tmp = make_rotX(theta)
            elif args[0] == 'y':
                tmp = make_rotY(theta)
            else:
                tmp = make_rotZ(theta)
            matrix_mult(stack[-1], tmp)
            stack[-1] = [x[:] for x in tmp]
            tmp = []
        elif c == 'push':
            stack.append([x[:] for x in stack[-1]])
        elif c == 'pop':
            stack.pop()
        elif c == 'display':
            display(screen)
        elif c == 'save':
            save_extension(screen, args[0])
示例#49
0
def parse_file( fname, points, transform, screen, color ):
    one_liners = {'ident': ident, 'apply': matrix_mult, 'display': display}
    two_liners = {'line': add_edge, 'scale': make_scale, 'move': make_translate, 'rotate': 'make_rot', 'save': save_extension}
    with open(fname) as file_:
        file_content = file_.readlines()
    for line_num, line in enumerate(file_content):
        line = line.strip()
        if line[0].isdigit() or file_content[line_num - 1].strip() == 'rotate' or file_content[line_num - 1].strip() == 'save':
            continue
        if line in one_liners:
            if line == 'ident':
                one_liners[line](transform)
            elif line == 'apply':
                one_liners[line](transform, points)
            else:
                clear_screen(screen)
                draw_lines(points, screen, color)
                one_liners[line](screen)
        elif line in two_liners:
            if line == 'line':
                next_line = file_content[line_num + 1].strip()
                args = next_line.split(' ')
                if valid_num_of_args(line_num, args, 6):
                    two_liners[line](points, args[0], args[1], args[2], args[3], args[4], args[5], line_num=line_num)
            elif line == 'scale':
                next_line = file_content[line_num + 1].strip()
                args = next_line.split(' ')
                if valid_num_of_args(line_num, args, 3):
                    scale_matrix = two_liners[line](args[0], args[1], args[2], line_num=line_num)
                    matrix_mult(scale_matrix, transform)
            elif line == 'move':
                next_line = file_content[line_num + 1].strip()
                args = next_line.split(' ')
                if valid_num_of_args(line_num, args, 3):
                    translate_matrix = two_liners[line](args[0], args[1], args[2], line_num=line_num)
                    matrix_mult(translate_matrix, transform)
            elif line == 'rotate':
                next_line = file_content[line_num + 1].strip()
                args = next_line.split(' ')
                if valid_num_of_args(line_num, args, 2):
                    if args[0] in 'xyzXYZ':
                        function = eval(two_liners[line] + args[0].upper())
                    else:
                        print 'Line ' + str(line_num + 2) + ' provided an invalid axis...'
                        raise SystemExit(1)                    
                    rotate_matrix = function(args[1], line_num=line_num)
                    matrix_mult(rotate_matrix, transform)
            elif line == 'save':
                next_line = file_content[line_num + 1].strip()
                args = next_line.split(' ')
                if valid_num_of_args(line_num, args, 1):
                    clear_screen(screen)
                    draw_lines(points, screen, color)
                    display(screen)
                    if args[0].endswith('.png'):
                        two_liners[line](screen, args[0])
                    else:
                        print 'Invalid filename at line ' + str(line_num + 2)
                        raise SystemExit(1)
        else:
            print 'Invalid command found at line ' + str(line_num)
            raise SystemExit(1)
示例#50
0
def parse_file(fname, screen, color):

    transform = new_matrix()
    ident(transform)
    transform = [transform]

    f = open(fname)
    lines = f.readlines()

    step = 0.01
    c = 0
    while c < len(lines):
        line = lines[c].strip()
        #print ':' + line + ':'

        if line in ARG_COMMANDS:
            c += 1
            args = lines[c].strip().split(' ')

        if line == 'push':
            transform.append(transform[len(transform) - 1][:])

        if line == 'pop':
            transform = transform[:-1]

        if line == 'circle':
            #print 'CIRCLE\t' + str(args)
            temp = []
            add_circle(temp, float(args[0]), float(args[1]), float(args[2]),
                       float(args[3]), step)
            matrix_mult(transform[-1], temp)
            draw_lines(temp, screen, color)

        elif line == 'hermite' or line == 'bezier':
            #print 'curve\t' + line + ": " + str(args)
            temp = []
            add_curve(edges, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), float(args[5]),
                      float(args[6]), float(args[7]), step, line)
            matrix_mult(transform[-1], temp)
            draw_lines(temp, screen, color)

        elif line == 'line':
            #print 'LINE\t' + str(args)
            temp = []
            add_edge(temp, float(args[0]), float(args[1]), float(args[2]),
                     float(args[3]), float(args[4]), float(args[5]))
            matrix_mult(transform[-1], temp)

        elif line == 'scale':
            #print 'SCALE\t' + str(args)
            t = make_scale(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(transform[-1], t)
            transform[-1] = t

        elif line == 'move':
            #print 'MOVE\t' + str(args)
            t = make_translate(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(transform[-1], t)
            transform[-1] = t

        elif line == 'rotate':
            #print 'ROTATE\t' + str(args)
            theta = float(args[1]) * (math.pi / 180)

            if args[0] == 'x':
                t = make_rotX(theta)
            elif args[0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            matrix_mult(transform[-1], t)
            transform[-1] = t

        elif line == 'box':
            for i in range(len(args)):
                args[i] = int(args[i])
            temp = []
            add_box(temp, args[0], args[1], args[2], args[3], args[4], args[5])
            print len(temp)
            matrix_mult(transform[-1], temp)
            draw_polygons(temp, screen, color)

        elif line == 'torus':
            for i in range(len(args)):
                args[i] = int(args[i])
            temp = []
            add_torus(temp, args[0], args[1], args[2], args[3], args[4], .1)
            matrix_mult(transform[-1], temp)
            draw_polygons(temp, screen, color)

        elif line == 'sphere':
            for i in range(len(args)):
                args[i] = int(args[i])
            temp = []
            add_sphere(temp, args[0], args[1], args[2], args[3], .04999999)
            matrix_mult(transform[-1], temp)
            draw_polygons(temp, screen, color)

        elif line == 'ident':
            ident(transform)

        elif line == 'apply':
            matrix_mult(transform, edges)

        elif line == 'display' or line == 'save':
            if line == 'display':
                display(screen)
            else:
                save_extension(screen, args[0])

        elif line == 'clear':
            edges = [[]]

        c += 1
示例#51
0
def parse_file(file, edge, polygons, transform, screen, color):
    global stack
    lines = genLines(file)
    ident(transform)
    x = 0
    while x < len(lines):
        if lines[x] == "line":
            p = [int(y) for y in lines[x + 1].split(" ")]
            add_edge(edge, p[0], p[1], p[2], p[3], p[4], p[5])
            matrix_mult(stack[-1], edge)
            draw_lines(edge, screen, DRAW_COLOR)
            del edge[:]
            x += 1
        elif lines[x] == "circle":
            p = [int(y) for y in lines[x + 1].split(" ")]
            add_circle(edge, p[0], p[1], p[2], p[3], 10000)
            matrix_mult(stack[-1], edge)
            draw_lines(edge, screen, DRAW_COLOR)
            del edge[:]
            x += 1
        elif lines[x] == "triangle":
            p = [int(y) for y in lines[x + 1].split(" ")]
            add_polygon(polygons, p[0], p[1], p[2], p[3], p[4], p[5], p[6],
                        p[7], p[8])
            matrix_mult(stack[-1], polygons)
            draw_polygons(polygons, screen, DRAW_COLOR)
            del polygons[:]
            x += 1
        elif lines[x] == "hermite":
            p = [int(y) for y in lines[x + 1].split(" ")]
            add_hermite(edge, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7])
            matrix_mult(stack[-1], edge)
            draw_lines(edge, screen, DRAW_COLOR)
            del edge[:]
            x += 1
        elif lines[x] == "bezier":
            p = [int(y) for y in lines[x + 1].split(" ")]
            add_bezier(edge, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7])
            matrix_mult(stack[-1], edge)
            draw_lines(edge, screen, DRAW_COLOR)
            del edge[:]
            x += 1
        elif lines[x] == "torus":
            p = [int(y) for y in lines[x + 1].split(" ")]
            add_torus(polygons, p[0], p[1], p[2], p[3], p[4], steps_3d)
            matrix_mult(stack[-1], polygons)
            draw_polygons(polygons, screen, DRAW_COLOR)
            del polygons[:]
            x += 1
        elif lines[x] == "sphere":
            p = [int(y) for y in lines[x + 1].split(" ")]
            add_sphere(polygons, p[0], p[1], p[2], p[3], steps_3d)
            matrix_mult(stack[-1], polygons)
            draw_polygons(polygons, screen, DRAW_COLOR)
            del polygons[:]
            x += 1
        elif lines[x] == "box":
            p = [int(y) for y in lines[x + 1].split(" ")]
            add_box(polygons, p[0], p[1], p[2], p[3], p[4], p[5])
            matrix_mult(stack[-1], polygons)
            draw_polygons(polygons, screen, DRAW_COLOR)
            del polygons[:]
            x += 1
        elif lines[x] == "ident":
            ident(transform)
        elif lines[x] == "scale":
            f = [int(y) for y in lines[x + 1].split(" ")]
            s = []
            scale(s, f[0], f[1], f[2])
            transform_mult(stack[-1], s)
            stack[-1] = deepcopy(s)
            x += 1
        elif lines[x] == "move":
            f = [int(y) for y in lines[x + 1].split(" ")]
            move = []
            translate(move, f[0], f[1], f[2])
            transform_mult(stack[-1], move)
            stack[-1] = deepcopy(move)
            x += 1
        elif lines[x] == "rotate":
            f = lines[x + 1].split(" ")
            r = []
            rotate(r, f[0], int(f[1]))
            transform_mult(stack[-1], r)
            stack[-1] = deepcopy(r)
            x += 1
        elif lines[x] == "push":
            push(stack)
        elif lines[x] == "pop":
            pop(stack)
        elif lines[x] == "apply":
            matrix_mult(transform, edge)
            matrix_mult(transform, polygons)
        elif lines[x] == "display":
            display(screen)
        elif lines[x] == "clear":
            edge.clear()
        elif lines[x] == "save":
            save_extension(screen, lines[x + 1])
            print("File name: " + lines[x + 1])
            x += 1
        elif lines[x] == "stop":
            return
        x += 1
示例#52
0
def run(filename):
    """
    This function runs an mdl script
    """
    color = [0, 0, 0]
    tmp = new_matrix()
    ident(tmp)

    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    (name, num_frames) = first_pass(commands)
    frames = second_pass(commands, num_frames)
    step = 0.1

    for f in range(num_frames):

        tmp = new_matrix()
        ident(tmp)
        stack = [[x[:] for x in tmp]]
        screen = new_screen()
        zb = new_zbuffer()
        tmp = []

        if num_frames > 1:
            frame = frames[f]
            for knob in frame:
                symbols[knob][1] = frame[knob]

        for command in commands:
            c = command[0]
            args = command[1:]
            knob_value = 1

            if c == 'set':
                symbols[args[0]][1] = args[1]
            elif c == 'set_knobs':
                for knob in symbols:
                    if symbols[knob][0] == 'knob':
                        symbols[knob][1] = args[0]
            elif c == 'box':
                add_box(tmp, args[0], args[1], args[2], args[3], args[4],
                        args[5])
                matrix_mult(stack[-1], tmp)
                draw_polygons(tmp, screen, zb, color)
                tmp = []
            elif c == 'sphere':
                add_sphere(tmp, args[0], args[1], args[2], args[3], step)
                matrix_mult(stack[-1], tmp)
                draw_polygons(tmp, screen, zb, color)
                tmp = []
            elif c == 'torus':
                add_torus(tmp, args[0], args[1], args[2], args[3], args[4],
                          step)
                matrix_mult(stack[-1], tmp)
                draw_polygons(tmp, screen, zb, color)
                tmp = []
            elif c == 'move':
                if command[-1]:
                    knob_value = symbols[command[-1]][1]
                tmp = make_translate(args[0] * knob_value,
                                     args[1] * knob_value,
                                     args[2] * knob_value)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'scale':
                if command[-1]:
                    knob_value = symbols[command[-1]][1]
                tmp = make_scale(args[0] * knob_value, args[1] * knob_value,
                                 args[2] * knob_value)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'rotate':
                if command[-1]:
                    knob_value = symbols[command[-1]][1]

                theta = args[1] * (math.pi / 180) * knob_value
                if args[0] == 'x':
                    tmp = make_rotX(theta)
                elif args[0] == 'y':
                    tmp = make_rotY(theta)
                else:
                    tmp = make_rotZ(theta)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'push':
                stack.append([x[:] for x in stack[-1]])
            elif c == 'pop':
                stack.pop()
            elif c == 'display':
                display(screen)
            elif c == 'save':
                save_extension(screen, args[0])

        if num_frames > 1:
            fname = 'anim/%s%03d.png' % (name, f)
            print 'Saving frame: ' + fname
            save_extension(screen, fname)

    if num_frames > 1:
        make_animation(name)
示例#53
0
def run(image):
    frame = cv2.imread(image)
    frame = preprocess_image(frame)
    display([[frame]])
示例#54
0
def run(filename):
    """
    This function runs an mdl script
    """
    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    view = [0,
            0,
            1];
    ambient = [50,
               50,
               50]
    light = [[0.5,
              0.75,
              1],
             [255,
              255,
              255]]

    color = [0, 0, 0]
    symbols['.white'] = ['constants',
                         {'red': [0.2, 0.5, 0.5],
                          'green': [0.2, 0.5, 0.5],
                          'blue': [0.2, 0.5, 0.5]}]
    reflect = '.white'

    (name, num_frames) = first_pass(commands)
    frames = second_pass(commands, num_frames)
    if num_frames > 1:
        if not path.exists('anim/' + name):
            mkdir('anim/' + name)
    for i in range(num_frames):
        tmp = new_matrix()
        ident( tmp )

        stack = [ [x[:] for x in tmp] ]
        screen = new_screen()
        zbuffer = new_zbuffer()
        tmp = []
        step_3d = 100
        consts = ''
        coords = []
        coords1 = []

        if num_frames > 1:
            for knob in frames[i]:
                symbols[knob][1] = frames[i][knob]

        for command in commands:
            print command
            c = command['op']
            args = command['args']
            v = 1

            if c == 'box':
                if command['constants']:
                    reflect = command['constants']
                add_box(tmp,
                        args[0], args[1], args[2],
                        args[3], args[4], args[5])
                matrix_mult( stack[-1], tmp )
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
                reflect = '.white'
            elif c == 'sphere':
                if command['constants']:
                    reflect = command['constants']
                add_sphere(tmp,
                           args[0], args[1], args[2], args[3], step_3d)
                matrix_mult( stack[-1], tmp )
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
                reflect = '.white'
            elif c == 'torus':
                if command['constants']:
                    reflect = command['constants']
                add_torus(tmp,
                          args[0], args[1], args[2], args[3], args[4], step_3d)
                matrix_mult( stack[-1], tmp )
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
                reflect = '.white'
            elif c == 'mesh':
                if command['constants']!=':':
                    reflect = command['constants']
                add_mesh(tmp, command['cs'])
                matrix_mult(stack[-1],tmp)
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
                reflect = '.white'
            elif c == 'line':
                add_edge(tmp,
                         args[0], args[1], args[2], args[3], args[4], args[5])
                matrix_mult( stack[-1], tmp )
                draw_lines(tmp, screen, zbuffer, color)
                tmp = []
            elif c == 'move':
                if command['knob']:
                    v = symbols[command["knob"]][1]
                tmp = make_translate(args[0] * v, args[1] * v, args[2] * v)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'scale':
                if command['knob']:
                    v = symbols[command["knob"]][1]
                tmp = make_scale(args[0] * v, args[1] * v, args[2] * v)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'rotate':
                if command['knob']:
                    v = symbols[command["knob"]][1]
                theta = args[1] * (math.pi/180) * v
                if args[0] == 'x':
                    tmp = make_rotX(theta)
                elif args[0] == 'y':
                    tmp = make_rotY(theta)
                else:
                    tmp = make_rotZ(theta)
                matrix_mult( stack[-1], tmp )
                stack[-1] = [ x[:] for x in tmp]
                tmp = []
            elif c == 'push':
                stack.append([x[:] for x in stack[-1]] )
            elif c == 'pop':
                stack.pop()
            elif c == 'display':
                display(screen)
            elif c == 'save':
                save_extension(screen, args[0])
        if num_frames > 1:
            filename = 'anim/' + name + '/' + name + ('%03d'%i)
            save_extension(screen, filename)

    if num_frames > 1:
        make_animation(name)
    print symbols
示例#55
0
def parse_file(fname, edges, polygons, transform, screen, color):

    f = open(fname)
    lines = f.readlines()

    steps_2d = 100
    steps_3d = 20

    c = 0
    while c < len(lines):
        line = lines[c].strip()
        #print ':' + line + ':'

        if line in ARG_COMMANDS:
            c += 1
            args = lines[c].strip().split(' ')

        if line == 'sphere':
            #print 'SPHERE\t' + str(args)
            add_sphere(polygons, float(args[0]), float(args[1]),
                       float(args[2]), float(args[3]), steps_3d)

        elif line == 'torus':
            #print 'TORUS\t' + str(args)
            add_torus(polygons, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), steps_3d)

        elif line == 'box':
            #print 'BOX\t' + str(args)
            add_box(polygons, float(args[0]), float(args[1]), float(args[2]),
                    float(args[3]), float(args[4]), float(args[5]))

        elif line == 'circle':
            #print 'CIRCLE\t' + str(args)
            add_circle(edges, float(args[0]), float(args[1]), float(args[2]),
                       float(args[3]), steps_2d)

        elif line == 'hermite' or line == 'bezier':
            #print 'curve\t' + line + ": " + str(args)
            add_curve(edges, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), float(args[5]),
                      float(args[6]), float(args[7]), steps_2d, line)

        elif line == 'line':
            #print 'LINE\t' + str(args)

            add_edge(edges, float(args[0]), float(args[1]), float(args[2]),
                     float(args[3]), float(args[4]), float(args[5]))

        elif line == 'scale':
            #print 'SCALE\t' + str(args)
            t = make_scale(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(t, transform)

        elif line == 'move':
            #print 'MOVE\t' + str(args)
            t = make_translate(float(args[0]), float(args[1]), float(args[2]))
            matrix_mult(t, transform)

        elif line == 'rotate':
            #print 'ROTATE\t' + str(args)
            theta = float(args[1]) * (math.pi / 180)

            if args[0] == 'x':
                t = make_rotX(theta)
            elif args[0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            matrix_mult(t, transform)

        elif line == 'ident':
            ident(transform)

        elif line == 'apply':
            matrix_mult(transform, edges)
            matrix_mult(transform, polygons)

        elif line == 'clear':
            edges = []
            polygons = []

        elif line == 'display' or line == 'save':
            clear_screen(screen)
            draw_lines(edges, screen, color)
            draw_polygons(polygons, screen, color)
            if line == 'display':
                display(screen)
            else:
                save_extension(screen, args[0])

        c += 1
示例#56
0
def parse_file(fname,
               points=[],
               transform=identity_matrix(),
               screen=new_screen(),
               color=[255, 0, 0]):
    f = open(fname, 'r')
    script = f.read().split('\n')
    i = 0
    while (i < len(script)):

        if (script[i] == 'l'):  #line
            #6 parameters: x0, y0, z0, x1, y1, z1
            i += 1
            p = script[i].split(" ")
            for j in range(len(p)):
                p[j] = float(p[j])
            if (len(p) != 6):
                print "add_edge: invalid number of arguments"
            else:
                add_edge(points, p[0], p[1], p[2], p[3], p[4], p[5])

        elif (script[i] == 'i'):  #identity
            #0 parameters
            transform = identity_matrix()
        elif (script[i] == 't'):  #translate
            #3 parameters: x_translation, y_translation, z_translation
            i += 1
            p = script[i].split(" ")
            for j in range(len(p)):
                p[j] = float(p[j])
            if (len(p) != 3):
                print "translate: invalid number of arguments"
            else:
                transform = matrix_mult(translate(p[0], p[1], p[2]), transform)
        elif (script[i] == 's'):  #scale
            #3 parameters: x_scale, y_scale, z_scale
            i += 1
            p = script[i].split(" ")
            for j in range(len(p)):
                p[j] = float(p[j])
            if (len(p) != 3):
                print "scale: invalid number of arguments"
            else:
                transform = matrix_mult(scale(p[0], p[1], p[2]), transform)
        elif (script[i] == 'x'):  #xrot
            #1 parameter: radians
            i += 1
            transform = matrix_mult(rotX(script[i]), transform)
        elif (script[i] == 'y'):  #yrot
            #1 parameter: radians
            i += 1
            transform = matrix_mult(rotY(script[i]), transform)
        elif (script[i] == 'z'):  #zrot
            #1 parameter: radians
            i += 1
            transform = matrix_mult(rotZ(script[i]), transform)
        elif (script[i] == 'a'):  #apply
            #0 parameters
            points = matrix_mult(transform, points)

        elif (script[i] == 'c'):  #circle
            #3 parameters: center_x, center_y, radius
            i += 1
            p = script[i].split(" ")
            for j in range(len(p)):
                p[j] = float(p[j])
            if (len(p) != 3):
                print "add_circle: invalid number of arguments"
            else:
                add_circle(points, p[0], p[1], 0, p[2], .01)
        elif (script[i] == 'h'):  #hermite
            #8 parameters: x0, y0, dx0, dy0, x1, y1, dx1, dy1
            #(x0, y0) and (x1, y1) - endpoints
            #(dx1, dy1) and (dx1, dy1) - rates of change at the endpoints
            i += 1
            p = script[i].split(" ")
            for j in range(len(p)):
                p[j] = float(p[j])
            if (len(p) != 8):
                print "add_curve: invalid number of arguments"
            else:
                add_curve(points, p[0], p[1], p[2], p[3], p[4], p[5], p[6],
                          p[7], .01, "hermite")
        elif (script[i] == 'b'):  #bezier
            #8 parameters: x0, y0, x1, y1, x2, y2, x3, y3
            #(x0, y0) and (x3, y3) - endpoints
            #(x1, y1) and (x2, y2) - points of influence
            i += 1
            p = script[i].split(" ")
            for j in range(len(p)):
                p[j] = float(p[j])
            if (len(p) != 8):
                print "add_curve: invalid number of arguments"
            else:
                add_curve(points, p[0], p[1], p[2], p[3], p[4], p[5], p[6],
                          p[7], .01, "bezier")

        elif (script[i] == 'v'):  #view
            #0 parameters
            draw_lines(points, screen, color)
            pic_name = str(i) + ".ppm"
            display(screen, pic_name)
            clear_screen(screen)
            remove(pic_name)
        elif (script[i] == 'g'):  #guh-save
            #1 parameter: filename
            draw_lines(points, screen, color)
            i += 1
            save_extension(
                screen, script[i]
            )  #there is some issue here; file extension changed, not actually converting file
            display(screen, script[i])
            clear_screen(screen)
        elif (script[i] == 'p'):  #print
            #0 parameters
            print "\nPOINTS:", points, "\n"
        else:
            print "parse_file: iteration " + str(
                i) + ": argument invalid(" + script[i] + ")"
        i += 1  #go to next line
    return
示例#57
0
def run(filename):
    """
    This function runs an mdl script
    """
    p = mdl.parseFile(filename)

    if p:
        (commands, symbols) = p
    else:
        print "Parsing failed."
        return

    view = [0,
            0,
            1];
    ambient = [50,
               50,
               50]
    light = [[0.5,
              0.75,
              1],
             [255,
              255,
              255]]

    color = [0, 0, 0]
    symbols['.white'] = ['constants',
                         {'red': [0.2, 0.5, 0.5],
                          'green': [0.2, 0.5, 0.5],
                          'blue': [0.2, 0.5, 0.5]}]
    reflect = '.white'

    (name, num_frames) = first_pass(commands)
    frames = second_pass(commands, num_frames)


    tmp = new_matrix()
    ident( tmp )

    stack = [ [x[:] for x in tmp] ]
    screen = new_screen()
    zbuffer = new_zbuffer()
    tmp = []
    step_3d = 100
    consts = ''
    coords = []
    coords1 = []


    fileNum = 0
    print(symbols)
    for frame in frames:
        for key in frame.keys():
            symbols[key] = frame[key]
        for command in commands:
            c = command['op']
            args = command['args']
            knob_value = 1

            if c == 'box':
                if command['constants']:
                    reflect = command['constants']
                add_box(tmp,
                        args[0], args[1], args[2],
                        args[3], args[4], args[5])
                matrix_mult( stack[-1], tmp )
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
                reflect = '.white'
            elif c == 'sphere':
                if command['constants']:
                    reflect = command['constants']
                add_sphere(tmp,
                           args[0], args[1], args[2], args[3], step_3d)
                matrix_mult( stack[-1], tmp )
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
                reflect = '.white'
            elif c == 'torus':
                if command['constants']:
                    reflect = command['constants']
                add_torus(tmp,
                          args[0], args[1], args[2], args[3], args[4], step_3d)
                matrix_mult( stack[-1], tmp )
                draw_polygons(tmp, screen, zbuffer, view, ambient, light, symbols, reflect)
                tmp = []
                reflect = '.white'
            elif c == 'line':
                add_edge(tmp,
                         args[0], args[1], args[2], args[3], args[4], args[5])
                matrix_mult( stack[-1], tmp )
                draw_lines(tmp, screen, zbuffer, color)
                tmp = []
            elif c == 'move':
                knobName = command['knob']
                if knobName:
                    tmp = make_translate(args[0]*symbols[knobName], args[1]*symbols[knobName], args[2]*symbols[knobName])
                else:
                    tmp = make_translate(args[0], args[1], args[2])
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'scale':
                knobName = command['knob']
                if knobName:
                    tmp = make_scale(args[0]*symbols[knobName], args[1]*symbols[knobName], args[2]*symbols[knobName])
                else:
                    tmp = make_scale(args[0], args[1], args[2])
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'rotate':
                knobName = command['knob']
                if knobName:
                    theta = args[1] * (math.pi/180) * symbols[knobName]
                else:
                    theta = args[1] * (math.pi/180)
                if args[0] == 'x':
                    tmp = make_rotX(theta)
                elif args[0] == 'y':
                    tmp = make_rotY(theta)
                else:
                    tmp = make_rotZ(theta)
                matrix_mult( stack[-1], tmp )
                stack[-1] = [ x[:] for x in tmp]
                tmp = []
            elif c == 'push':
                stack.append([x[:] for x in stack[-1]] )
            elif c == 'pop':
                stack.pop()
            elif c == 'display':
                display(screen)
            elif c == 'save':
                save_extension(screen, args[0])
        # end operation loop
        save_extension(screen, "anim/" + name+ "_" +"%03d"%fileNum)
        fileNum += 1
        print(fileNum)
        tmp = new_matrix()
        ident(tmp)
        stack = [ [x[:] for x in tmp] ]
        screen = new_screen()
        zbuffer = new_zbuffer()
    make_animation(name)
def third_pass(commands, symbols):
    global knoblist
    global basename

    count = 0
    while count < num_frames:  #start of outer loop
        #print(symbols)

        color = [255, 255, 255]
        tmp = new_matrix()
        ident(tmp)

        ident(tmp)
        stack = [[x[:] for x in tmp]]
        screen = new_screen()
        tmp = []
        step = 0.1
        for command in commands:
            c = command[0]
            args = command[1:]
            #print args

            if c == 'box':
                add_box(tmp, args[0], args[1], args[2], args[3], args[4],
                        args[5])
                matrix_mult(stack[-1], tmp)
                draw_polygons(tmp, screen, color)
                tmp = []
            elif c == 'sphere':
                add_sphere(tmp, args[0], args[1], args[2], args[3], step)
                matrix_mult(stack[-1], tmp)
                draw_polygons(tmp, screen, color)
                tmp = []
            elif c == 'torus':
                add_torus(tmp, args[0], args[1], args[2], args[3], args[4],
                          step)
                matrix_mult(stack[-1], tmp)
                draw_polygons(tmp, screen, color)
                tmp = []
            elif c == 'move':
                val = 1
                if (args[3] != None):
                    knob = args[3]
                    symbols[knob][1] = knoblist[count][knob]
                    val = knoblist[count][knob]
                tmp = make_translate(args[0] * val, args[1] * val,
                                     args[2] * val)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'scale':
                val = 1
                if (args[3] != None):
                    knob = args[3]
                    symbols[knob][1] = knoblist[count][knob]
                    val = knoblist[count][knob]
                tmp = make_scale(args[0] * val, args[1] * val, args[2] * val)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'rotate':
                val = 1
                if (args[2] != None):
                    knob = args[2]
                    symbols[knob][1] = knoblist[count][knob]
                    val = knoblist[count][knob]
                theta = args[1] * (math.pi / 180)
                if args[0] == 'x':
                    tmp = make_rotX(theta * val)
                elif args[0] == 'y':
                    tmp = make_rotY(theta * val)
                else:
                    tmp = make_rotZ(theta * val)
                matrix_mult(stack[-1], tmp)
                stack[-1] = [x[:] for x in tmp]
                tmp = []
            elif c == 'push':
                stack.append([x[:] for x in stack[-1]])
            elif c == 'pop':
                stack.pop()
            elif c == 'display':
                display(screen)
            #elif c == 'save':

        if (count < 10):
            save_extension(screen,
                           "anim/" + basename + "0" + str(count) + ".png")
            print("Frame saved to: " + basename + "0" + str(count))
        else:
            save_extension(screen, "anim/" + basename + str(count) + ".png")
            print("Frame saved to: " + basename + str(count))

        count += 1
示例#59
0
文件: main.py 项目: akratsios/Matrix
add_edge(matrix, 20, 20, 1, 20, 50, 1)
add_edge(matrix, 20, 50, 1, 50, 50, 1)
add_edge(matrix, 50, 50, 1, 50, 20, 1)
add_edge(matrix, 50, 20, 1, 20, 20, 1)

add_edge(matrix, 200, 200, 1, 200, 250, 1)
add_edge(matrix, 200, 250, 1, 250, 250, 1)
add_edge(matrix, 250, 250, 1, 250, 200, 1)
add_edge(matrix, 250, 200, 1, 200, 200, 1)

add_edge(matrix, 100, 100, 1, 100, 250, 1)
add_edge(matrix, 100, 250, 1, 250, 250, 1)
add_edge(matrix, 250, 250, 1, 250, 100, 1)
add_edge(matrix, 250, 100, 1, 100, 100, 1)

edge[0].extend(matrix[0])
edge[1].extend(matrix[1])
edge[2].extend(matrix[2])
edge[3].extend(matrix[3])

    
for n in xrange(50):
    trans_matrix = matrix_mult(
        matrix_mult(make_translate(x,y,0), make_rotZ(pi/4)),
        make_translate(-x,-y,0))
    edge = matrix_mult(trans_matrix, edge)
    draw_lines(edge, screen, color)
    
    
display(screen)
示例#60
0
def parse_file(fname, stack, edges, polygons, transform, screen, color):

    f = open(fname)
    lines = f.readlines()

    step = 100
    step_3d = 20

    c = 0
    '''
    cs = []
    ident1 = new_matrix()
    print_matrix(ident1)
    ident(ident1)
    cs.append(ident1)
    '''
    #print_matrix(cs[0])

    while c < len(lines):
        line = lines[c].strip()
        #print ':' + line + ':'

        if line in ARG_COMMANDS:
            c += 1
            args = lines[c].strip().split(' ')
            #print 'args\t' + str(args)

        if line == 'sphere':
            #print 'SPHERE\t' + str(args)
            add_sphere(polygons, float(args[0]), float(args[1]),
                       float(args[2]), float(args[3]), step_3d)
            matrix_mult(stack[-1:][0], polygons)
            draw_polygons(polygons, screen, color)
            polygons = []

        #NEW STUFF ---------------

        elif line == 'push':
            push_helper(stack)

        elif line == 'pop':
            stack.pop()

        #\NEW STUFF --------------

        elif line == 'torus':
            #print 'TORUS\t' + str(args)
            add_torus(polygons, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), step_3d)
            matrix_mult(stack[-1:][0], polygons)
            draw_polygons(polygons, screen, color)
            polygons = []

        elif line == 'box':
            #print 'BOX\t' + str(args)
            add_box(polygons, float(args[0]), float(args[1]), float(args[2]),
                    float(args[3]), float(args[4]), float(args[5]))
            matrix_mult(stack[-1:][0], polygons)
            draw_polygons(polygons, screen, color)
            polygons = []

        elif line == 'circle':
            #print 'CIRCLE\t' + str(args)
            add_circle(edges, float(args[0]), float(args[1]), float(args[2]),
                       float(args[3]), step)
            matrix_mult(stack[-1:][0], edges)
            draw_lines(edges, screen, color)
            edges = []

        elif line == 'hermite' or line == 'bezier':
            #print 'curve\t' + line + ": " + str(args)
            add_curve(edges, float(args[0]), float(args[1]), float(args[2]),
                      float(args[3]), float(args[4]), float(args[5]),
                      float(args[6]), float(args[7]), step, line)
            matrix_mult(stack[-1:][0], edges)
            draw_lines(edges, screen, color)
            edges = []

        elif line == 'line':
            #print 'LINE\t' + str(args)

            add_edge(edges, float(args[0]), float(args[1]), float(args[2]),
                     float(args[3]), float(args[4]), float(args[5]))
            matrix_mult(stack[-1:][0], edges)
            draw_lines(edges, screen, color)
            edges = []

        elif line == 'scale':
            #print 'SCALE\t' + str(args)
            t = make_scale(float(args[0]), float(args[1]), float(args[2]))
            #matrix_mult(t, transform)
            matrix_mult(stack[-1:][0], t)
            stack[-1] = t

        elif line == 'move':
            #print 'MOVE\t' + str(args)
            t = make_translate(float(args[0]), float(args[1]), float(args[2]))
            #matrix_mult(t, transform)
            matrix_mult(stack[-1:][0], t)
            stack[-1] = t

        elif line == 'rotate':
            #print 'ROTATE\t' + str(args)
            theta = float(args[1]) * (math.pi / 180)

            if args[0] == 'x':
                t = make_rotX(theta)
            elif args[0] == 'y':
                t = make_rotY(theta)
            else:
                t = make_rotZ(theta)
            #matrix_mult(t, transform)
            matrix_mult(stack[-1:][0], t)
            stack[-1] = t

        elif line == 'clear':
            edges = []
            polygons = []

        elif line == 'ident':
            ident(transform)

        elif line == 'apply':
            matrix_mult(transform, edges)
            matrix_mult(transform, polygons)

        elif line == 'display' or line == 'save':
            #clear_screen(screen)
            #draw_lines(edges, screen, color)
            #draw_polygons(polygons, screen, color)

            if line == 'display':
                display(screen)
            else:
                save_extension(screen, args[0])
        c += 1