# -*- coding: utf-8 -*- """Exporta as peças de MDF da montagem para corte a laser. * planifica cada peça (face maior -> plano XY); * gera 1 DXF (R12, mm) por peça em corte/pecas/ e chapas 900 x 600 mm com as peças arranjadas (corte/chapa_N.dxf) + um SVG de conferência; * camadas: CORTE (vermelho, contorno e furos). Compensação de kerf NÃO aplicada no desenho: ajuste na máquina (tipicamente 0,08–0,12 mm por lado para MDF 3 mm) ou altere CL em montagem_base.py. """ import math, os, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # cad/ deste repositório import FreeCAD as App import Part from FreeCAD import Vector as V, Rotation, Placement import montagem_base as MB OUT = os.path.join(MB.CORTE) SHEET = (900.0, 600.0) GAP = 6.0 def flatten(shape): faces = sorted([f for f in shape.Faces if f.Surface.__class__.__name__ == "Plane"], key=lambda f: -f.Area) n = faces[0].normalAt(0, 0) rot = Rotation(n, V(0, 0, 1)) s = shape.copy() s.Placement = Placement(V(), rot).multiply(s.Placement) bb = s.BoundBox s.translate(V(-bb.XMin, -bb.YMin, -bb.ZMin)) # se a peça ficou "em pé" de outro jeito, garante espessura em Z # (uma face por sólido: num composto, ex. nervura + miolos, todas as peças entram) bots = [] for sol in (s.Solids or [s]): fs = [f for f in sol.Faces if f.Surface.__class__.__name__ == "Plane" and abs(f.BoundBox.ZMax) < 1e-4 and abs(f.BoundBox.ZMin) < 1e-4] if fs: bots.append(max(fs, key=lambda f: f.Area)) bot = bots[0] if len(bots) == 1 else Part.makeCompound(bots) # gira no plano para ficar paisagem bb = bot.BoundBox if bb.YLength > bb.XLength: bot.rotate(V(0, 0, 0), V(0, 0, 1), 90) b2 = bot.BoundBox bot.translate(V(-b2.XMin, -b2.YMin, 0)) return bot def edges_2d(face): ents = [] for e in face.Edges: c = e.Curve cn = c.__class__.__name__ if cn == "Line" or cn == "LineSegment": a, b = e.Vertexes[0].Point, e.Vertexes[-1].Point ents.append(("LINE", a, b)) elif cn == "Circle" and e.isClosed(): ents.append(("CIRCLE", c.Center, c.Radius)) elif cn == "Circle": cen = c.Center a, b = e.Vertexes[0].Point, e.Vertexes[-1].Point m = e.valueAt((e.FirstParameter + e.LastParameter) / 2) ang = lambda p: math.degrees(math.atan2(p.y - cen.y, p.x - cen.x)) % 360 sa, ea, ma = ang(a), ang(b), ang(m) # arco anti-horário de sa a ea deve conter ma def ccw_contains(s, e_, x): return (x - s) % 360 < (e_ - s) % 360 if not ccw_contains(sa, ea, ma): sa, ea = ea, sa ents.append(("ARC", cen, c.Radius, sa, ea)) else: pts = e.discretize(Deflection=0.02) for p, q in zip(pts[:-1], pts[1:]): ents.append(("LINE", p, q)) return sem_repetidas(ents) def sem_repetidas(ents, tol=1e-3): """Remove entidades iguais (ex.: contorno do miolo que coincide com o da abertura): o laser não deve passar duas vezes na mesma linha.""" r = lambda v: (round(v.x / tol), round(v.y / tol)) vistos, out = set(), [] for en in ents: if en[0] == "LINE": chave = ("LINE",) + tuple(sorted((r(en[1]), r(en[2])))) elif en[0] == "CIRCLE": chave = ("CIRCLE", r(en[1]), round(en[2] / tol)) else: chave = ("ARC", r(en[1]), round(en[2] / tol), round(en[3] % 360, 1), round(en[4] % 360, 1)) if chave not in vistos: vistos.add(chave) out.append(en) return out def dxf_write(path, groups): """groups: lista de (entidades, deslocamento V, rótulo).""" L = ["0", "SECTION", "2", "HEADER", "9", "$INSUNITS", "70", "4", "0", "ENDSEC", "0", "SECTION", "2", "TABLES", "0", "TABLE", "2", "LAYER", "70", "2", "0", "LAYER", "2", "CORTE", "70", "0", "62", "1", "6", "CONTINUOUS", "0", "LAYER", "2", "TEXTO", "70", "0", "62", "5", "6", "CONTINUOUS", "0", "ENDTAB", "0", "ENDSEC", "0", "SECTION", "2", "ENTITIES"] f = lambda v: "%.4f" % v for ents, off, label in groups: for en in ents: if en[0] == "LINE": a, b = en[1] + off, en[2] + off L += ["0", "LINE", "8", "CORTE", "10", f(a.x), "20", f(a.y), "30", "0", "11", f(b.x), "21", f(b.y), "31", "0"] elif en[0] == "CIRCLE": c = en[1] + off L += ["0", "CIRCLE", "8", "CORTE", "10", f(c.x), "20", f(c.y), "30", "0", "40", f(en[2])] else: c = en[1] + off L += ["0", "ARC", "8", "CORTE", "10", f(c.x), "20", f(c.y), "30", "0", "40", f(en[2]), "50", f(en[3]), "51", f(en[4])] if label: L += ["0", "TEXT", "8", "TEXTO", "10", f(off.x + 2), "20", f(off.y + 2), "30", "0", "40", "3", "1", label] L += ["0", "ENDSEC", "0", "EOF"] with open(path, "w") as fh: fh.write("\n".join(L)) def svg_write(path, sheet_items, W, H): s = ['' % (W, H, W, H), '' % (W, H)] for face, off, label in sheet_items: for w in face.Wires: pts = w.discretize(Deflection=0.2) d = "M " + " L ".join("%.2f %.2f" % (p.x + off.x, H - (p.y + off.y)) for p in pts) + " Z" s.append('' % d) s.append('%s' % (off.x + 3, H - off.y - 3, label)) s.append("") open(path, "w").write("\n".join(s)) def export(parts=None): parts = parts or MB.MDF_PARTS or MB.mdf_parts() os.makedirs(os.path.join(OUT, "pecas"), exist_ok=True) flat = [] for name, (shape, desc) in parts.items(): face = flatten(shape) ents = edges_2d(face) dxf_write(os.path.join(OUT, "pecas", name + ".dxf"), [(ents, V(0, 0, 0), None)]) flat.append((name, face, ents)) # arranjo em chapas (prateleiras, maior primeiro) flat.sort(key=lambda t: -t[1].BoundBox.YLength * 1000 - t[1].BoundBox.XLength) sheets, cur, x, y, row_h = [], [], GAP, GAP, 0 for name, face, ents in flat: bb = face.BoundBox if x + bb.XLength + GAP > SHEET[0]: x, y, row_h = GAP, y + row_h + GAP, 0 if y + bb.YLength + GAP > SHEET[1]: sheets.append(cur) cur, x, y, row_h = [], GAP, GAP, 0 cur.append((name, face, ents, V(x, y, 0))) x += bb.XLength + GAP row_h = max(row_h, bb.YLength) if cur: sheets.append(cur) for i, sh in enumerate(sheets): dxf_write(os.path.join(OUT, "chapa_%d_900x600.dxf" % (i + 1)), [(e, o, n) for n, f, e, o in sh]) svg_write(os.path.join(OUT, "chapa_%d_900x600.svg" % (i + 1)), [(f, o, n) for n, f, e, o in sh], *SHEET) return len(flat), len(sheets) # ---------------------------------------------------------------- SVG para laser def _svg_paths(ents, off, Hs): """Entidades -> elementos SVG (mm). Espelha Y (SVG cresce p/ baixo).""" import math Y = lambda y: Hs - y out = [] for en in ents: if en[0] == "LINE": a, b = en[1] + off, en[2] + off out.append('' % (a.x, Y(a.y), b.x, Y(b.y))) elif en[0] == "CIRCLE": c = en[1] + off out.append('' % (c.x, Y(c.y), en[2])) else: c, r, sa, ea = en[1] + off, en[2], math.radians(en[3]), math.radians(en[4]) p0 = (c.x + r * math.cos(sa), Y(c.y + r * math.sin(sa))) p1 = (c.x + r * math.cos(ea), Y(c.y + r * math.sin(ea))) sweep = (en[4] - en[3]) % 360 large = 1 if sweep > 180 else 0 # anti-horário no plano Y-cima vira horário no SVG (sweep-flag 0) out.append('' % (p0[0], p0[1], r, r, large, p1[0], p1[1])) return out def svg_laser(path, groups, Ws, Hs, names=False): s = ['', '' % (Ws, Hs, Ws, Hs), ''] for ents, off, label in groups: s.append('' % (label or "peca")) s += _svg_paths(ents, off, Hs) s.append("") s.append("") if names: s.append('') for ents, off, label in groups: if label: s.append('%s' % (off.x + 4, Hs - (off.y + 4), label.replace("_", " "))) s.append("") s.append("") open(path, "w").write("\n".join(s)) def export_svg(parts=None): """Gera SVGs de laser: corte/laser/chapa_N_900x600[_nomes].svg e corte/laser/pecas/*.svg""" parts = parts or MB.MDF_PARTS or MB.mdf_parts() L = os.path.join(OUT, "laser") os.makedirs(os.path.join(L, "pecas"), exist_ok=True) flat = [] for name, (shape, desc) in parts.items(): face = flatten(shape) ents = edges_2d(face) bb = face.BoundBox svg_laser(os.path.join(L, "pecas", name + ".svg"), [(ents, V(0, 0, 0), name)], bb.XLength, bb.YLength) flat.append((name, face, ents)) flat.sort(key=lambda t: -t[1].BoundBox.YLength * 1000 - t[1].BoundBox.XLength) sheets, cur, x, y, row_h = [], [], GAP, GAP, 0 for name, face, ents in flat: bb = face.BoundBox if x + bb.XLength + GAP > SHEET[0]: x, y, row_h = GAP, y + row_h + GAP, 0 if y + bb.YLength + GAP > SHEET[1]: sheets.append(cur) cur, x, y, row_h = [], GAP, GAP, 0 cur.append((name, ents, V(x, y, 0))) x += bb.XLength + GAP row_h = max(row_h, bb.YLength) if cur: sheets.append(cur) for i, sh in enumerate(sheets): g = [(e, o, n) for n, e, o in sh] svg_laser(os.path.join(L, "chapa_%d_900x600.svg" % (i + 1)), g, *SHEET) svg_laser(os.path.join(L, "chapa_%d_900x600_nomes.svg" % (i + 1)), g, *SHEET, names=True) return len(flat), len(sheets)