Leggi il solido dei .prt ed esportalo in STEP senza Creo

- scripts/psb/brep.py: B-rep esatto da VisibGeom/ActDatums riscritto in
  STEP; coincide faccia per faccia con lo STEP di Creo su due campioni.
- scripts/psb/mesh.py: STEP sfaccettato dalla mesh di SolidPrimdata, per
  i file Wildfire in cui VisibGeom e' cifrata.
- psb.py: tabella dei double corretta (modi a 3/6 byte, prefissi con
  buchi, costanti 04 e 0d, tag ee); tabella dei float a 81 voci, i tag
  ignoti non ricevono piu' un valore inventato; struct dichiarate sotto
  due id.
- tagfit.py, fltfit.py, stepread.py: verifica delle tabelle con vincoli
  geometrici e confronto con lo STEP di Creo.
- docs: nuovo formato-prt-brep.md e lettura-prt-asm.md; correzioni in
  formato-psb.md (3.4) e formato-prt-geometria.md (assi di local_sys =
  colonne); history.md con regressioni e punti aperti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Opus 5.5 committed 2026-11-17 09:00:51 +01:00
1 parent 7754bea9d4
commit 3396df6be0
16 files changed
+1584 -15

No files matched your search

+481
View File
@@ -0,0 +1,481 @@
"""B-rep di un .prt Creo: superfici, contorni e spigoli letti dal file, senza Creo, ed esportati
in STEP per poterli vedere in qualsiasi visualizzatore. Reverse engineering: formato e prove in
docs/formato-prt-brep.md.
python scripts/psb/brep.py <file.prt.N> riepilogo + controllo di coerenza
python scripts/psb/brep.py <file.prt.N> --step out.stp esporta il B-rep in STEP
python scripts/psb/brep.py <file.prt.N> --check ref.stp confronta, faccia per faccia, con lo STEP di Creo
"""
import math, os, sys, tempfile
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import prt, psb
PLANE, CYL, CONE, TORUS, SPL = 34, 36, 37, 38, 40 # geom_type (44 = tab_cyl, non gestito)
QUILT = 57 # topol_ref_data.list_type: 57 = quilt, 98 = solido
TOL = 1e-4 # mm
# --- lettura ---------------------------------------------------------------
def section(d, secs, name):
o, l, f = secs[name]
if f[2] != '9':
raise SystemExit(f"{name} e' di tipo {f[2]} (file Wildfire o sezione cifrata): non leggibile")
p, root, e = psb.parse(d[o:o + l])
if e is not None:
raise SystemExit(f"{name} non letta fino in fondo: {e!r}")
return root[1]
def walk(v):
if isinstance(v, psb.Node):
for n, x in v:
yield n, x
yield from walk(x)
elif isinstance(v, psb.Arr):
for x in v:
yield from walk(x)
def load(path):
"""(superfici, spigoli) della geometria visibile. Gli spigoli stanno tutti in VisibGeom; le
superfici quasi: quelle a cui e' agganciato un asse di riferimento stanno in ActDatums, con lo
stesso formato e nella stessa catena next_geom_ptr. Si tengono solo quelle con un contorno."""
d, secs, _ = prt.load(path)
g = section(d, secs, 'VisibGeom').get('active_geom')
srf = list(g.get('srf_array') or [])
if 'ActDatums' in secs:
for n, v in walk(section(d, secs, 'ActDatums')):
if n == 'srf_array' and v:
srf += v
return [s for s in srf if contours(s)], g.get('crv_array') or []
def prim(s):
for n, v in s:
if n.startswith('srf_prim_ptr'):
return v
def contours(s):
"""[(primo spigolo, trv, inviluppo UV)]: frst_cntr_ptr e i next_cntr_ptr non nulli (nel file
sono una lista concatenata; il parser li rende come campi allo stesso livello)"""
return [(v.get('frst_cntr_crv_hdr_ptr'), v.get('trv'), v.get('envlp'))
for n, v in s if n in ('frst_cntr_ptr', 'next_cntr_ptr') and v is not None]
# --- geometria -------------------------------------------------------------
def sub(a, b):
return tuple(x - y for x, y in zip(a, b))
def add(a, b, k=1.0):
return tuple(x + k * y for x, y in zip(a, b))
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def norm(a):
return math.sqrt(dot(a, a))
def unit(a):
n = norm(a)
return tuple(x / n for x in a)
def frame(p):
"""local_sys -> (asse x, asse y, asse z, origine). Nel file ci sono le RIGHE di R in
mondo = origine + R * locale: gli assi locali sono le colonne."""
*R, o = p.get('local_sys')
return tuple(tuple(R[i][j] for i in range(3)) for j in range(3)) + (tuple(o),)
def xyz(s, u, v):
"""punto 3D della superficie s ai parametri (u, v)"""
p = prim(s)
t = s.get('geom_type')
if t == SPL:
return bicubic(p, u, v)
if t == PLANE:
a, b, c = u, v, 0.0
elif t == CYL:
r = p.get('radius')
a, b, c = r * math.cos(u), r * math.sin(u), v
elif t == CONE: # vertice nell'origine, v = quota lungo l'asse
r = v * math.tan(p.get('half_angle'))
a, b, c = r * math.cos(u), r * math.sin(u), v
elif t == TORUS: # u attorno all'asse, v attorno al tubo
r = p.get('radius1') + p.get('radius2') * math.cos(v)
a, b, c = r * math.cos(u), r * math.sin(u), p.get('radius2') * math.sin(v)
else:
raise ValueError(f"geom_type {t} non gestito")
ex, ey, ez, o = frame(p)
return tuple(o[i] + a * ex[i] + b * ey[i] + c * ez[i] for i in range(3))
def hermite(t):
return (2 * t**3 - 3 * t**2 + 1, -2 * t**3 + 3 * t**2, t**3 - 2 * t**2 + t, t**3 - t**2)
def one_patch(p):
if list(p.get('u_params')) != [0.0, 1.0] or list(p.get('v_params')) != [0.0, 1.0]:
raise ValueError("splsrf con piu' di una maglia: non gestita")
return tuple(p.get(k) for k in ('i_points', 'end_u_tangts', 'end_v_tangts', 'end_uv_deriv'))
def bicubic(p, u, v):
"""pezza di Hermite bicubica su una sola maglia; l'angolo (a, b) sta all'indice 2a + b"""
P, Tu, Tv, Tuv = one_patch(p)
hu, hv = hermite(u), hermite(v)
out = []
for i in range(3):
acc = 0.0
for a in range(2):
for b in range(2):
k = 2 * a + b
acc += (hu[a] * hv[b] * P[k][i] + hu[a + 2] * hv[b] * Tu[k][i]
+ hu[a] * hv[b + 2] * Tv[k][i] + hu[a + 2] * hv[b + 2] * Tuv[k][i])
out.append(acc)
return tuple(out)
def bezier_net(p):
"""la stessa pezza come 4x4 punti di controllo di Bezier (per lo STEP)"""
P, Tu, Tv, Tuv = one_patch(p)
net = [[None] * 4 for _ in range(4)]
for a in range(2):
for b in range(2):
k, su, sv = 2 * a + b, 1 - 2 * a, 1 - 2 * b
for i, ku in ((3 * a, 0), (3 * a + su, su / 3)):
for j, kv in ((3 * b, 0), (3 * b + sv, sv / 3)):
net[i][j] = add(add(add(P[k], Tu[k], ku), Tv[k], kv), Tuv[k], ku * kv)
return net
# --- topologia -------------------------------------------------------------
def loop(S_id, first, C):
"""spigoli di un contorno: [(id, lato)]. Ogni spigolo ha due lati (le due superfici che separa);
si segue next_crv_hdr_ptr del lato che guarda la superficie S_id fino a tornare al primo."""
out, e = [], first
while True:
c = C[e]
k = 0 if c.get('crv_hdr_geom_ptr[0]') == S_id else 1
if c.get(f'crv_hdr_geom_ptr[{k}]') != S_id:
raise ValueError(f"spigolo {e} non tocca la superficie {S_id}")
out.append((e, k))
e = c.get(f'next_crv_hdr_ptr[{k}]')
if e == first:
return out
if len(out) > len(C):
raise ValueError(f"contorno di {S_id} non chiuso")
def faces(srf, C):
"""[(superficie, [contorno esterno, fori...])]: una faccia per contorno esterno (trv = 1),
perche' una superficie Creo puo' avere piu' regioni staccate. Un foro (trv = -1) va al
contorno esterno piu' piccolo il cui inviluppo UV lo contiene."""
out = []
for s in srf:
groups = [(c, [c]) for c in contours(s) if c[1] == 1]
for h in (c for c in contours(s) if c[1] != 1):
(a0, b0), (a1, b1) = h[2]
inside = [g for g in groups if g[0][2][0][0] - TOL <= a0 and g[0][2][0][1] - TOL <= b0
and g[0][2][1][0] + TOL >= a1 and g[0][2][1][1] + TOL >= b1]
if not inside:
raise ValueError(f"superficie {s.get('geom_id')}: foro senza contorno esterno")
min(inside, key=lambda g: (g[0][2][1][0] - g[0][2][0][0]) * (g[0][2][1][1] - g[0][2][0][1]))[1].append(h)
out += [(s, [loop(s.get('geom_id'), c[0], C) for c in cl]) for _, cl in groups]
return out
def side_points(c, S, k):
s = S.get(c.get(f'crv_hdr_geom_ptr[{k}]'))
return [xyz(s, q[2 * k], q[2 * k + 1]) for q in c.get('crv_pnt_arr')] if s else None
def edge3d(c, S, n=8):
"""polilinea 3D fitta dello spigolo. Il file ha solo campioni (u, v) sulle due superfici: si
interpolano in UV (Catmull-Rom) sulla superficie curva, dove cerchi e generatrici sono rette."""
# ponytail: fra due superfici curve qualsiasi e' un'approssimazione fra i campioni; se serve
# la curva esatta va calcolata l'intersezione delle due superfici
sides = [(k, S[c.get(f'crv_hdr_geom_ptr[{k}]')]) for k in (0, 1) if c.get(f'crv_hdr_geom_ptr[{k}]') in S]
k, s = min(sides, key=lambda t: {CYL: 0, CONE: 0, TORUS: 0, PLANE: 1}.get(t[1].get('geom_type'), 2))
uv = [(q[2 * k], q[2 * k + 1]) for q in c.get('crv_pnt_arr')]
m = [sub(uv[min(i + 1, len(uv) - 1)], uv[max(i - 1, 0)]) for i in range(len(uv))]
m = [tuple(v / 2 for v in x) if 0 < i < len(uv) - 1 else x for i, x in enumerate(m)]
out = []
for i in range(len(uv) - 1):
for j in range(n):
h = hermite(j / n)
out.append(tuple(h[0] * uv[i][d] + h[1] * uv[i + 1][d] + h[2] * m[i][d] + h[3] * m[i + 1][d] for d in range(2)))
out.append(uv[-1])
return [xyz(s, u, v) for u, v in out]
def classify(P):
"""('line',) | ('circle', centro, asse, raggio) | None, dai punti della polilinea"""
a, b = P[0], P[-1]
closed = math.dist(a, b) < TOL
if not closed:
d = unit(sub(b, a))
if all(norm(cross(sub(p, a), d)) < TOL for p in P):
return ('line',)
if len(P) < 3:
return None
m, e = (P[len(P) // 3], P[2 * len(P) // 3]) if closed else (P[len(P) // 2], b)
ab, ac = sub(m, a), sub(e, a)
n = cross(ab, ac)
if norm(n) < 1e-9:
return None
c = add(a, add(tuple(x * dot(ac, ac) for x in cross(n, ab)), cross(ac, n), dot(ab, ab)), 1 / (2 * dot(n, n)))
r, n = math.dist(a, c), unit(n)
if all(abs(math.dist(p, c) - r) < TOL and abs(dot(sub(p, c), n)) < TOL for p in P):
return ('circle', c, n, r) # n orientato cosi' che a -> m -> e sia antiorario
return None
# --- STEP ------------------------------------------------------------------
def num(x):
x = float(f"{x:.12g}") + 0.0
if not math.isfinite(x):
raise ValueError("numero non decodificato nel B-rep")
s = repr(x)
if 'e' in s:
m, e = s.split('e')
s = (m if '.' in m else m + '.') + 'E' + e
return s
class Step:
def __init__(s):
s.out = []
def add(s, text):
s.out.append(text)
return f"#{len(s.out)}"
def pt(s, p):
return s.add(f"CARTESIAN_POINT('',({','.join(num(x) for x in p)}))")
def dir(s, d):
return s.add(f"DIRECTION('',({','.join(num(x) for x in d)}))")
def ax(s, o, z, x):
return s.add(f"AXIS2_PLACEMENT_3D('',{s.pt(o)},{s.dir(z)},{s.dir(x)})")
def step_surface(st, s):
"""scrive la superficie; ritorna (riferimento, same_sense)"""
t, p = s.get('geom_type'), prim(s)
(u0, v0), (u1, v1) = s.get('envlp')
u, v = (u0 + u1) / 2, (v0 + v1) / 2
if t not in (PLANE, CYL, CONE, TORUS, SPL):
raise ValueError(f"geom_type {t} non gestito")
if t == SPL:
net = bezier_net(p)
rows = ','.join('(' + ','.join(st.pt(q) for q in row) + ')' for row in net)
ref = st.add(f"B_SPLINE_SURFACE_WITH_KNOTS('',3,3,({rows}),.UNSPECIFIED.,.F.,.F.,.F.,(4,4),(4,4),(0.,1.),(0.,1.),.UNSPECIFIED.)")
return ref, s.get('orient') == 1
ex, ey, ez, o = frame(p)
P, h = xyz(s, u, v), 1e-4
n = cross(sub(xyz(s, u + h, v), P), sub(xyz(s, u, v + h), P)) # normale naturale di Creo
radial = sub(sub(P, o), tuple(x * dot(sub(P, o), ez) for x in ez))
if t == PLANE:
ref, nstep = st.add(f"PLANE('',{st.ax(o, ez, ex)})"), ez
elif t == CYL:
ref, nstep = st.add(f"CYLINDRICAL_SURFACE('',{st.ax(o, ez, ex)},{num(p.get('radius'))})"), radial
elif t == TORUS:
ref = st.add(f"TOROIDAL_SURFACE('',{st.ax(o, ez, ex)},{num(p.get('radius1'))},{num(p.get('radius2'))})")
c = add(o, unit(radial), p.get('radius1')) # centro del tubo sotto il punto P
nstep = sub(P, c)
elif t == CONE:
# STEP vuole un raggio > 0 nel punto di piazzamento: lo si mette a meta' della falda usata
if abs(v) < 1e-9:
raise ValueError(f"cono {s.get('geom_id')}: falda a cavallo del vertice")
z = ez if v > 0 else tuple(-x for x in ez)
ang = p.get('half_angle')
# half_angle puo' essere negativo (raggio v*tan < 0 = stessa falda vista da u + pi): STEP
# vuole raggio e angolo positivi, la superficie e' la stessa
ref = st.add(f"CONICAL_SURFACE('',{st.ax(add(o, ez, v), z, ex)},{num(abs(v * math.tan(ang)))},{num(abs(ang))})")
nstep = radial
# orient = 1: il materiale sta dietro la normale naturale. same_sense dice lo stesso della
# normale STEP: i due versi si confrontano in un punto della faccia
return ref, (s.get('orient') == 1) == (dot(n, nstep) > 0)
def new_step(name):
"""Step con l'intestazione di prodotto gia' scritta (#1-#13; #8 = forma, #13 = contesto)"""
st = Step()
for h in [
"APPLICATION_CONTEXT('automotive design')",
"APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#1)",
"PRODUCT_CONTEXT('',#1,'mechanical')",
f"PRODUCT('{name}','{name}','',(#3))",
"PRODUCT_DEFINITION_FORMATION('','',#4)",
"PRODUCT_DEFINITION_CONTEXT('part definition',#1,'design')",
"PRODUCT_DEFINITION('design','',#5,#6)",
"PRODUCT_DEFINITION_SHAPE('','',#7)",
"(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))",
"(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))",
"(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())",
"UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-3),#9,'distance_accuracy_value','')",
"(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#12))"
"GLOBAL_UNIT_ASSIGNED_CONTEXT((#9,#10,#11))REPRESENTATION_CONTEXT('',''))",
]:
st.add(h)
return st
def save_step(path, st, name, items, note):
rep = st.add(f"SHAPE_REPRESENTATION('',({','.join(items)}),#13)")
st.add(f"SHAPE_DEFINITION_REPRESENTATION(#8,{rep})")
with open(path, 'w', encoding='ascii') as f:
f.write(f"ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION(('{note}'),'2;1');\n"
f"FILE_NAME('{name}','',(''),(''),'PrepStep scripts/psb','','');\n"
"FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));\nENDSEC;\nDATA;\n")
f.writelines(f"#{i}={t};\n" for i, t in enumerate(st.out, 1))
f.write("ENDSEC;\nEND-ISO-10303-21;\n")
def write_step(path, srf, crv, name):
S = {s.get('geom_id'): s for s in srf}
C = {c.get('crv_id'): c for c in crv}
st = new_step(name)
verts = [] # [(punto, riferimento)]
def vertex(p):
for q, r in verts:
if math.dist(p, q) < TOL:
return q, r
verts.append((p, st.add(f"VERTEX_POINT('',{st.pt(p)})")))
return verts[-1]
edges, surfs, solid, quilts = {}, {}, [], {} # quilts: id della quilt -> facce
def edge(eid):
if eid not in edges:
P = edge3d(C[eid], S)
(P[0], a), (P[-1], b) = vertex(P[0]), vertex(P[-1])
# se la polilinea fitta non e' una retta o un cerchio, lo si chiede ai soli campioni del
# file, che stanno esattamente sulla curva (serve sui bordi liberi: un lato solo, piano)
k = classify(P) or (len(P) > 4 * 8 and classify(P[::8]))
if k and k[0] == 'line':
d = sub(P[-1], P[0])
cv = st.add(f"LINE('',{st.pt(P[0])},{st.add(f'VECTOR({chr(39)}{chr(39)},{st.dir(unit(d))},{num(norm(d))})')})")
elif k:
_, c, n, r = k
cv = st.add(f"CIRCLE('',{st.ax(c, n, unit(sub(P[0], c)))},{num(r)})")
else:
# ponytail: polilinea (B-spline di grado 1), basta per vedere; grado 3 se serve liscia
pts = ','.join(st.pt(p) for p in P)
mult = ','.join(['2'] + ['1'] * (len(P) - 2) + ['2'])
knots = ','.join(num(i) for i in range(len(P)))
cv = st.add(f"B_SPLINE_CURVE_WITH_KNOTS('',1,({pts}),.UNSPECIFIED.,.F.,.F.,({mult}),({knots}),.UNSPECIFIED.)")
edges[eid] = st.add(f"EDGE_CURVE('',{a},{b},{cv},.T.)")
return edges[eid]
for s, loops in faces(srf, C):
gid = s.get('geom_id')
if gid not in surfs:
surfs[gid] = step_surface(st, s)
bounds = []
for i, lp in enumerate(loops):
oes = ','.join(st.add(f"ORIENTED_EDGE('',*,*,{edge(e)},{'.T.' if C[e].get('crv_pnt_dir')[k] == 1 else '.F.'})")
for e, k in lp)
el = st.add(f"EDGE_LOOP('',({oes}))")
bounds.append(st.add(f"{'FACE_BOUND' if i else 'FACE_OUTER_BOUND'}('',{el},.T.)"))
ref, same = surfs[gid]
f = st.add(f"ADVANCED_FACE('',({','.join(bounds)}),{ref},{'.T.' if same else '.F.'})")
ref = s.get('topol_ref_data')
(quilts.setdefault(ref.get('list_id'), []) if ref.get('list_type') == QUILT else solid).append(f)
items = []
if solid:
closed = st.add(f"CLOSED_SHELL('',({','.join(solid)}))")
items.append(st.add(f"MANIFOLD_SOLID_BREP('{name}',{closed})"))
if quilts: # un guscio aperto per quilt, come fa Creo
opened = ','.join(st.add(f"OPEN_SHELL('',({','.join(fs)}))") for fs in quilts.values())
items.append(st.add(f"SHELL_BASED_SURFACE_MODEL('',({opened}))"))
save_step(path, st, name, items, 'B-rep letto dal .prt senza Creo')
return len(solid), sum(len(fs) for fs in quilts.values())
# --- controlli -------------------------------------------------------------
def coherence(srf, crv):
"""il vincolo che regge tutto: lo stesso campione, calcolato sulle due superfici che lo
spigolo separa, deve dare lo stesso punto. Ritorna (scarto massimo, spigoli fuori tolleranza)."""
S = {s.get('geom_id'): s for s in srf}
worst, bad = 0.0, []
for c in crv:
a, b = side_points(c, S, 0), side_points(c, S, 1)
if a is None or b is None:
continue # bordo libero di una quilt: un lato solo
d = max(math.dist(x, y) for x, y in zip(a, b))
if not d < TOL:
bad.append((c.get('crv_id'), d))
elif d > worst:
worst = d
return worst, bad
def compare(mine, ref):
"""confronto fra due STEP: facce abbinate per contorni (estremi degli spigoli, con verso)"""
import stepread
import collections
def R(p):
return tuple(round(x, 3) + 0.0 for x in p)
def key(f):
return frozenset(frozenset((R(a), R(b)) for a, b, *_ in lp) for lp in f['loops'])
A, B = stepread.faces(mine), stepread.faces(ref)
idx = {key(f): f for f in B}
res = collections.Counter()
curves = collections.Counter()
for f in A:
g = idx.get(key(f))
if g is None:
res['facce senza corrispondente'] += 1
continue
res['facce abbinate (stessi contorni, stesso verso)'] += 1
res[' stesso tipo di superficie'] += f['surf'] == g['surf']
res[' stesso verso (same_sense)'] += f['same'] == g['same']
res[' stesso raggio (cilindri)'] += f['surf'] == 'CYLINDRICAL_SURFACE' and abs(f['par'][0] - g['par'][0]) < TOL
res[' stessa suddivisione esterno/fori'] += f['outer'] == g['outer'] or sorted(f['outer']) == sorted(g['outer'])
ct = {(R(a), R(b)): t for lp in g['loops'] for a, b, t, _ in lp}
for lp in f['loops']:
for a, b, t, _ in lp:
curves[(t.split('_')[0], ct.get((R(a), R(b)), '?').split('_')[0])] += 1
print(f"facce: prt {len(A)} step di riferimento {len(B)}")
for k, v in res.items():
print(f"{k}: {v}")
sa, sb = stepread.shells(mine), stepread.shells(ref)
print("gusci chiusi/aperti (numero di facce):", {k: [len(x) for x in v] for k, v in sa.items()},
"riferimento", {k: [len(x) for x in v] for k, v in sb.items()})
print("curve degli spigoli (mia -> riferimento), contate per lato:")
for (a, b), v in sorted(curves.items()):
print(f" {a:8} -> {b:8} {v}")
if __name__ == '__main__':
src = sys.argv[1]
srf, crv = load(src)
C = {c.get('crv_id'): c for c in crv}
F = faces(srf, C)
worst, bad = coherence(srf, crv)
print(f"superfici {len(srf)} facce {len(F)} contorni {sum(len(l) for _, l in F)} spigoli {len(crv)}")
print(f"coerenza fra le due superfici di ogni spigolo: scarto massimo {worst:.1e} mm, fuori tolleranza {len(bad)}")
for e, d in bad[:20]:
print(f" spigolo {e}: scarto {d:.6f}")
name = os.path.basename(src).split('.')[0]
if '--step' in sys.argv:
out = sys.argv[sys.argv.index('--step') + 1]
print(f"scritto {out}: facce del solido {'/ della quilt '.join(str(n) + ' ' for n in write_step(out, srf, crv, name))}")
if '--check' in sys.argv:
tmp = os.path.join(tempfile.mkdtemp(), 'mio.stp')
write_step(tmp, srf, crv, name)
compare(tmp, sys.argv[sys.argv.index('--check') + 1])
+193
View File
@@ -0,0 +1,193 @@
"""Ricostruisce la tabella dei prefissi dei float (psb.P.FPFX, tag 50-df) dalla mesh di
SolidPrimdata, con due vincoli: ogni normale e' unitaria, ogni vertice sta su una superficie
dello STEP esportato da Creo dallo stesso modello (o, senza STEP, sul piano della sua striscia).
python scripts/psb/fltfit.py <file.prt.N> <file.stp> [altre coppie ...]
Al posto dello STEP si puo' mettere '-': di quel file si usano solo le normali.
Stampa per ogni tag il prefisso scelto, quante volte e' stato messo alla prova e quante
alternative lo spiegano altrettanto bene (0 = provato).
"""
import math, os, struct, sys, collections
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import psb, mesh, stepread
TOL = 3e-4 # mm: i vertici sono float a 32 bit
class TF(float):
pass
_rflt = psb.P.rflt
def rflt(s):
p = s.p
v = _rflt(s)
t = s.b[p]
if 0x50 <= t <= 0xdf:
o = TF(0.0 if isinstance(v, psb.Unk) else v)
o.tag, o.pl = t, bytes(s.b[p + 1:p + 3])
return o
return v
psb.P.rflt = rflt
def val(x, pfx):
"""valore del float x con la tabella pfx; None se il suo tag non ha ancora un prefisso"""
if not isinstance(x, TF):
return float(x)
hi = pfx.get(x.tag)
return None if hi is None else struct.unpack('>f', hi.to_bytes(2, 'big') + x.pl)[0]
def surfaces(path):
out = []
for f in stepread.faces(path):
if f['surf'] == 'PLANE':
out.append(('p', f['o'], f['z']))
elif f['surf'] == 'CYLINDRICAL_SURFACE':
out.append(('c', f['o'], f['z'], f['par'][0]))
elif f['surf'] == 'CONICAL_SURFACE':
a = f['par'][1]
out.append(('k', f['o'], f['z'], f['par'][0], math.tan(math.radians(a) if a > 1.6 else a)))
return list(set(out))
def wire(path):
"""(vertici, cerchi) dello STEP: i vertici della mesh stanno quasi tutti sul bordo delle facce,
cioe' su un vertice o su uno spigolo circolare. E' un vincolo molto piu' stretto di "sta su
una superficie", che per una faccia piana lascia libera la coordinata ignota."""
E = stepread.parse(path)
def pt(r):
return tuple(E[r[1]][1][1])
verts = [pt(a[1]) for n, a in E.values() if n == 'VERTEX_POINT']
circles = []
for n, a in E.values():
if n == 'CIRCLE':
ax = E[a[1][1]][1]
circles.append((pt(ax[1]), tuple(E[ax[2][1]][1][1]), a[2]))
return verts, circles
def on_wire(p, W, tol):
verts, circles = W
for q in verts:
if abs(p[0] - q[0]) < tol and abs(p[1] - q[1]) < tol and abs(p[2] - q[2]) < tol:
return True
for c, z, r in circles:
d = (p[0] - c[0], p[1] - c[1], p[2] - c[2])
h = d[0] * z[0] + d[1] * z[1] + d[2] * z[2]
if abs(h) < tol and abs(math.sqrt(max(0.0, d[0] * d[0] + d[1] * d[1] + d[2] * d[2] - h * h)) - r) < tol:
return True
return False
def on_surface(p, S, tol):
for s in S:
d = (p[0] - s[1][0], p[1] - s[1][1], p[2] - s[1][2])
h = d[0] * s[2][0] + d[1] * s[2][1] + d[2] * s[2][2]
if s[0] == 'p':
if abs(h) < tol:
return True
continue
r = math.sqrt(max(0.0, d[0] * d[0] + d[1] * d[1] + d[2] * d[2] - h * h))
if s[0] == 'c' and abs(r - s[3]) < tol:
return True
if s[0] == 'k' and (abs(r - (s[3] + h * s[4])) < tol or abs(r - (s[3] - h * s[4])) < tol):
return True
return False
def candidates(t, pfx):
"""50-a3 positivi, a4-df negativi. Tutte le voci trovate finora crescono in modulo con il tag:
un tag ignoto si cerca fra i vicini noti (e' cio' che decide i casi con due soluzioni)"""
neg = t >= 0xa4
lo, hi = (0xb000, 0xc500) if neg else (0x3000, 0x4500)
for k, v in pfx.items():
if (k >= 0xa4) == neg:
if k < t:
lo = max(lo, v + 1)
elif k > t:
hi = min(hi, v - 1)
return range(lo, hi + 1)
def main(args):
V, N = [], [] # vertici e normali: liste di 3 float (alcuni TF), con le superfici
for prt_path, stp in zip(args[::2], args[1::2]):
S = (surfaces(stp), wire(stp)) if stp != '-' else None
try:
G = mesh.groups(mesh.load(prt_path))
except SystemExit:
continue
for lod, strips in G:
for s in strips:
for n, p in s:
N.append(n)
if S: # senza STEP ('-') contano solo le normali
V.append((p, S))
pfx = dict(psb.P.FKNOWN)
use = collections.defaultdict(list)
for i, n in enumerate(N):
for x in n:
if isinstance(x, TF):
use[x.tag].append(('n', i))
for i, (p, S) in enumerate(V):
for x in p:
if isinstance(x, TF):
use[x.tag].append(('v', i))
report, debug = {}, {}
for rnd in range(6):
changed = False
for t in sorted(use):
if t in pfx and t in report:
continue
score = collections.Counter()
tests = 0
cands = [pfx[t]] if t in pfx else candidates(t, pfx)
trial = dict(pfx)
for kind, i in use[t]:
item = N[i] if kind == 'n' else V[i][0]
if any(isinstance(x, TF) and x.tag != t and x.tag not in pfx for x in item):
continue # dipende da un altro tag ancora ignoto: piu' tardi
tests += 1
for c in cands:
trial[t] = c
q = [val(x, trial) for x in item]
if kind == 'n':
ok = abs(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] - 1) < 2e-5
else:
ok = on_surface(q, V[i][1][0], TOL) and (2 if on_wire(q, V[i][1][1], TOL) else 1)
score[c] += ok
if not tests:
continue
best, n = score.most_common(1)[0] if score else (None, 0)
ties = sum(1 for c, v in score.items() if v == n) - 1
debug[t] = f"prove {tests}, migliori {[(hex(c), v) for c, v in score.most_common(4)]}"
if t in pfx:
report[t] = (pfx[t], tests, score[pfx[t]], 0, 'gia nota')
elif n >= 1 and ties == 0 and n >= 0.9 * tests:
pfx[t] = best
report[t] = (best, tests, n, ties, 'trovata')
changed = True
if not changed:
break
for t in sorted(use):
if t in report:
hi, tests, n, ties, how = report[t]
print(f"tag {t:02x} -> {hi:04x} prove {tests:4} riuscite {n:4} {how}")
else:
print(f"tag {t:02x} -> ? usato {len(use[t])} volte, non determinato", debug.get(t, ''))
print("FKNOWN = {" + ', '.join(f"0x{t:02x}: 0x{v:04x}" for t, v in sorted(pfx.items())) + "}")
if __name__ == '__main__':
main(sys.argv[1:])
+133
View File
@@ -0,0 +1,133 @@
"""Mesh di visualizzazione di un .prt Creo, letta da SolidPrimdata (sezione compressa, mai cifrata:
c'e' anche nei file Wildfire in cui il B-rep e' illeggibile). Reverse engineering, vedi
docs/formato-prt-brep.md.
python scripts/psb/mesh.py <file.prt.N> riepilogo
python scripts/psb/mesh.py <file.prt.N> --step out.stp STEP sfaccettato (triangoli piani)
python scripts/psb/mesh.py <file.prt.N> --stl out.stl gli stessi triangoli in STL
"""
import os, struct, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import prt, psb, unz
def walk(v, name=''):
if isinstance(v, psb.Node):
for n, x in v:
yield n, x
yield from walk(x, n)
elif isinstance(v, psb.Arr):
for x in v:
yield from walk(x, name)
def load(path):
"""radice di SolidPrimdata decompressa e letta"""
d, secs, _ = prt.load(path)
if 'SolidPrimdata' not in secs:
raise SystemExit("SolidPrimdata assente")
o, l, _ = secs['SolidPrimdata']
p, root, e = psb.parse(unz.unz(d[o:o + l]))
if e is not None:
raise SystemExit(f"SolidPrimdata non letta fino in fondo: {e!r}")
return root[1]
def groups(root):
"""[(lod_value, [strisce])]: ogni striscia e' una lista di (normale, punto)"""
out = []
for g in root.get('pgl_primdata_groups_arr') or []:
g = g.get('pgl_primdata_group') if isinstance(g, psb.Node) and g.get('pgl_primdata_group') is not None else g
strips = []
for n, v in walk(g):
if n.startswith('value(prim_tristripset') and v is not None:
a, ends = v.get('mv_p_NxNyNzxyz'), v.get('p_accum_set_size')
if not a or not ends:
continue
vs = [(tuple(a[i:i + 3]), tuple(a[i + 3:i + 6])) for i in range(0, len(a), 6)]
start = 0
for e in ends:
strips.append(vs[start:e])
start = e
out.append((g.get('lod_value'), strips))
return out
def triangles(strips):
for s in strips:
for i in range(len(s) - 2):
a, b, c = (s[i], s[i + 1], s[i + 2]) if i % 2 == 0 else (s[i + 1], s[i], s[i + 2])
if a[1] != b[1] and b[1] != c[1] and a[1] != c[1]:
yield a, b, c
def write_stl(path, tris):
tris = list(tris)
with open(path, 'wb') as f:
f.write(b'PrepStep mesh.py'.ljust(80, b' ') + struct.pack('<I', len(tris)))
for a, b, c in tris:
f.write(struct.pack('<12fH', *a[0], *a[1], *b[1], *c[1], 0))
return len(tris)
def write_step(path, tris, name):
"""STEP sfaccettato: ogni triangolo e' una faccia piana, vertici e spigoli condivisi. Non e' il
B-rep (un cilindro resta fatto di triangoli): e' il meglio che si ricava dai file in cui
VisibGeom e' cifrata. Ritorna (triangoli, spigoli usati da una sola faccia)."""
import brep
st = brep.new_step(name)
verts, edges, faces, uses = {}, {}, [], {}
def vertex(p):
k = tuple(round(x, 5) + 0.0 for x in p)
if k not in verts:
verts[k] = (k, st.add(f"VERTEX_POINT('',{st.pt(k)})"))
return verts[k]
def edge(a, b):
k = (a[0], b[0]) if a[0] <= b[0] else (b[0], a[0])
if k not in edges:
d = brep.sub(k[1], k[0])
vec = st.add(f"VECTOR('',{st.dir(brep.unit(d))},{brep.num(brep.norm(d))})")
edges[k] = st.add(f"EDGE_CURVE('',{verts[k[0]][1]},{verts[k[1]][1]},{st.add(f'LINE({chr(39)}{chr(39)},{st.pt(k[0])},{vec})')},.T.)")
uses[k] = uses.get(k, 0) + 1
return st.add(f"ORIENTED_EDGE('',*,*,{edges[k]},{'.T.' if k[0] == a[0] else '.F.'})")
for a, b, c in tris:
A, B, C = vertex(a[1]), vertex(b[1]), vertex(c[1])
if len({A[0], B[0], C[0]}) < 3:
continue
n = brep.cross(brep.sub(B[0], A[0]), brep.sub(C[0], A[0]))
if brep.norm(n) < 1e-12:
continue
if brep.dot(n, a[0]) < 0: # il verso lo decide la normale del vertice
B, C, n = C, B, tuple(-x for x in n)
loop = st.add(f"EDGE_LOOP('',({edge(A, B)},{edge(B, C)},{edge(C, A)}))")
plane = st.add(f"PLANE('',{st.ax(A[0], brep.unit(n), brep.unit(brep.sub(B[0], A[0])))})")
outer = st.add(f"FACE_OUTER_BOUND('',{loop},.T.)")
faces.append(st.add(f"ADVANCED_FACE('',({outer}),{plane},.T.)"))
free = sum(1 for v in uses.values() if v != 2)
# chiuso (ogni spigolo fra due triangoli) -> solido; altrimenti solo una pelle
if free == 0:
items = [st.add(f"MANIFOLD_SOLID_BREP('{name}',{st.add('CLOSED_SHELL(' + chr(39) * 2 + ',(' + ','.join(faces) + '))')})")]
else:
items = [st.add(f"SHELL_BASED_SURFACE_MODEL('',({st.add('OPEN_SHELL(' + chr(39) * 2 + ',(' + ','.join(faces) + '))')}))")]
brep.save_step(path, st, name, items, 'mesh di visualizzazione letta dal .prt senza Creo (sfaccettata)')
return len(faces), free
if __name__ == '__main__':
G = groups(load(sys.argv[1]))
for lod, strips in G:
print(f"livello di dettaglio {lod}: strisce {len(strips)} vertici {sum(len(s) for s in strips)} triangoli {sum(1 for _ in triangles(strips))}")
if not any(strips for lod, strips in G):
raise SystemExit("SolidPrimdata non contiene una mesh (succede nei file recenti: usare brep.py)")
if any(isinstance(x, psb.Unk) for lod, strips in G for s in strips for n, p in s for x in n + p):
raise SystemExit("la mesh usa tag float non ancora in tabella (psb.P.FKNOWN): non esportata")
if '--step' in sys.argv:
best = max(G, key=lambda g: len(g[1]))
n, free = write_step(sys.argv[sys.argv.index('--step') + 1], triangles(best[1]), os.path.basename(sys.argv[1]).split('.')[0])
print(f"scritto STEP sfaccettato: {n} triangoli, {'solido chiuso' if not free else str(free) + ' spigoli liberi: pelle aperta'}")
if '--stl' in sys.argv:
best = max(G, key=lambda g: len(g[1])) # il livello con piu' triangoli
print("scritti", write_stl(sys.argv[sys.argv.index('--stl') + 1], triangles(best[1])), "triangoli")
+49 -11
View File
@@ -91,9 +91,27 @@ class P:
return -1
raise Err(f"int tag {b:02x} @{s.p - 1:x}")
CONST = {0x17: -6.283185307179586, 0x14: 4.71238898038469, 0x0d: -0.5, 0x11: 3.141592653589793, 0x15: -3.141592653589793, 0x12: 1.5707963267948966, 0x16: -1.5707963267948966, 0x13: 6.283185307179586, 0x18: 0.0, 0x0f: 1.0, 0x0e: 0.5, 0x10: -1.0, 0x0c: 0.1, 0x0a: 0.01, 0x07: 0.001}
CONST = {0x04: 1.0, 0x0d: 0.25, 0x17: -6.283185307179586, 0x14: 4.71238898038469, 0x11: 3.141592653589793, 0x15: -3.141592653589793, 0x12: 1.5707963267948966, 0x16: -1.5707963267948966, 0x13: 6.283185307179586, 0x18: 0.0, 0x0f: 1.0, 0x0e: 0.5, 0x10: -1.0, 0x0c: 0.1, 0x0a: 0.01, 0x07: 0.001}
FBASE = 0x3f9d
# tag 50-df dei float -> primi due byte (seguono 2 byte). Tabella sparsa, crescente in modulo
# (50-a3 positivi, a4-df negativi), ricostruita da fltfit.py; un tag assente e' ignoto
FKNOWN = {0x52: 0x3d2d, 0x53: 0x3d4c, 0x54: 0x3d56, 0x55: 0x3d57, 0x57: 0x3d78,
0x58: 0x3d79, 0x59: 0x3d7f, 0x5a: 0x3d80, 0x5b: 0x3d83, 0x5c: 0x3d86,
0x5d: 0x3d87, 0x5e: 0x3d89, 0x5f: 0x3d8a, 0x60: 0x3df1, 0x61: 0x3dff,
0x62: 0x3e00, 0x63: 0x3e1d, 0x64: 0x3e20, 0x65: 0x3e21, 0x66: 0x3e3b,
0x67: 0x3e46, 0x68: 0x3e80, 0x69: 0x3e84, 0x6a: 0x3ea6, 0x6b: 0x3eae,
0x6c: 0x3ec6, 0x6d: 0x3f08, 0x6e: 0x3f0a, 0x6f: 0x3f0b, 0x70: 0x3f0c,
0x71: 0x3f0d, 0x72: 0x3f0e, 0x73: 0x3f0f, 0x74: 0x3f10, 0x75: 0x3f17,
0x76: 0x3f21, 0x77: 0x3f57, 0x82: 0x3fae, 0x8c: 0x3fca, 0x94: 0x4007,
0x97: 0x401b, 0x99: 0x4023, 0xa7: 0xbd56, 0xa8: 0xbd57, 0xa9: 0xbd61,
0xaa: 0xbd70, 0xab: 0xbd75, 0xac: 0xbd78, 0xae: 0xbd7f, 0xaf: 0xbd80,
0xb0: 0xbd83, 0xb1: 0xbd86, 0xb2: 0xbd87, 0xb3: 0xbd89, 0xb4: 0xbd8a,
0xb5: 0xbdff, 0xb6: 0xbe00, 0xb7: 0xbe16, 0xb8: 0xbe20, 0xb9: 0xbe46,
0xba: 0xbe48, 0xbb: 0xbe72, 0xbc: 0xbe80, 0xbd: 0xbe84, 0xbe: 0xbeb2,
0xbf: 0xbecf, 0xc0: 0xbee4, 0xc1: 0xbeea, 0xc2: 0xbeee, 0xc3: 0xbef5,
0xc4: 0xbf0a, 0xc5: 0xbf1c, 0xc6: 0xbf20, 0xc7: 0xbf27, 0xc8: 0xbf32,
0xc9: 0xbf46, 0xca: 0xbf60, 0xcb: 0xbf66, 0xcc: 0xbf7a, 0xd7: 0xbfb2,
0xdd: 0xc01b}
FCONST = {0x0b: 1.0, 0x28: -1.0}
def rflt(s):
@@ -102,7 +120,9 @@ class P:
T = (0x37 + t - 0x30) if t < 0x40 else (0xb7 + t - 0x40)
raw = bytes([T]) + s.b[s.p:s.p + 3]
s.p += 3
elif t == 0xea:
elif t in (0xea, 0xee):
# ee: visto solo per rumore numerico attorno a zero (1e-14); che cosa lo distingua da ea
# non e' noto, la lunghezza si' (76 file letti fino in fondo)
raw = s.b[s.p:s.p + 3] + bytes(1)
s.p += 3
elif t == 0xeb:
@@ -121,8 +141,11 @@ class P:
elif t < 0x30:
return Unk(t)
elif 0x50 <= t <= 0xdf:
raw = (s.FBASE + t).to_bytes(2, 'big') + s.b[s.p:s.p + 2]
pl = s.b[s.p:s.p + 2]
s.p += 2
if t not in s.FKNOWN:
return Unk(t) # lunghezza giusta, valore ignoto: mai inventarlo
raw = s.FKNOWN[t].to_bytes(2, 'big') + pl
else:
raise Err(f"flt tag {t:02x} @{s.p - 1:x}")
return struct.unpack('>f', raw)[0]
@@ -133,8 +156,13 @@ class P:
return s.u8()
return b
# prefissi negativi a 16 bit dei tag a5-df: bfd0..c00d meno tre buchi (bfd2, bfdf, bffe)
NEG = [x for x in range(0xbfd0, 0xc00e) if x not in (0xbfd2, 0xbfdf, 0xbffe)]
# tag 4b-df -> primi due byte del double (seguono 6 byte). Non e' una formula: e' una tabella
# con dei buchi. tagfit.py la verifica con il vincolo geometrico dei B-rep (formato-psb.md 3.2)
POS = [0x3fb0, 0x3fb1, 0x3fb5] + [x for x in range(0x3fc0, 0x4019) if x not in (0x3fc6, 0x3fcb, 0x3fce)] # 4b-a3
NEG = ([0xbfc0] + [x for x in range(0xbfd0, 0xc00b) if x not in (0xbfd2, 0xbfdf, 0xbffd)]
+ [0xc00c, 0xc010, 0xc011]) # a4-df
PFX = dict(zip(range(0x4b, 0xe0), POS + NEG))
assert len(PFX) == 0xe0 - 0x4b == len(POS) + len(NEG)
def rdbl(s):
t = s.u8()
@@ -158,7 +186,7 @@ class P:
v = struct.unpack('>d', s.b[s.p:s.p + 8])[0]
s.p += 8
return v
if t == 0xea:
if t in (0xea, 0xee): # ee: come nei float, rumore attorno a zero; 3 byte
v = struct.unpack('>d', s.b[s.p:s.p + 3] + bytes(5))[0]
s.p += 3
return v
@@ -166,13 +194,17 @@ class P:
v = struct.unpack('>d', s.b[s.p:s.p + 7] + bytes(1))[0]
s.p += 7
return v
if 0x19 <= t <= 0x48:
if t <= 0x2f:
if 0x19 <= t <= 0x4a:
# cinque tag per byte alto T, nell'ordine: 7 byte, 2 byte + ripetizione, 2 byte,
# 3 byte, 6 byte. Positivi 19-31 (T = 3c-40), negativi 32-4a (T = bc-c0).
if t <= 0x31:
T = 0x3c + (t - 0x17) // 5
m = (t - 0x17) % 5
else:
T = 0xbc + (t - 0x30) // 5
m = (t - 0x30) % 5
if m < 2:
T -= 1
if m == 4:
pl = s.b[s.p:s.p + 2]
s.p += 2
@@ -194,8 +226,8 @@ class P:
s.p += 3
raw = bytes([T]) + pl + bytes(4)
return struct.unpack('>d', raw)[0]
if 0x49 <= t <= 0xdf:
hi = (0x3f75 + t) if t <= 0xa4 else s.NEG[t - 0xa5]
if 0x4b <= t <= 0xdf:
hi = s.PFX[t]
pl = s.b[s.p:s.p + 6]
s.p += 6
return struct.unpack('>d', hi.to_bytes(2, 'big') + pl)[0]
@@ -343,6 +375,12 @@ class P:
f['own'].add(top['schema'])
s.lenient += 1
return 'field'
if i is None and not jump and top is s.lastc and top['kind'] == 'struct' and s.last is not None and s.fields[s.last]['parent'] == par:
# il campo precedente e' finito qui per la regola sopra (stessa struct C dichiarata sotto
# due id diversi): i suoi fratelli posizionali lo seguono nello stesso contenitore
f['own'].add(top['schema'])
s.lenient += 1
return 'field'
fresh = top['kind'] == 'struct' and not top['node']
if jump and fresh and i != len(s.stack) - 1:
s.alias[top['field']] = par
+97
View File
@@ -0,0 +1,97 @@
"""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')}
+138
View File
@@ -0,0 +1,138 @@
"""Verifica la tabella dei prefissi dei double (psb.P.PFX, tag 4b-df) con un vincolo geometrico:
il punto di uno spigolo calcolato sulle due superfici adiacenti deve coincidere (brep.py).
Per ogni tag prova i prefissi vicini e sceglie quello che lascia meno punti incoerenti.
python scripts/psb/tagfit.py 9245000212.prt.6 "raw/*.prt.*"
Variabili d'ambiente: TAGS=4b,4c (solo questi tag), SPAN=40 (quanti prefissi provare per lato),
TOL=1e-3 (tolleranza in mm: le intersezioni non analitiche sono precise solo al millesimo).
"""
import sys, os, glob, math, struct, collections
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import psb, brep
class TF(float):
pass
orig = psb.P.rdbl
def rdbl(s):
p0 = s.p
t = s.b[p0]
v = orig(s)
if 0x4b <= t <= 0xdf and not isinstance(v, psb.Unk):
o = TF(v)
o.tag = t
o.pl = bytes(s.b[p0 + 1:p0 + 7])
return o
return v
psb.P.rdbl = rdbl
slots = collections.defaultdict(list) # tag -> [(lista, indice, payload)]
edges = collections.defaultdict(set) # tag -> {indice in E}
E = [] # (spigolo, superfici del file)
def collect(x, found):
"""registra dove stanno i double a prefisso dentro x (liste annidate)"""
for i, v in enumerate(x):
if isinstance(v, TF):
slots[v.tag].append((x, i, v.pl))
found.add(v.tag)
elif isinstance(v, list):
collect(v, found)
def prim_tags(s, cache={}):
k = id(s)
if k not in cache:
f = set()
p = brep.prim(s)
if p is not None:
for j, (n, v) in enumerate(p):
if isinstance(v, list):
collect(v, f)
elif isinstance(v, TF): # scalare (radius, half_angle): lo si porta in lista
box = [v]
p[j] = (n, box)
collect(box, f)
cache[k] = f
return cache[k]
def unbox(v):
return v[0] if isinstance(v, list) and len(v) == 1 and not isinstance(v[0], list) else v
SCALARS = ('radius', 'half_angle', 'radius1', 'radius2')
_get = psb.Node.get
psb.Node.get = lambda s, k, d=None: unbox(_get(s, k, d)) if k in SCALARS else _get(s, k, d)
TOL = float(os.environ.get('TOL', '1e-5'))
def nbad(idx):
n = 0
for i in idx:
c, S = E[i]
try:
a, b = brep.side_points(c, S, 0), brep.side_points(c, S, 1)
except (ValueError, TypeError):
continue
if a is None or b is None:
continue
n += sum(1 for x, y in zip(a, b) if math.dist(x, y) > TOL)
return n
def setpfx(t, hi):
for x, i, pl in slots[t]:
x[i] = struct.unpack('>d', hi.to_bytes(2, 'big') + pl)[0]
files = [g for a in sys.argv[1:] for g in glob.glob(a)]
used = 0
for f in files:
try:
srf, crv = brep.load(f)
except (SystemExit, Exception):
continue
if not srf or not crv:
continue
used += 1
S = {s.get('geom_id'): s for s in srf}
for c in crv:
tags = set()
if c.get('crv_pnt_arr'):
collect(c.get('crv_pnt_arr'), tags)
for k in (0, 1):
s = S.get(c.get(f'crv_hdr_geom_ptr[{k}]'))
if s is not None:
tags |= prim_tags(s)
E.append((c, S))
for t in tags:
edges[t].add(len(E) - 1)
print(f"file con VisibGeom leggibile: {used}/{len(files)} spigoli {len(E)} punti incoerenti all'inizio {nbad(range(len(E)))}")
pfx = dict(psb.P.PFX)
only = {int(x, 16) for x in os.environ.get('TAGS', '').split(',') if x}
span = int(os.environ.get('SPAN', '6'))
for t in sorted(edges):
if only and t not in only:
continue
cur = pfx[t]
score = {}
for hi in range(cur - span, cur + span + 1):
setpfx(t, hi)
score[hi] = nbad(edges[t])
setpfx(t, cur)
best = min(score, key=lambda h: (score[h], abs(h - cur)))
second = min(v for h, v in score.items() if h != best)
verdict = 'PROVATO' if best == cur and second > score[cur] else 'non distinguibile' if best == cur else f'MEGLIO {best:04x} ({score[best]})'
print(f"tag {t:02x} -> {cur:04x} spigoli {len(edges[t]):4} incoerenti {score[cur]:4} miglior alternativa {second:4} {verdict}")
print("tag mai usati da uno spigolo (non verificabili cosi'):",
' '.join(f"{t:02x}" for t in sorted(psb.P.PFX) if t not in edges))