- 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>
134 lines
6.0 KiB
Python
134 lines
6.0 KiB
Python
"""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")
|