# -*- coding: utf-8 -*- """Disposição das peças de MDF do robô 35x35 em 2 chapas de 900 x 600 mm: uma com as peças da base e outra com as das prateleiras. Rodar dentro do FreeCAD com interface (usa textos Draft). Gera, a partir de montagem_base_35x35.py: partes/mdf_35x35/dxf/pecas, dxf/chapas, svg/chapas, svg/conferencia (arquivos de corte) partes/mdf_35x35/chapas_identificadas_35x35.FCStd (documento de conferência) Mesmo formato de partes/mdf/chapas_identificadas.FCStd. """ import glob, os, random, shutil, sys, tempfile import FreeCAD as App import Part from FreeCAD import Vector as V, Placement, Rotation AQUI = os.path.dirname(os.path.abspath(__file__)) REPO = os.path.abspath(os.path.join(AQUI, "..", "..", "..")) RAIZ = os.path.join(REPO, "partes", "mdf_35x35") DOC = "chapas_identificadas_35x35" ANTIGO = os.path.join(REPO, "partes", "mdf", "chapas_identificadas.FCStd") PASSO_Y = 700.0 # distância entre as chapas no documento TENTATIVAS, SEED = 3000, 1 GRUPOS = (("base", "BASE DO ROBÔ"), ("prateleiras", "PRATELEIRAS")) # uma chapa por grupo VERMELHO = (1.0, 0.149, 0.149) AZUL = (0.451, 0.8, 1.0) CINZA = (0.6, 0.6, 0.6) for p in (AQUI, os.path.join(AQUI, "pecas")): if p not in sys.path: sys.path.insert(0, p) def exportar_pecas(): """DXF de cada peça, gerado da geometria atual de montagem_base_35x35.""" tmp = tempfile.mkdtemp() os.environ["RM25_CORTE"] = tmp import importlib import montagem_base_35x35 as MB importlib.reload(MB) anterior = sys.modules.get("montagem_base") sys.modules["montagem_base"] = MB try: import corte importlib.reload(corte) corte.export(MB.mdf_parts()) finally: if anterior is None: del sys.modules["montagem_base"] else: sys.modules["montagem_base"] = anterior destino = os.path.join(RAIZ, "dxf", "pecas") os.makedirs(destino, exist_ok=True) for f in glob.glob(os.path.join(destino, "*.dxf")): os.remove(f) for f in glob.glob(os.path.join(tmp, "pecas", "*.dxf")): shutil.copy(f, destino) shutil.rmtree(tmp) os.environ.pop("RM25_CORTE", None) calcos_nas_nervuras(destino, MB) def calcos_nas_nervuras(destino, MB): """Os miolos das aberturas das nervuras viram calços: grava os furos M4 dentro de cada abertura e tira das chapas os calços avulsos que deixam de ser necessários. No laser, os furos precisam ser cortados antes do contorno da abertura.""" import encaixe_chapas as EC import suporte_nema17 as SP n_miolos = 0 for nome in ("Nervura_Long_D", "Nervura_Long_E", "Nervura_Transversal"): caminho = os.path.join(destino, nome + ".dxf") ents = EC.ler_dxf(caminho) x0, y0, x1, y1 = EC.bbox(ents) eixo = 0 if x1 - x0 > y1 - y0 else 1 # as aberturas seguem o comprimento da nervura arcos = sorted((e[1] for e in ents if e[0] == "ARC" and abs(e[2] - MB.OPEN_R) < 1e-3), key=lambda c: c[eixo]) if not arcos or len(arcos) % 4: raise SystemExit("%s: esperava 4 arcos por abertura, achei %d" % (nome, len(arcos))) novos = "" for i in range(0, len(arcos), 4): grupo = arcos[i:i + 4] cx = sum(c[0] for c in grupo) / 4 cy = sum(c[1] for c in grupo) / 4 for sinal in (-1, 1): dx, dy = (sinal * SP.SLOT_X, 0) if eixo == 0 else (0, sinal * SP.SLOT_X) novos += "CIRCLE\n8\nCORTE\n10\n%.4f\n20\n%.4f\n30\n0\n40\n2.1500\n0\n" % (cx + dx, cy + dy) n_miolos += 1 with open(caminho) as fh: txt = fh.read() if txt.count("ENDSEC\n0\nEOF") != 1: raise SystemExit("%s: fim de DXF inesperado" % nome) with open(caminho, "w") as fh: fh.write(txt.replace("ENDSEC\n0\nEOF", novos + "ENDSEC\n0\nEOF")) calcos = glob.glob(os.path.join(destino, "Calco_*.dxf")) sobram = [f for f in calcos if os.path.splitext(os.path.basename(f))[0] in MB.CALCOS_AVULSOS] if len(calcos) - len(sobram) != n_miolos: raise SystemExit("%d miolos para %d calços dispensados" % (n_miolos, len(calcos) - len(sobram))) for f in calcos: if f not in sobram: os.remove(f) def grupo_de(nome): return "prateleiras" if nome.startswith("Prat_") else "base" def arranjo(): """Encaixa cada grupo em uma chapa própria. Grava os arquivos de corte com encaixe_chapas.main e repete o mesmo sorteio (mesma semente) para o documento.""" import importlib import encaixe_chapas as EC importlib.reload(EC) for pasta in ("dxf/chapas", "svg/chapas", "svg/conferencia"): # arranjos anteriores for f in glob.glob(os.path.join(RAIZ, pasta, "chapa_*")): os.remove(f) geo, todas = {}, {} for f in sorted(glob.glob(os.path.join(RAIZ, "dxf", "pecas", "*.dxf"))): nome = os.path.splitext(os.path.basename(f))[0] geo[nome] = EC.ler_dxf(f) x0, y0, x1, y1 = EC.bbox(geo[nome]) todas[nome] = (x1 - x0 + EC.GAP, y1 - y0 + EC.GAP) resultado = [] for grupo, titulo in GRUPOS: pecas = {n: v for n, v in todas.items() if grupo_de(n) == grupo} argv = sys.argv sys.argv = ["encaixe_chapas.py", RAIZ, "--tentativas", str(TENTATIVAS), "--seed", str(SEED), "--so", ",".join(sorted(pecas)), "--saida", "chapa_" + grupo] try: EC.main() finally: sys.argv = argv rnd = random.Random(SEED) base = sorted(pecas, key=lambda n: (-pecas[n][0] * pecas[n][1], n)) melhor = None for i in range(TENTATIVAS): ordem = base if i == 0 else sorted(base, key=lambda n: -pecas[n][0] * pecas[n][1] * rnd.uniform(0.6, 1.4)) chapas, arr = EC.encaixar(pecas, ordem) k = EC.custo(chapas) if melhor is None or k < melhor[0]: melhor = (k, arr) if len(melhor[1]) != 1: raise SystemExit("grupo %s não coube em uma chapa" % grupo) resultado.append((titulo, melhor[1][0])) return EC, geo, resultado def rotulos(): """Nomes das peças, reaproveitados do documento antigo (só leitura).""" aberto = App.listDocuments().get("chapas_identificadas") d = aberto or App.openDocument(ANTIGO, hidden=True) r = {o.Name: o.Label.replace("(X) ", "") for o in d.Objects if o.TypeId == "Part::Feature" and "contorno" not in o.Name} if not aberto: App.closeDocument(d.Name) return r def forma(ents, dy): arestas = [] for e in ents: if e[0] == "LINE": a, b = V(e[1][0], e[1][1] + dy, 0), V(e[2][0], e[2][1] + dy, 0) if (a - b).Length > 1e-6: arestas.append(Part.makeLine(a, b)) elif e[0] == "CIRCLE": arestas.append(Part.makeCircle(e[2], V(e[1][0], e[1][1] + dy, 0))) else: a0, a1 = e[3], e[4] if a1 <= a0: a1 += 360.0 arestas.append(Part.makeCircle(e[2], V(e[1][0], e[1][1] + dy, 0), V(0, 0, 1), a0, a1)) return Part.makeCompound(arestas) def texto(doc, grupo, nome, linhas, pos, tam, ang=0.0, just="Center", esp=1.1): import Draft t = Draft.make_text(linhas, Placement(pos, Rotation(V(0, 0, 1), ang))) t.Label = nome vo = t.ViewObject vo.FontSize = "%.3f mm" % tam vo.FontName = "Noto Sans" vo.Justification = just vo.TextColor = AZUL vo.LineSpacing = esp grupo.addObject(t) return t def tamanho_fonte(w, h, linhas): longo, curto = max(w, h), min(w, h) chars = max(len(l) for l in linhas) return min(12.0, longo * 0.9 / (0.56 * chars), curto * 0.8 / (1.1 * len(linhas))) def gerar(): os.makedirs(RAIZ, exist_ok=True) exportar_pecas() EC, geo, arr = arranjo() nomes = rotulos() if DOC in App.listDocuments(): App.closeDocument(DOC) doc = App.newDocument(DOC) W, H = EC.SHEET relatorio = [] for i, (nome_grupo, itens) in enumerate(arr): dy = -PASSO_Y * i g = doc.addObject("App::DocumentObjectGroup", "Chapa_%d" % (i + 1)) g.Label = "Chapa %d - %s" % (i + 1, nome_grupo.capitalize()) c = doc.addObject("Part::Feature", "Chapa_%d_contorno" % (i + 1)) c.Label = "Chapa %d contorno 900x600" % (i + 1) c.Shape = Part.makePolygon([V(0, dy, 0), V(W, dy, 0), V(W, H + dy, 0), V(0, H + dy, 0), V(0, dy, 0)]) c.ViewObject.LineColor = CINZA c.ViewObject.LineWidth = 2.0 g.addObject(c) area = 0.0 for nome, x, y, rot in itens: ox, oy = x + EC.MARGEM, y + EC.MARGEM ents = EC.transformar(geo[nome], rot, ox, oy) o = doc.addObject("Part::Feature", nome) rotulo = nomes.get(nome, nome.replace("_", " ")) o.Label = rotulo o.Shape = forma(ents, dy) o.ViewObject.LineColor = VERMELHO o.ViewObject.PointColor = VERMELHO o.ViewObject.LineWidth = 2.0 g.addObject(o) b = o.Shape.BoundBox area += b.XLength * b.YLength linhas = rotulo.split(" — ", 1) tam = tamanho_fonte(b.XLength, b.YLength, linhas) ang = 90.0 if b.YLength > b.XLength else 0.0 texto(doc, g, "txt " + nome, linhas, V(b.Center.x, b.Center.y, 0.2), tam, ang) titulo = "CHAPA %d: %s (%d peças, %.0f%% ocupada)" % (i + 1, nome_grupo, len(itens), 100.0 * area / (W * H)) texto(doc, g, "Título chapa %d" % (i + 1), [titulo], V(0, H + dy + 8.0, 0), 22.0, 0.0, "Left", 1.0) relatorio.append(titulo) doc.recompute() doc.saveAs(os.path.join(RAIZ, DOC + ".FCStd")) return doc, relatorio if __name__ == "__main__": gerar()