parse.py

changeset 94
109fb7cf658f
parent 69
a24c4490d9f2
child 101
745f2c3aec0a
equal deleted inserted replaced
93:ffe05d369412 94:109fb7cf658f
6 6
7 class BadLdrawLine(Exception): 7 class BadLdrawLine(Exception):
8 pass 8 pass
9 9
10 class Model: 10 class Model:
11 def __init__(self, header, body, *, ldraw_directories, header_size = 0): 11 def __init__(
12 self, header, body, *, ldraw_directories, \
13 header_size = 0, line_ending_errors = None
14 ):
12 self.header = header 15 self.header = header
13 self.body = body 16 self.body = body
14 self.header_size = header_size 17 self.header_size = header_size
15 self.ldraw_directories = ldraw_directories 18 self.ldraw_directories = ldraw_directories
19 self.line_ending_errors = line_ending_errors
16 def filter_by_type(self, type): 20 def filter_by_type(self, type):
17 yield from [ 21 yield from [
18 element 22 element
19 for element in self.body 23 for element in self.body
20 if isinstance(element, type) 24 if isinstance(element, type)
60 matrix_4x4 = complete_matrix(element.matrix, element.anchor) 64 matrix_4x4 = complete_matrix(element.matrix, element.anchor)
61 point @= matrix_4x4 65 point @= matrix_4x4
62 yield point @ transformation_matrix 66 yield point @ transformation_matrix
63 67
64 def read_ldraw(file, *, ldraw_directories, name = ''): 68 def read_ldraw(file, *, ldraw_directories, name = ''):
65 model_body = [ 69 line_ending_errors = {
66 parse_ldraw_code(line) 70 'count': 0,
67 for line in file 71 'first-at': None,
68 ] 72 }
73 model_body = []
74 for i, line in enumerate(file.readlines()):
75 # check line endings
76 if not line.endswith(b'\r\n'):
77 if line_ending_errors['first-at'] is None:
78 line_ending_errors['first-at'] = i
79 line_ending_errors['count'] += 1
80 model_body.append(parse_ldraw_code(line))
81 if line_ending_errors['count'] == 0:
82 line_ending_errors = None
69 headerparser = header.HeaderParser() 83 headerparser = header.HeaderParser()
70 try: 84 try:
71 header_parse_result = headerparser.parse(model_body) 85 header_parse_result = headerparser.parse(model_body)
72 header_object = header_parse_result['header'] 86 header_object = header_parse_result['header']
73 end = header_parse_result['end-index'] 87 end = header_parse_result['end-index']
76 end = 0 90 end = 0
77 model = Model( 91 model = Model(
78 header = header_object, 92 header = header_object,
79 body = model_body, 93 body = model_body,
80 header_size = end, 94 header_size = end,
81 ldraw_directories = ldraw_directories) 95 ldraw_directories = ldraw_directories,
96 line_ending_errors = line_ending_errors,
97 )
82 model.name = name 98 model.name = name
83 return model 99 return model
84 100
85 def parse_ldraw_code(line): 101 def parse_ldraw_code(line):
86 try: 102 try:

mercurial