Files
prep-step/scripts/psb/stepread.py
T

97 lines
2.7 KiB
Python
Raw Normal View History

"""Lettore minimo di file STEP (AP203/AP214): solo quanto serve a confrontare un B-rep.
faces(path) -> [dict(surf=tipo, par=[numeri], o=origine, z=asse, x=rif, same=bool,
loops=[[(p_inizio, p_fine, tipo_curva), ...]])]
"""
import re
def parse(path):
txt = open(path, encoding='latin1').read()
txt = txt[txt.index('DATA;') + 5:]
ents = {}
for m in re.finditer(r"#(\d+)\s*=\s*([A-Z_0-9]*)\s*\((.*?)\)\s*;", txt, re.S):
if m[2]:
ents[int(m[1])] = (m[2], args(m[3]))
return ents
def args(s):
"""'a,(b,c),#3' -> lista annidata; #n -> ('#', n); numeri -> float; resto -> str"""
out, stack, tok, instr = [], [], '', False
cur = out
def flush():
nonlocal tok
t = tok.strip()
tok = ''
if not t:
return
if t[0] == '#':
cur.append(('#', int(t[1:])))
else:
try:
cur.append(float(t))
except ValueError:
cur.append(t)
for ch in s:
if instr:
tok += ch
instr = ch != "'"
elif ch == "'":
tok += ch
instr = True
elif ch == '(':
new = []
cur.append(new)
stack.append(cur)
cur = new
elif ch == ')':
flush()
cur = stack.pop()
elif ch == ',':
flush()
else:
tok += ch
flush()
return out
def faces(path):
E = parse(path)
def ref(r):
return E[r[1]]
def pt(r):
return tuple(ref(r)[1][1])
def axis(r):
a = ref(r)[1]
return pt(a[1]), tuple(ref(a[2])[1][1]), tuple(ref(a[3])[1][1])
out = []
for i, (name, a) in E.items():
if name != 'ADVANCED_FACE':
continue
sname, sa = ref(a[2])
f = dict(id=i, surf=sname, same=a[3] == '.T.', loops=[], outer=[], par=[x for x in sa[2:] if isinstance(x, float)])
if sname in ('PLANE', 'CYLINDRICAL_SURFACE', 'CONICAL_SURFACE'):
f['o'], f['z'], f['x'] = axis(sa[1])
for b in a[1]:
bname, ba = ref(b)
loop = []
for oe in ref(ba[1])[1][1]:
oa = ref(oe)[1]
ec = ref(oa[3])[1]
p0, p1 = pt(ref(ec[1])[1][1]), pt(ref(ec[2])[1][1])
if oa[4] != '.T.':
p0, p1 = p1, p0
loop.append((p0, p1, ref(ec[3])[0], oa[3][1]))
f['loops'].append(loop)
f['outer'].append(bname == 'FACE_OUTER_BOUND')
out.append(f)
return out
def shells(path):
E = parse(path)
return {n: [[r[1] for r in a[1]] for nm, a in E.values() if nm == n] for n in ('CLOSED_SHELL', 'OPEN_SHELL')}