- app/: app demo (Kivy/buildozer) da API do robo - software/: servidor RoboMovel (SLAM, profundidade, navegacao) e firmware da base movel (movido de firmware/) - simulacao/: projeto Godot do robo e script de lancamento servidor + simulacao - modelos/: planta do 5o andar do bloco D, cena Blender do corredor e modelo real do robo - partes/mdf/: chapas identificadas e nesting da base do robo (DXF/SVG/FCStd) - projeto/render, relatorio/imagens, slides: renders finais e apresentacoes de progresso - ferramentas/scripts: encaixe de chapas, planta do bloco D e render do corredor no Blender - .gitignore: ignora backups do Blender/FreeCAD e .godot/
312 lines
13 KiB
Python
312 lines
13 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Reorganiza as peças de MDF (DXF de partes/mdf/dxf/pecas) em chapas 900 x 600 mm
|
|
gastando o mínimo de chapas possível.
|
|
|
|
* lê cada DXF R12 de peça (LINE / CIRCLE / ARC, gerados por corte.py);
|
|
* encaixa os retângulos envolventes com MaxRects (Best Short Side Fit),
|
|
permitindo girar 90°, e repete com ordens aleatórias guardando o melhor arranjo:
|
|
menos chapas, depois a última chapa o mais vazia/compacta possível
|
|
(sobra em um retalho grande, reaproveitável);
|
|
* grava chapas em dxf/chapas, svg/chapas (laser, com e sem nomes) e svg/conferencia.
|
|
|
|
Uso: python3 encaixe_chapas.py [pasta partes/mdf] [--tentativas N] [--seed S]
|
|
[--so Peca1,Peca2,...] [--saida prefixo]
|
|
--so encaixa só as peças listadas (nomes dos DXF, sem extensão)
|
|
--saida prefixo dos arquivos gerados (padrão "chapa"; só apaga arquivos com esse prefixo)
|
|
Não precisa de FreeCAD nem de bibliotecas externas.
|
|
"""
|
|
import glob, math, os, random, sys
|
|
|
|
SHEET = (900.0, 600.0)
|
|
MARGEM = 6.0 # da borda da chapa até a peça
|
|
GAP = 6.0 # entre peças
|
|
EPS = 1e-6
|
|
|
|
|
|
# ---------------------------------------------------------------- leitura DXF
|
|
def ler_dxf(path):
|
|
t = [l.strip() for l in open(path).read().split("\n")]
|
|
pares = list(zip(t[0::2], t[1::2]))
|
|
ents, cur, em_ent = [], None, False
|
|
for c, v in pares:
|
|
if c == "0":
|
|
if cur:
|
|
ents.append(cur)
|
|
cur = {"tipo": v} if v in ("LINE", "CIRCLE", "ARC") else None
|
|
elif cur is not None:
|
|
cur[c] = float(v) if c not in ("8",) else v
|
|
if cur:
|
|
ents.append(cur)
|
|
out = []
|
|
for e in ents:
|
|
if e["tipo"] == "LINE":
|
|
out.append(("LINE", (e["10"], e["20"]), (e["11"], e["21"])))
|
|
elif e["tipo"] == "CIRCLE":
|
|
out.append(("CIRCLE", (e["10"], e["20"]), e["40"]))
|
|
else:
|
|
out.append(("ARC", (e["10"], e["20"]), e["40"], e["50"], e["51"]))
|
|
return out
|
|
|
|
|
|
def bbox(ents):
|
|
xs, ys = [], []
|
|
for e in ents:
|
|
if e[0] == "LINE":
|
|
xs += [e[1][0], e[2][0]]; ys += [e[1][1], e[2][1]]
|
|
elif e[0] == "CIRCLE":
|
|
(cx, cy), r = e[1], e[2]
|
|
xs += [cx - r, cx + r]; ys += [cy - r, cy + r]
|
|
else:
|
|
(cx, cy), r, a0, a1 = e[1], e[2], e[3], e[4]
|
|
angs = [a0, a1] + [a for a in (0, 90, 180, 270) if (a - a0) % 360 <= (a1 - a0) % 360]
|
|
for a in angs:
|
|
xs.append(cx + r * math.cos(math.radians(a))); ys.append(cy + r * math.sin(math.radians(a)))
|
|
return min(xs), min(ys), max(xs), max(ys)
|
|
|
|
|
|
def transformar(ents, rot, dx, dy):
|
|
"""Leva a peça para a origem (bbox), gira 90° anti-horário se rot, depois desloca."""
|
|
x0, y0, x1, y1 = bbox(ents)
|
|
h = y1 - y0
|
|
|
|
def P(p):
|
|
x, y = p[0] - x0, p[1] - y0
|
|
if rot:
|
|
x, y = h - y, x
|
|
return (x + dx, y + dy)
|
|
out = []
|
|
for e in ents:
|
|
if e[0] == "LINE":
|
|
out.append(("LINE", P(e[1]), P(e[2])))
|
|
elif e[0] == "CIRCLE":
|
|
out.append(("CIRCLE", P(e[1]), e[2]))
|
|
else:
|
|
da = 90.0 if rot else 0.0
|
|
out.append(("ARC", P(e[1]), e[2], (e[3] + da) % 360, (e[4] + da) % 360))
|
|
return out
|
|
|
|
|
|
# ---------------------------------------------------------------- MaxRects
|
|
class Chapa:
|
|
def __init__(self, W, H):
|
|
self.W, self.H = W, H
|
|
self.livres = [(0.0, 0.0, W, H)]
|
|
self.usados = []
|
|
|
|
def melhor(self, w, h):
|
|
best = None
|
|
for fx, fy, fw, fh in self.livres:
|
|
for rot, (pw, ph) in ((False, (w, h)), (True, (h, w))):
|
|
if pw <= fw + EPS and ph <= fh + EPS:
|
|
curto = min(fw - pw, fh - ph)
|
|
longo = max(fw - pw, fh - ph)
|
|
chave = (curto, longo, fy, fx)
|
|
if best is None or chave < best[0]:
|
|
best = (chave, fx, fy, pw, ph, rot)
|
|
return best
|
|
|
|
def colocar(self, x, y, w, h):
|
|
novos = []
|
|
for f in self.livres:
|
|
fx, fy, fw, fh = f
|
|
if x >= fx + fw - EPS or x + w <= fx + EPS or y >= fy + fh - EPS or y + h <= fy + EPS:
|
|
novos.append(f)
|
|
continue
|
|
if x > fx + EPS:
|
|
novos.append((fx, fy, x - fx, fh))
|
|
if x + w < fx + fw - EPS:
|
|
novos.append((x + w, fy, fx + fw - x - w, fh))
|
|
if y > fy + EPS:
|
|
novos.append((fx, fy, fw, y - fy))
|
|
if y + h < fy + fh - EPS:
|
|
novos.append((fx, y + h, fw, fy + fh - y - h))
|
|
# remove retângulos contidos em outros
|
|
lim = []
|
|
for i, a in enumerate(novos):
|
|
if any(j != i and a[0] >= b[0] - EPS and a[1] >= b[1] - EPS and a[0] + a[2] <= b[0] + b[2] + EPS
|
|
and a[1] + a[3] <= b[1] + b[3] + EPS and (a != b or j < i) for j, b in enumerate(novos)):
|
|
continue
|
|
lim.append(a)
|
|
self.livres = lim
|
|
self.usados.append((x, y, w, h))
|
|
|
|
|
|
def encaixar(pecas, ordem):
|
|
"""pecas: {nome: (w, h)} já com GAP somado. Retorna lista de chapas [(nome, x, y, rot)]."""
|
|
W = SHEET[0] - 2 * MARGEM + GAP
|
|
H = SHEET[1] - 2 * MARGEM + GAP
|
|
chapas, arranjo = [], []
|
|
for nome in ordem:
|
|
w, h = pecas[nome]
|
|
feito = False
|
|
for c, arr in zip(chapas, arranjo):
|
|
m = c.melhor(w, h)
|
|
if m:
|
|
_, x, y, pw, ph, rot = m
|
|
c.colocar(x, y, pw, ph); arr.append((nome, x, y, rot)); feito = True
|
|
break
|
|
if not feito:
|
|
c = Chapa(W, H)
|
|
m = c.melhor(w, h)
|
|
if not m:
|
|
raise SystemExit("peça %s não cabe na chapa" % nome)
|
|
_, x, y, pw, ph, rot = m
|
|
c.colocar(x, y, pw, ph)
|
|
chapas.append(c); arranjo.append([(nome, x, y, rot)])
|
|
return chapas, arranjo
|
|
|
|
|
|
def custo(chapas):
|
|
# 1) número de chapas; 2) área ocupada (envoltória) na última chapa -> retalho maior;
|
|
# 3) envoltória da penúltima, e assim por diante
|
|
def env(c):
|
|
return max(x + w for x, y, w, h in c.usados) * max(y + h for x, y, w, h in c.usados)
|
|
return (len(chapas), env(chapas[-1]), env(chapas[-2]) if len(chapas) > 1 else 0)
|
|
|
|
|
|
# ---------------------------------------------------------------- saída
|
|
def dxf_write(path, grupos):
|
|
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, (ox, oy), nome in grupos:
|
|
for e in ents:
|
|
if e[0] == "LINE":
|
|
L += ["0", "LINE", "8", "CORTE", "10", f(e[1][0]), "20", f(e[1][1]), "30", "0",
|
|
"11", f(e[2][0]), "21", f(e[2][1]), "31", "0"]
|
|
elif e[0] == "CIRCLE":
|
|
L += ["0", "CIRCLE", "8", "CORTE", "10", f(e[1][0]), "20", f(e[1][1]), "30", "0", "40", f(e[2])]
|
|
else:
|
|
L += ["0", "ARC", "8", "CORTE", "10", f(e[1][0]), "20", f(e[1][1]), "30", "0",
|
|
"40", f(e[2]), "50", f(e[3]), "51", f(e[4])]
|
|
L += ["0", "TEXT", "8", "TEXTO", "10", f(ox + 2), "20", f(oy + 2), "30", "0", "40", "3", "1", nome]
|
|
L += ["0", "ENDSEC", "0", "EOF"]
|
|
open(path, "w").write("\n".join(L))
|
|
|
|
|
|
def svg_ents(ents, Hs):
|
|
Y = lambda y: Hs - y
|
|
out = []
|
|
for e in ents:
|
|
if e[0] == "LINE":
|
|
out.append('<line x1="%.4f" y1="%.4f" x2="%.4f" y2="%.4f"/>' % (e[1][0], Y(e[1][1]), e[2][0], Y(e[2][1])))
|
|
elif e[0] == "CIRCLE":
|
|
out.append('<circle cx="%.4f" cy="%.4f" r="%.4f"/>' % (e[1][0], Y(e[1][1]), e[2]))
|
|
else:
|
|
(cx, cy), r = e[1], e[2]
|
|
sa, ea = math.radians(e[3]), math.radians(e[4])
|
|
p0 = (cx + r * math.cos(sa), Y(cy + r * math.sin(sa)))
|
|
p1 = (cx + r * math.cos(ea), Y(cy + r * math.sin(ea)))
|
|
large = 1 if (e[4] - e[3]) % 360 > 180 else 0
|
|
out.append('<path d="M %.4f %.4f A %.4f %.4f 0 %d 0 %.4f %.4f"/>' % (p0[0], p0[1], r, r, large, p1[0], p1[1]))
|
|
return out
|
|
|
|
|
|
def svg_laser(path, grupos, nomes=False):
|
|
Ws, Hs = SHEET
|
|
s = ['<?xml version="1.0" encoding="UTF-8"?>',
|
|
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" '
|
|
'width="%.3fmm" height="%.3fmm" viewBox="0 0 %.3f %.3f">' % (Ws, Hs, Ws, Hs),
|
|
'<g inkscape:groupmode="layer" inkscape:label="CORTE" fill="none" stroke="#FF0000" stroke-width="0.01">']
|
|
for ents, off, nome in grupos:
|
|
s.append('<g id="%s">' % nome)
|
|
s += svg_ents(ents, Hs)
|
|
s.append("</g>")
|
|
s.append("</g>")
|
|
if nomes:
|
|
s.append('<g inkscape:groupmode="layer" inkscape:label="GRAVAR_NOMES" fill="#0000FF" stroke="none" '
|
|
'font-family="DejaVu Sans, Arial" font-size="5">')
|
|
for ents, (ox, oy), nome in grupos:
|
|
s.append('<text x="%.2f" y="%.2f">%s</text>' % (ox + 4, Hs - (oy + 4), nome.replace("_", " ")))
|
|
s.append("</g>")
|
|
s.append("</svg>")
|
|
open(path, "w").write("\n".join(s))
|
|
|
|
|
|
def svg_conferencia(path, grupos, caixas, titulo):
|
|
Ws, Hs = SHEET
|
|
s = ['<svg xmlns="http://www.w3.org/2000/svg" width="%dmm" height="%dmm" viewBox="0 0 %d %d">' % (Ws, Hs, Ws, Hs),
|
|
'<rect x="0" y="0" width="%d" height="%d" fill="#f4ead9" stroke="#999"/>' % (Ws, Hs)]
|
|
for (x, y, w, h) in caixas:
|
|
s.append('<rect x="%.2f" y="%.2f" width="%.2f" height="%.2f" fill="#e6d3b3" stroke="none"/>' % (x, Hs - y - h, w, h))
|
|
s.append('<g fill="none" stroke="#c00" stroke-width="0.4">')
|
|
for ents, off, nome in grupos:
|
|
s += svg_ents(ents, Hs)
|
|
s.append("</g>")
|
|
for ents, (ox, oy), nome in grupos:
|
|
s.append('<text x="%.1f" y="%.1f" font-size="6" fill="#036">%s</text>' % (ox + 3, Hs - oy - 3, nome))
|
|
s.append('<text x="%.1f" y="%.1f" font-size="9" fill="#555" text-anchor="end">%s</text>' % (Ws - 8, Hs - 4, titulo))
|
|
s.append("</svg>")
|
|
open(path, "w").write("\n".join(s))
|
|
|
|
|
|
# ---------------------------------------------------------------- main
|
|
def main():
|
|
args = sys.argv[1:]
|
|
raiz = next((a for a in args if not a.startswith("--") and os.path.isdir(a)),
|
|
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "partes", "mdf"))
|
|
raiz = os.path.abspath(raiz)
|
|
N = int(args[args.index("--tentativas") + 1]) if "--tentativas" in args else 3000
|
|
seed = int(args[args.index("--seed") + 1]) if "--seed" in args else 1
|
|
so = set(args[args.index("--so") + 1].split(",")) if "--so" in args else None
|
|
prefixo = args[args.index("--saida") + 1] if "--saida" in args else "chapa"
|
|
|
|
geo, pecas = {}, {}
|
|
for f in sorted(glob.glob(os.path.join(raiz, "dxf", "pecas", "*.dxf"))):
|
|
nome = os.path.splitext(os.path.basename(f))[0]
|
|
if so is not None and nome not in so:
|
|
continue
|
|
geo[nome] = ler_dxf(f)
|
|
x0, y0, x1, y1 = bbox(geo[nome])
|
|
pecas[nome] = (x1 - x0 + GAP, y1 - y0 + GAP)
|
|
area = sum((w - GAP) * (h - GAP) for w, h in pecas.values())
|
|
|
|
rnd = random.Random(seed)
|
|
base = sorted(pecas, key=lambda n: (-pecas[n][0] * pecas[n][1], n))
|
|
melhor = None
|
|
for i in range(N):
|
|
if i == 0:
|
|
ordem = base
|
|
else:
|
|
# perturba levemente a ordem por área (mantém grandes primeiro)
|
|
ordem = sorted(base, key=lambda n: -pecas[n][0] * pecas[n][1] * rnd.uniform(0.6, 1.4))
|
|
chapas, arranjo = encaixar(pecas, ordem)
|
|
k = custo(chapas)
|
|
if melhor is None or k < melhor[0]:
|
|
melhor = (k, chapas, arranjo)
|
|
k, chapas, arranjo = melhor
|
|
|
|
for sub in ("dxf/chapas", "svg/chapas", "svg/conferencia"):
|
|
d = os.path.join(raiz, sub)
|
|
os.makedirs(d, exist_ok=True)
|
|
for f in glob.glob(os.path.join(d, prefixo + "_[0-9]*")):
|
|
os.remove(f)
|
|
|
|
total = SHEET[0] * SHEET[1]
|
|
print("%d peças, área líquida %.3f m² -> %d chapas (mínimo teórico por área: %.2f)"
|
|
% (len(pecas), area / 1e6, len(chapas), area / total))
|
|
for i, (c, arr) in enumerate(zip(chapas, arranjo)):
|
|
grupos, caixas = [], []
|
|
for nome, x, y, rot in arr:
|
|
ox, oy = x + MARGEM, y + MARGEM
|
|
grupos.append((transformar(geo[nome], rot, ox, oy), (ox, oy), nome))
|
|
w, h = pecas[nome]
|
|
if rot:
|
|
w, h = h, w
|
|
caixas.append((ox, oy, w - GAP, h - GAP))
|
|
uso = sum(w * h for _, _, w, h in caixas) / total
|
|
n = "%s_%d_900x600" % (prefixo, i + 1)
|
|
dxf_write(os.path.join(raiz, "dxf", "chapas", n + ".dxf"), grupos)
|
|
svg_laser(os.path.join(raiz, "svg", "chapas", n + ".svg"), grupos)
|
|
svg_laser(os.path.join(raiz, "svg", "chapas", n + "_nomes.svg"), grupos, nomes=True)
|
|
svg_conferencia(os.path.join(raiz, "svg", "conferencia", n + ".svg"), grupos, caixas,
|
|
"%s %d - %d peças - %.0f%% ocupada" % (prefixo.replace("_", " "), i + 1, len(arr), uso * 100))
|
|
print(" chapa %d: %2d peças, %.0f%% ocupada" % (i + 1, len(arr), uso * 100))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|