source: tools/generate_poly.py

Last change on this file was 445:79ba44e04b57, checked in by Simon Cross <hodgestar@…>, 8 years ago

Add offset support.

File size: 2.7 KB
Line 
1import optparse
2import sys
3import math
4
5
6def parse_params(args):
7 params = {}
8 for arg in args:
9 key, _, value = arg.partition("=")
10 params[key] = value
11 return params
12
13
14def parse_args(args):
15 """Parse arguments."""
16 parser = optparse.OptionParser(usage="%prog <type> arg1=foo arg2=bar")
17
18 parser.add_option('-x',
19 dest='offset_x', type=int, default=0,
20 help='X offset for poly.')
21
22 parser.add_option('-y',
23 dest='offset_y', type=int, default=0,
24 help='Y offset for poly.')
25
26 opts, args = parser.parse_args(args)
27 args = args[1:]
28
29 if not args:
30 parser.print_help()
31 return None, {}, opts
32
33 obj_type = args[0]
34 params = parse_params(args[1:])
35 return obj_type, params, opts
36
37
38class PolyGenerator(object):
39 def __init__(self, opts):
40 self.offset_x = opts.offset_x
41 self.offset_y = opts.offset_y
42
43 def generate(self, obj_type, params):
44 handler = getattr(self, 'generate_%s' % (obj_type,),
45 self.unknown_type)
46 return handler(params)
47
48 def print_poly(self, poly):
49 print "Poly:"
50 for point in poly:
51 print " - [%d, %d]" % tuple(point)
52
53 def unknown_type(self, params):
54 prefix = "generate_"
55 known_types = [k[len(prefix):] for k in self.__dict__
56 if k.startswith(prefix)]
57 raise ValueError("Unknown object type. Known types: %s" %
58 ",".join(known_types))
59
60 def check_params(self, params, *sigs):
61 results = []
62 for name, parser in sigs:
63 value = params.get(name)
64 try:
65 result = parser(value)
66 except:
67 raise ValueError(
68 "Failed to parse param %s with value %s (parser: %r)"
69 % (name, value, parser))
70 results.append(result)
71 return results
72
73 def apply_opts(self, poly):
74 new_poly = []
75 for p in poly:
76 x = p[0] + self.offset_x
77 y = p[1] + self.offset_y
78 new_poly.append([x, y])
79 return new_poly
80
81 def generate_circle(self, params):
82 r, steps = self.check_params(params, ("r", int), ("steps", int))
83 poly = []
84 rad, step_size = 0, 2 * math.pi / steps
85 for p in range(steps + 1):
86 x, y = r * math.sin(rad), r * math.cos(rad)
87 poly.append([x, y])
88 rad += step_size
89 return self.apply_opts(poly)
90
91
92if __name__ == "__main__":
93 obj_type, params, opts = parse_args(sys.argv)
94 if obj_type is not None:
95 p = PolyGenerator(opts)
96 poly = p.generate(obj_type, params)
97 p.print_poly(poly)
Note: See TracBrowser for help on using the repository browser.