comparison LightTools/Map.py @ 0:7e3a0ae9c016

Initial commit
author koryspansel <koryspansel@bendbroadband.com>
date Wed, 07 Sep 2011 12:36:37 -0700
parents
children 50def8c971d9
comparison
equal deleted inserted replaced
-1:000000000000 0:7e3a0ae9c016
1 #
2 # Map
3 #
4
5 import sys
6 import string
7 import struct
8 import os
9 import functools
10
11 class MapDefinition:
12 Parse = functools.partial(string.split, sep=',')
13
14 def __init__(self, size, position, direction, fcount, functions, grid):
15 self.Size = self._ParseVector(size)
16 self.Position = self._ParseVector(position)
17 self.Direction = self._ParseVector(direction)
18 self.Count = self._ParseVector(fcount)
19 self.Functions = self._ParseList(functions)
20 self.Grid = self._ParseList(grid)
21
22 def Write(self, filename):
23 with open(filename, 'wb') as handle:
24 handle.write(struct.pack('i' * len(self.Size), *self.Size)) # 8
25 handle.write(struct.pack('i' * len(self.Position), *self.Position)) # 8
26 handle.write(struct.pack('i' * len(self.Direction), *self.Direction)) # 4
27 handle.write(struct.pack('i' * len(self.Count), *self.Count)) # 4
28
29 for function in self.Functions:
30 handle.write(struct.pack('i' * len(function), *function)) # 4 * Count
31
32 for tower in self.Grid:
33 handle.write(struct.pack('i' * len(tower), *tower)) # 8 * Size.X * Size.Y
34
35 def _ParseVector(self, line):
36 return map(int, self.Parse(line))
37
38 def _ParseList(self, lines):
39 return [self._ParseVector(line) for line in lines]
40
41 def ReadDefinition(filename):
42 def FilterLines(lines):
43 for line in map(string.strip, lines):
44 if line and not line.startswith('#'):
45 yield line.split('#')[0]
46
47 with open(filename, 'rt') as handle:
48 lines = handle.readlines()
49
50 definition = tuple(FilterLines(lines))
51
52 offset = 0
53 size = definition[offset]
54 offset += 1
55 position = definition[offset]
56 offset += 1
57 direction = definition[offset]
58 offset += 1
59 fcount = definition[offset]
60 offset += 1
61 length = int(fcount)
62 functions = definition[offset:offset+length]
63 offset += length
64 grid = definition[offset:]
65
66 return MapDefinition(size, position, direction, fcount, functions, grid)
67
68 if __name__ == '__main__':
69 if len(sys.argv) < 2:
70 print 'Usage: Map <map> [output]'
71 sys.exit()
72
73 path_input = os.path.abspath(sys.argv[1])
74 path_output = os.path.splitext(path_input)[0] + '.map'
75
76 if len(sys.argv) > 2:
77 path_output = os.path.abspath(sys.argv[2])
78 if os.path.isdir(path_output):
79 path_output += os.path.splitext(os.path.basename(path_input))[0] + '.map'
80
81 definition = ReadDefinition(path_input)
82 if definition:
83 print 'Building %s from %s' % (os.path.basename(path_output), os.path.basename(path_input))
84 definition.Write(path_output)