Macro Unfold Box: Difference between revisions
(Do not remove the pair of <nowiki> </nowiki> tags because the special symbols won't be parsed correctly) |
(v1.1) |
||
Line 6: | Line 6: | ||
|Icon=Macro_Unfold_Box.png |
|Icon=Macro_Unfold_Box.png |
||
|Description=The macro allows to unfold the surfaces of a box of any shape and to draw them on a page.<BR/> |
|Description=The macro allows to unfold the surfaces of a box of any shape and to draw them on a page.<BR/> |
||
|Author=Hervé B. |
|Author=Hervé B., heda |
||
|Version=1 |
|Version=1.1 |
||
|Date= |
|Date=2022-07-28 |
||
|FCVersion= |
|FCVersion= |
||
|Download=[https://www.freecadweb.org/wiki/images/e/e4/Macro_Unfold_Box.png ToolBar Icon] |
|Download=[https://www.freecadweb.org/wiki/images/e/e4/Macro_Unfold_Box.png ToolBar Icon] |
||
Line 21: | Line 21: | ||
== Installation == <!--T:4--> |
== Installation == <!--T:4--> |
||
Available in Add-on manager. |
|||
Copy the code file of the macro in the directory : |
|||
*'''Linux & Mac''' : $home/.Freecad/Mod/unfoldBox. |
|||
*'''Windows''' : C:\Program Files\FreeCAD0.13 |
|||
Add templates : A3_Landscape_Empty.svg A3_Landscape.svg A4_Landscape_Empty.svg A4_Landscape.svg<br /> |
|||
Cf [http://forum.freecadweb.org/viewtopic.php?f=17&t=4587 Macro for unfolding box surfaces] |
Cf [http://forum.freecadweb.org/viewtopic.php?f=17&t=4587 Macro for unfolding box surfaces] |
||
Line 32: | Line 30: | ||
# Group drawings in the same page as possible. |
# Group drawings in the same page as possible. |
||
# Sew or not the edges of the pieces. |
# Sew or not the edges of the pieces. |
||
[[File:Macro_UnFoldBox_start_form.png|Macro_unfoldBox]] |
|||
== Instruction for use == <!--T:6--> |
== Instruction for use == <!--T:6--> |
||
Line 38: | Line 38: | ||
# Select the surfaces |
# Select the surfaces |
||
# Execute the macro |
# Execute the macro |
||
The unfolding algorithm will place the faces on the xy-plane, however it seldom does the unfolding correctly. Thus some manual post-processing is needed to get to desired result, as shown in the picture below. |
|||
[[File:MacroUnFoldBoxInstruction.png|Macro_unfoldBox]] |
|||
Starting point is a box like the upper left picture. |
|||
# Select all faces and run the macro |
|||
# Orient to Top View |
|||
# Toggle visibilty on the created set of faces, the individual clones are to be visible, not the compound |
|||
# Use Draft/Move and Draft/Rotate to reposition the folded cloned faces (a handfull of clicks per face when snapping is used) |
|||
# The drawing updates automatically to the new positions |
|||
The finished result is shown in the lower right picture above. |
|||
==Script== <!--T:7--> |
==Script== <!--T:7--> |
||
Line 49: | Line 63: | ||
{{MacroCode|code= |
{{MacroCode|code= |
||
<nowiki> |
<nowiki> |
||
# -*- coding: utf-8 -*- |
|||
'''FreeCAD Macro unfoldBox. |
|||
""" |
|||
FreeCAD Macro unfoldBox. |
|||
Unfolding of planar surfaces |
|||
Unroll of a ruled surface |
|||
""" |
|||
''' |
|||
##################################### |
################################################## |
||
# SEE https://wiki.freecadweb.org/Macro_Unfold_Box |
# SEE https://wiki.freecadweb.org/Macro_Unfold_Box |
||
# *************************************************************************** |
# *************************************************************************** |
||
# * * |
# * * |
||
# * Copyright (c) 2013 - DoNovae/Herve BAILLY <hbl13@donovae.com> * |
# * Copyright (c) 2013 - DoNovae/Herve BAILLY <hbl13@donovae.com> * |
||
# * Copyright (c) 2022 - heda <heda@fc-forum> * |
|||
# * * |
# * * |
||
# * This program is free software; you can redistribute it and/or modify * |
# * This program is free software; you can redistribute it and/or modify * |
||
Line 77: | Line 94: | ||
# *************************************************************************** |
# *************************************************************************** |
||
__Name__ = 'Unfold Box' |
|||
import os |
|||
__Comment__ = 'Unfolds planar surfaces and draws them on a page.' |
|||
import math |
|||
__Author__ = 'Hervé B., heda' |
|||
__Version__ = '1.1' |
|||
__Date__ = '2022-07-28' |
|||
__License__ = 'LGPL-2.0-or-later' |
|||
__Web__ = 'https://wiki.freecad.org/Macro_Unfold_Box' |
|||
__Wiki__ = 'https://wiki.freecad.org/Macro_Unfold_Box' |
|||
__Icon__ = '' |
|||
__Help__ = ('Select surfaces, Explode them (cf Draft menu Downgrade), ' |
|||
'Select the exploded surfaces, Execute the macro') |
|||
__Status__ = '' |
|||
__Requires__ = '' |
|||
__Communication__ = '' |
|||
__Files__ = '' |
|||
__doc__ = """ |
|||
select a face, or several and run the macro. |
|||
a shell/solid needs to be draft/downgraded to get the faces as separate objects |
|||
the macro is intended to unfold a set of planar faces, |
|||
in current state, most of the times it does not place the faces correctly. |
|||
thus one needs to do the final placement of the clones manually, with Draft/Move & Rotate |
|||
regardless, the macro saves a lot of clicks compared to a fully manual unfold |
|||
settings are not context aware, all settings not applicable are ignored. |
|||
as example, using autoscaling ignores the scale-value in the form |
|||
sew is always enabled, thus the drawing |
|||
is always the sewed shape on a single page |
|||
v1.1 (2022-07-28) py3/qt5 compat, cosmetic code changes, |
|||
minor code tweaks for evolved fc-api |
|||
added option to skip drawing, made layout engine with techdraw, |
|||
the drawing wb layout engine is now called "legacy" |
|||
v1.0.1 (2020-03-10) - on wiki |
|||
v1.0 (2013-09-14) - on wiki |
|||
note: |
|||
- unfolding occasionally work as expected, but mostly not |
|||
- anyone is free to improve functionality |
|||
""" |
|||
import os, math |
|||
import FreeCAD, FreeCADGui, Draft |
|||
from PySide import QtGui, QtCore |
from PySide import QtGui, QtCore |
||
from FreeCAD import Base |
|||
import FreeCAD, FreeCADGui |
|||
import Draft |
|||
Vector = FreeCAD.Base.Vector |
|||
Units = FreeCAD.Units |
|||
PrintMessage = FreeCAD.Console.PrintMessage |
|||
PrintError = FreeCAD.Console.PrintError |
|||
fields_l = [] |
fields_l = [] |
||
unroll_l = [] |
unroll_l = [] |
||
dwgtpllegacy = 'Mod/Drawing/Templates' |
|||
dwgtpl = 'Mod/TechDraw/Templates' |
|||
##################################### |
##################################### |
||
# Functions |
### Functions |
||
##################################### |
##################################### |
||
def errorDialog(msg): |
def errorDialog(msg): |
||
diag = QtGui.QMessageBox(QtGui.QMessageBox.Critical, |
diag = QtGui.QMessageBox(QtGui.QMessageBox.Critical, 'Error Message', msg) |
||
diag.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) |
diag.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) |
||
diag.exec_() |
diag.exec_() |
||
Line 98: | Line 169: | ||
def proceed(): |
def proceed(): |
||
QtGui. |
QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) |
||
PrintMessage('===========================================\n') |
|||
PrintMessage('unfoldBox: start.\n') |
|||
try: |
try: |
||
file_name = fields_l[0].text() |
file_name = fields_l[0].text() |
||
makedwg = makedwg_check.isChecked() |
|||
leglay = leglay_check.isChecked() |
|||
scale = float(fields_l[1].text()) |
scale = float(fields_l[1].text()) |
||
scale_auto = scale_check.isChecked() |
scale_auto = scale_check.isChecked() |
||
Line 110: | Line 183: | ||
onedrawing = onedrawing_check.isChecked() |
onedrawing = onedrawing_check.isChecked() |
||
sewed = sewed_check.isChecked() |
sewed = sewed_check.isChecked() |
||
PrintMessage('unfoldBox.file_name: {}\n'.format(file_name)) |
|||
PrintMessage('unfoldBox.makedwg: {}\n'.format(makedwg)) |
|||
PrintMessage('unfoldBox.leglay: {}\n'.format(leglay)) |
|||
PrintMessage('unfoldBox.scale: {}\n'.format(scale)) |
|||
PrintMessage('unfoldBox.scale_check: {}\n'.format(scale_auto)) |
|||
PrintMessage('unfoldBox.a3_check: {}\n'.format(a3)) |
|||
PrintMessage('unfoldBox.cartridge: {}\n'.format(cartridge)) |
|||
PrintMessage('unfoldBox.onedrawing: {}\n'.format(onedrawing)) |
|||
PrintMessage('unfoldBox.sewed: {}\n'.format(sewed)) |
|||
except: |
except: |
||
msg = 'unfoldBox: wrong inputs...\n' |
msg = 'unfoldBox: wrong inputs...\n' |
||
PrintError(msg) |
|||
errorDialog(msg) |
errorDialog(msg) |
||
QtGui. |
QtGui.QApplication.restoreOverrideCursor() |
||
DialogBox.hide() |
DialogBox.hide() |
||
# |
|||
# Get selection |
## Get selection |
||
# |
|||
sel = FreeCADGui.Selection.getSelection() |
sel = FreeCADGui.Selection.getSelection() |
||
if not sel or len(sel) < 2: |
|||
PrintMessage('unfoldBox: requires at least 2 selected faces, ending.\n') |
|||
return |
|||
doc = FreeCAD.ActiveDocument |
|||
objnames_l=[] |
objnames_l=[] |
||
grp = |
grp = doc.addObject('App::DocumentObjectGroup', str(file_name)) |
||
for objid in range( |
for objid in range(len(sel)): |
||
obj = Draft. |
obj = Draft.make_clone(sel[objid]) |
||
grp.addObject(obj) |
grp.addObject(obj) |
||
objnames_l.append([ obj, sel[objid].Name ]) |
objnames_l.append([ obj, sel[objid].Name ]) |
||
print('xxx', obj, obj.Placement) |
|||
doc.recompute() |
|||
unfold = unfoldBox(doc) |
|||
if sewed : |
|||
if sewed: |
|||
objnames_l = unfold.done(objnames_l) |
objnames_l = unfold.done(objnames_l) |
||
grp.addObject(objnames_l[0][0]) |
grp.addObject(objnames_l[0][0]) |
||
else: |
else: |
||
for objid in range( |
for objid in range(len(objnames_l)): |
||
unfold.moveXY(objnames_l[objid][0]) |
unfold.moveXY(objnames_l[objid][0]) |
||
if not makedwg: |
|||
return |
|||
while objnames_l.__len__() > 0: |
|||
draw = Drawing2d(scale, scale_auto, a3, cartridge, onedrawing, FreeCAD.activeDocument().Name, 'Page'+str(id_)) |
|||
objnames_l = draw.all_(objnames_l) |
|||
id_ = id_+1 |
|||
FreeCAD.Console.PrintMessage('unfoldBox: obj_l= '+str(objnames_l.__len__())+'\n') |
|||
if leglay: |
|||
FreeCAD.Console.PrintMessage('unfoldBox: end.\n') |
|||
idx = 0 |
|||
FreeCAD.Console.PrintMessage('===========================================\n') |
|||
while len(objnames_l) > 0: |
|||
draw = Drawing2dLegacy(scale, scale_auto, a3, |
|||
cartridge, onedrawing, |
|||
doc.Name, 'Page'+str(idx)) |
|||
objnames_l = draw.all_(objnames_l) |
|||
idx += 1 |
|||
PrintMessage('unfoldBox: obj_l= {}\n'.format(len(objnames_l))) |
|||
else: |
|||
draw = Drawing2d(scale, scale_auto, a3, cartridge) |
|||
draw.drawpage(objnames_l[0], "{}Page".format(file_name)) |
|||
PrintMessage('unfoldBox: end.\n') |
|||
PrintMessage('===========================================\n') |
|||
Line 157: | Line 248: | ||
DialogBox.hide() |
DialogBox.hide() |
||
def getType(obj): |
|||
return type(obj).__name__ |
|||
def mkmm(l): |
|||
return Units.Quantity(l, Units.Length) |
|||
class unfoldBox: |
class unfoldBox: |
||
def __init__(self): |
def __init__(self, doc): |
||
PrintMessage('unfoldBox.unfoldBox\n') |
|||
self.doc = doc |
|||
self.LIMIT = 0.0001 |
self.LIMIT = 0.0001 |
||
def done(self, objnames_l): |
def done(self, objnames_l): |
||
tree_l = self.makeTree(objnames_l) |
tree_l = self.makeTree(objnames_l) |
||
for |
for idx in range(len(objnames_l)): |
||
face = objnames_l[ |
face = objnames_l[idx] |
||
self.moveXY(face[0]) |
self.moveXY(face[0]) |
||
self.sew(objnames_l, tree_l) |
self.sew(objnames_l, tree_l) |
||
return self.fusion(objnames_l) |
return self.fusion(objnames_l) |
||
def getEndPoints(self, edge): |
|||
return [v.Point for v in edge.Vertexes] |
|||
def makeTree(self, objnames_l): |
def makeTree(self, objnames_l): |
||
# Initialisation of tree_l. |
## Initialisation of tree_l. |
||
tree_l = [] |
tree_l = [] |
||
for k in range( |
for k in range(len(objnames_l)): |
||
facek = objnames_l[k][0] |
facek = objnames_l[k][0] |
||
facekEdges = facek.Shape.Edges |
|||
facek_l = [] |
facek_l = [] |
||
for i in range( |
for i in range(len(facekEdges)): |
||
if False and |
if False and getType(facekEdges[i].Curve) != 'GeomLineSegment': |
||
## this is a no-op... |
|||
facek_l.append([-1, -1]) |
facek_l.append([-1, -1]) |
||
else: |
else: |
||
# Search face link to the ith edge |
## Search face link to the ith edge |
||
vki0 = |
#vki0 = facekEdges[i].Curve.StartPoint |
||
vki1 = |
#vki1 = facekEdges[i].Curve.EndPoint |
||
vki0, vki1 = self.getEndPoints(facekEdges[i]) |
|||
found = False |
found = False |
||
for l in range(k+1, |
for l in range(k+1, len(objnames_l)): |
||
facel = objnames_l[l][0] |
facel = objnames_l[l][0] |
||
facelEdges = facel.Shape.Edges |
|||
for j in range(len(facelEdges)): |
|||
#vlj0 = facelEdges[j].Curve.StartPoint |
|||
#vlj1 = facelEdges[j].Curve.EndPoint |
|||
vlj0, vlj1 = self.getEndPoints(facelEdges[j]) |
|||
if (vki0.isEqual(vlj0, self.LIMIT) |
|||
and vki1.isEqual(vlj1, self.LIMIT)): |
|||
arelinked = False |
arelinked = False |
||
isfacek = False |
isfacek = isfacel = False |
||
isfacel = False |
|||
for kk in range(k-1): |
for kk in range(k-1): |
||
for ii in range(tree_l[kk] |
for ii in range(len(tree_l[kk])): |
||
isfacek = tree_l[kk][ii][0] == k |
|||
isfacel = tree_l[kk][ii][0] == l |
|||
if tree_l[kk][ii][0] == l: |
|||
isfacel = True |
|||
if isfacek and isfacel: |
if isfacek and isfacel: |
||
arelinked = True |
arelinked = True |
||
Line 216: | Line 320: | ||
def sew(self, objnames_l, tree_l): |
def sew(self, objnames_l, tree_l): |
||
placed_l = [] |
placed_l = [] |
||
for k in range( |
for k in range(len(tree_l)): |
||
iskplaced = False |
iskplaced = False |
||
for p in range( |
for p in range(len(placed_l)): |
||
iskplaced = placed_l[p] == k |
|||
iskplaced = True |
|||
if not iskplaced: |
if not iskplaced: |
||
placed_l.append(k) |
placed_l.append(k) |
||
facek = tree_l[k] |
facek = tree_l[k] |
||
objk = objnames_l[k][0] |
objk = objnames_l[k][0] |
||
for i in range( |
for i in range(len(facek)): |
||
edgeki = facek[i] |
edgeki = facek[i] |
||
l = edgeki[ |
l, j = edgeki[:2] |
||
j = edgeki[1] |
|||
islplaced = False |
islplaced = False |
||
for p in range( |
for p in range(len(placed_l)): |
||
if placed_l[p] == l: |
if placed_l[p] == l: |
||
islplaced = True |
islplaced = True |
||
Line 238: | Line 340: | ||
if l >= 0 and not (islplaced and iskplaced): |
if l >= 0 and not (islplaced and iskplaced): |
||
iskplaced = True |
iskplaced = True |
||
# Move facel.edgelj to facek.edgeki. |
## Move facel.edgelj to facek.edgeki. |
||
objl = objnames_l[l][0] |
objl = objnames_l[l][0] |
||
vki0 = objk.Shape.Edges[i].Curve.StartPoint |
#vki0 = objk.Shape.Edges[i].Curve.StartPoint |
||
vki1 = objk.Shape.Edges[i].Curve.EndPoint |
#vki1 = objk.Shape.Edges[i].Curve.EndPoint |
||
vki0, vki1 = self.getEndPoints(objk.Shape.Edges[i]) |
|||
#vlj0 = objl.Shape.Edges[j].Curve.StartPoint |
|||
#vlj1 = objl.Shape.Edges[j].Curve.EndPoint |
|||
vlj0, vlj1 = self.getEndPoints(objk.Shape.Edges[j]) |
|||
vk = vki1.sub(vki0) |
vk = vki1.sub(vki0) |
||
vl = vlj1.sub(vlj0) |
vl = vlj1.sub(vlj0) |
||
alpk = vk.getAngle(vl)*180/math.pi |
alpk = vk.getAngle(vl) * 180 / math.pi |
||
alpl = vl.getAngle(vk)*180/math.pi |
alpl = vl.getAngle(vk) * 180 / math.pi |
||
self.isPlanZ(objk) |
self.isPlanZ(objk) |
||
if islplaced: |
if islplaced: |
||
Line 255: | Line 359: | ||
self.isPlanZ(objk) |
self.isPlanZ(objk) |
||
if math.fabs(vk.dot( |
if math.fabs(vk.dot(Vector(-vl.y, vl.x, 0))) > self.LIMIT: |
||
if islplaced: |
if islplaced: |
||
Draft.rotate(objk, -alpl, vlj0, self.vecto(vl, vk)) |
Draft.rotate(objk, -alpl, vlj0, self.vecto(vl, vk)) |
||
Line 262: | Line 366: | ||
elif vk.dot(vl) < 0: |
elif vk.dot(vl) < 0: |
||
if islplaced: |
if islplaced: |
||
Draft.rotate(objk, 180, vlj0, self.vecto(vl, |
Draft.rotate(objk, 180, vlj0, self.vecto(vl, Vector(-vl.y, vl.x, 0))) |
||
else: |
else: |
||
Draft.rotate(objl, 180, vki0, self.vecto(vk, |
Draft.rotate(objl, 180, vki0, self.vecto(vk, Vector(-vk.y, vk.x, 0))) |
||
# Verifications. |
## Verifications. |
||
vki0 = objk.Shape.Edges[i].Curve.StartPoint |
#vki0 = objk.Shape.Edges[i].Curve.StartPoint |
||
vki1 = objk.Shape.Edges[i].Curve.EndPoint |
#vki1 = objk.Shape.Edges[i].Curve.EndPoint |
||
vki0, vki1 = self.getEndPoints(objk.Shape.Edges[i]) |
|||
#vlj0 = objl.Shape.Edges[j].Curve.StartPoint |
|||
#vlj1 = objl.Shape.Edges[j].Curve.EndPoint |
|||
vli0, vli1 = self.getEndPoints(objk.Shape.Edges[j]) |
|||
vk = vki1.sub(vki0) |
vk = vki1.sub(vki0) |
||
vl = vlj1.sub(vlj0) |
vl = vlj1.sub(vlj0) |
||
self.isPlanZ(objk) |
self.isPlanZ(objk) |
||
# Flip or not. |
## Flip or not. |
||
bbl, bbk = objl.Shape.BoundBox, objk.Shape.BoundBox |
|||
L = max(bbl.XMax, bbk.XMax) - min(bbl.XMin, bbk.XMin) |
|||
W = max(bbl.YMax, bbk.YMax) - min(bbl.YMin, bbk.YMin) |
|||
S1 = L * W |
|||
if islplaced: |
if islplaced: |
||
Draft.rotate(objk, 180, vlj0, vl) |
Draft.rotate(objk, 180, vlj0, vl) |
||
else: |
else: |
||
Draft.rotate(objl, 180, vki0, vk) |
Draft.rotate(objl, 180, vki0, vk) |
||
bbl, bbk = objl.Shape.BoundBox, objk.Shape.BoundBox |
|||
L = max(bbl.XMax, bbk.XMax) - min(bbl.XMin, bbk.XMin) |
|||
W = max(bbl.YMax, bbk.YMax) - min(bbl.YMin, bbk.YMin) |
|||
S2 = L * W |
S2 = L * W |
||
if |
if S2 <= S1: |
||
if islplaced: |
if islplaced: |
||
Draft.rotate(objk, 180, vlj0, vl) |
Draft.rotate(objk, 180, vlj0, vl) |
||
Line 293: | Line 401: | ||
def isPlanZ(self, obj): |
def isPlanZ(self, obj): |
||
bb = obj.Shape.BoundBox |
|||
L = bb.XMax - bb.XMin |
|||
W = bb.YMax - bb.YMin |
|||
H = bb.ZMax - bb.ZMin |
|||
return H < self.LIMIT |
|||
else: |
|||
return False |
|||
def fusion(self, objnames_l): |
def fusion(self, objnames_l): |
||
# Init. |
## Init. |
||
obj_l=[] |
obj_l, objna_l =[], [] |
||
obj0, name = objnames_l[0] |
|||
objfuse = self.doc.addObject('Part::MultiFuse', 'Unfolding') |
|||
obj0 = objnames_l[0][0];name=objnames_l[0][1] |
|||
for k in range(len(objnames_l)): |
|||
objfuse = FreeCAD.activeDocument().addObject('Part::MultiFuse','Unfolding') |
|||
for k in range(objnames_l.__len__()): |
|||
objk = objnames_l[k][0] |
objk = objnames_l[k][0] |
||
obj_l.append(objk) |
obj_l.append(objk) |
||
objfuse.Shapes = obj_l |
objfuse.Shapes = obj_l |
||
self.doc.recompute() |
|||
objna_l.append([objfuse, name]) |
objna_l.append([objfuse, name]) |
||
return objna_l |
return objna_l |
||
def get2Vectors(self, shape): |
def get2Vectors(self, shape): |
||
"""not used in v1.1""" |
|||
v1 = |
v0, v1 = Vector(), Vector() |
||
edges= shape.Edges |
edges = shape.Edges |
||
for |
for idx in range(len(edges) - 1): |
||
e1, e2 = edges[idx], edges[idx + 1] |
|||
## .EndPoint errors out... |
|||
va = e1.Curve.EndPoint.sub(e1.Curve.StartPoint) |
|||
vb = e2.Curve.EndPoint.sub(e2.Curve.StartPoint) |
|||
if vb.sub(va).Length > v1.sub(v0).Length: |
if vb.sub(va).Length > v1.sub(v0).Length: |
||
v0 = self.vect_copy(va) |
v0, v1 = self.vect_copy(va), self.vect_copy(vb) |
||
return [v0, v1] |
return [v0, v1] |
||
def vecto(self, vect1, vect2): |
def vecto(self, vect1, vect2): |
||
'''Function vecto.''' |
'''Function vecto.''' |
||
v= |
v = Vector() |
||
v.x = vect1.y*vect2.z-vect1.z*vect2.y |
v.x = vect1.y * vect2.z - vect1.z * vect2.y |
||
v.y = vect1.z*vect2.x-vect1.x*vect2.z |
v.y = vect1.z * vect2.x - vect1.x * vect2.z |
||
v.z = vect1.x*vect2.y-vect1.y*vect2.x |
v.z = vect1.x * vect2.y - vect1.y * vect2.x |
||
return v |
return v |
||
def vect_copy(self, vect): |
def vect_copy(self, vect): |
||
'''Return a copy of vector.''' |
'''Return a copy of vector.''' |
||
return vect.add(Vector()) |
|||
return v |
|||
def moveXY(self, obj): |
def moveXY(self, obj): |
||
# Move to origin |
## Move to origin |
||
bb = obj.Shape.BoundBox |
|||
Draft.move(obj, Vector(-bb.XMin, -bb.YMin, -bb.ZMin)) |
|||
# Find 2 vectors defining the plan of surface |
## Find 2 vectors defining the plan of surface |
||
tab = self.get2Vectors(obj.Shape) |
#tab = self.get2Vectors(obj.Shape) |
||
v0 = tab[ |
#v0, v1 = tab[:2] |
||
#norm = self.vecto(v0, v1) |
|||
norm |
#norm.normalize() |
||
## above gives null vector, and errors out... |
|||
## probably sprung out of some api-change over time |
|||
## probably part.line vs part.linesegment... |
|||
## a part.line does not have edge.Curve.StartPoint, or .EndPoint any more |
|||
## the semantics is to get first & second point from a line, |
|||
## so edge.Curve.value(edge.Curve.FirstParameter) should get the sought values |
|||
## however easier to just use edge.Vertexes... |
|||
## which appears to have same orientation |
|||
norm = obj.Shape.findPlane().Axis ## works for planar surfaces |
|||
#norm = obj.Shape.Surface.Axis ## gives worse results... |
|||
norm.normalize() |
norm.normalize() |
||
#print(obj, obj.Shape, obj.Shape.findPlane(), norm, norm.normalize()) |
|||
# Rotate. |
## Rotate. |
||
nx, ny, nz = (math.fabs(xyz) for xyz in norm) |
|||
if nx < self.LIMIT and nz < self.LIMIT: |
|||
Draft.rotate(obj, 90, FreeCAD.Base.Vector(0, 0, 0), FreeCAD.Base.Vector(1, 0, 0)) |
|||
Draft.rotate(obj, 90, Vector(0, 0, 0), Vector(1, 0, 0)) |
|||
elif math.fabs(norm.y) < self.LIMIT and math.fabs(norm.z) < self.LIMIT: |
|||
elif ny < self.LIMIT and nz < self.LIMIT: |
|||
Draft.rotate(obj, 90, FreeCAD.Base.Vector(0, 0, 0), FreeCAD.Base.Vector(0, 1, 0)) |
|||
Draft.rotate(obj, 90, Vector(0, 0, 0), Vector(0, 1, 0)) |
|||
else: |
else: |
||
# Rotate following the angle to the normal direction of the plan. |
## Rotate following the angle to the normal direction of the plan. |
||
oz= |
oz = Vector(0, 0, 1) |
||
alp = oz.getAngle(norm)*180/math.pi |
alp = oz.getAngle(norm) * 180 / math.pi |
||
print('yyy', oz, alp, self.vecto(oz, norm)) |
|||
vecto = self.vecto(oz, norm) |
|||
rotv = oz if vecto.isEqual(Vector(), self.LIMIT) else self.vecto(oz, norm) |
|||
#rotv = norm if vecto.isEqual(Vector(), self.LIMIT) else self.vecto(oz, norm) |
|||
## flipping here seems to give worse results as well... |
|||
Draft.rotate(obj, -alp, Vector(0, 0, 0), rotv) |
|||
# Move to z = 0. |
## Move to z = 0. |
||
Draft.move(obj, |
Draft.move(obj, Vector(0, 0, -obj.Shape.BoundBox.ZMin)) |
||
class Scale: |
|||
"""keeps autoscaling to integers""" |
|||
def __init__(self, scale): |
|||
self.scale = scale if scale >= 1 else 1 / scale |
|||
self.scale = int(self.scale) |
|||
self.inverted = scale >= 1 |
|||
def get(self): |
|||
if self.inverted: |
|||
return self.scale, '{}:1'.format(self.scale) |
|||
else: |
|||
return 1/self.scale, '1:{}'.format(self.scale) |
|||
class Drawing2d: |
class Drawing2d: |
||
def __init__(self, scale, scale_auto, a3, cartridge |
def __init__(self, scale, scale_auto, a3, cartridge): |
||
"""techdraw based layout for one page only""" |
|||
self.scale = scale |
|||
self.scale_auto = scale_auto |
|||
self.a3 = a3 |
|||
self.cartridge = cartridge |
|||
if a3: |
|||
self.WH = 420, 297 |
|||
else: |
|||
self.WH = 297, 210 |
|||
self.doc = FreeCAD.ActiveDocument |
|||
def newPage(self, page_name): |
|||
freecad_dir = os.path.join(FreeCAD.getResourceDir(), dwgtpl) |
|||
page = self.doc.addObject('TechDraw::DrawPage', page_name) |
|||
template = self.doc.addObject('TechDraw::DrawSVGTemplate', 'Template') |
|||
size = 'A3' if self.a3 else 'A4' |
|||
frame = 'TD' if self.cartridge else '_blank' |
|||
template.Template = freecad_dir + '/{}_Landscape{}.svg'.format(size, frame) |
|||
page.Template = template |
|||
return page |
|||
def drawpage(self, objname, page_name): |
|||
page = self.newPage(page_name) |
|||
faceset, name = objname |
|||
bb = faceset.Shape.BoundBox |
|||
## bb does not auto-update, have to pick up new bb after manipulation |
|||
if bb.YLength > bb.XLength: ## auto rotate |
|||
Draft.rotate(faceset, 90) |
|||
bb = faceset.Shape.BoundBox |
|||
Draft.move(faceset, Vector(-bb.XMin, -bb.YMin, 0)) |
|||
bb = faceset.Shape.BoundBox |
|||
W, H = self.WH |
|||
xr, yr = W / bb.XLength, H / bb.YLength |
|||
adjust = 0.7 if self.cartridge else 0.85 |
|||
scale = min(xr, yr) * adjust if self.scale_auto else self.scale |
|||
scale, scr = Scale(scale).get() |
|||
bb.scale(scale, scale, 1) ## faceset in xy-plane |
|||
TopView = self.doc.addObject('TechDraw::DrawViewPart', 'TopView') |
|||
page.addView(TopView) |
|||
TopView.Source = faceset |
|||
TopView.Direction = (0, 0, 1) |
|||
TopView.XDirection = (1, 0, 0) |
|||
TopView.Scale = scale |
|||
Text = self.doc.addObject('TechDraw::DrawViewAnnotation', name) |
|||
page.addView(Text) |
|||
Text.Text = name |
|||
Text.recompute() # for size |
|||
bb.scale(scale, scale, scale) |
|||
yt = (H - bb.YLength) / 2 - Text.TextSize.Value * 1.5 |
|||
Text.Y = max(1, yt) |
|||
self.doc.recompute() |
|||
page.ViewObject.doubleClicked() |
|||
FreeCADGui.runCommand('TechDraw_ToggleFrame', 0) |
|||
class Drawing2dLegacy: |
|||
def __init__(self, scale, scale_auto, a3, cartridge, onedrawing, |
|||
drawing_name, page_name): |
|||
"""Function __init__ |
"""Function __init__ |
||
Line 376: | Line 583: | ||
- cartridge |
- cartridge |
||
- onedrawing |
- onedrawing |
||
v1.1 - renamed to legacy, functional wise untouched |
|||
""" |
""" |
||
self.TopX_H = 0 |
self.TopX_H = self.TopY_H = 0 |
||
self. |
self.TopX_V = self.TopY_V = 0 |
||
self. |
self.TopX_Hmax = self.TopY_Hmax = 0 |
||
self. |
self.TopX_Vmax = self.TopY_Vmax = 0 |
||
self.TopX_Hmax = 0 |
|||
self.TopY_Hmax = 0 |
|||
self.TopX_Vmax = 0 |
|||
self.TopY_Vmax = 0 |
|||
self.a3 = a3 |
self.a3 = a3 |
||
self.pts_nbr = 100 |
|||
self.scale = scale |
self.scale = scale |
||
self.scale_auto = scale_auto |
self.scale_auto = scale_auto |
||
self.cartridge = cartridge |
self.cartridge = cartridge |
||
self.onedrawing = onedrawing |
self.onedrawing = onedrawing |
||
self.marge = 6 |
|||
if self.a3: |
if self.a3: |
||
self.L = 420 |
self.L, self.H = 420, 297 |
||
self.H = 297 |
|||
self.marge = 6 |
|||
else: |
else: |
||
self.L = 297 |
self.L, self.H = 297, 210 |
||
self.H = 210 |
|||
self.marge = 6 |
|||
self.page_name = page_name |
self.page_name = page_name |
||
self.drawing_name = drawing_name |
self.drawing_name = drawing_name |
||
self.doc = FreeCAD.ActiveDocument |
|||
def newPage(self): |
def newPage(self): |
||
freecad_dir = os. |
freecad_dir = os.path.join(FreeCAD.getResourceDir(), dwgtpllegacy) |
||
page = |
page = self.doc.addObject('Drawing::FeaturePage', self.page_name) |
||
size = 'A3' if self.a3 else 'A4' |
|||
if self. |
frame = '' if self.cartridge else '_plain' |
||
page.Template = freecad_dir + '/{}_Landscape{}.svg'.format(size, frame) |
|||
if self.cartridge: |
|||
page.Template = freecad_dir+'/A3_Landscape.svg' |
|||
else: |
|||
page.Template = freecad_dir+'/A3_Landscape_Empty.svg' |
|||
else: |
|||
if self.cartridge: |
|||
page.Template = freecad_dir+'/A4_Landscape.svg' |
|||
else: |
|||
page.Template = freecad_dir+'/A4_Landscape_Empty.svg' |
|||
return page |
return page |
||
def all_(self, objnames_l): |
def all_(self, objnames_l): |
||
obj_l = [] |
obj_l = [] |
||
for objid in range( |
for objid in range(len(objnames_l)): |
||
if objid == 0 or not self.onedrawing: |
if objid == 0 or not self.onedrawing: |
||
self.newPage() |
self.newPage() |
||
Line 427: | Line 620: | ||
def done(self, id_, objname): |
def done(self, id_, objname): |
||
# Init. |
## Init. |
||
obj_l = [] |
obj_l = [] |
||
obj = objname |
obj, objname = objname |
||
bb = obj.Shape.BoundBox |
|||
xmax = |
xmax, ymax = bb.XMax - bb.XMin, bb.YMax - bb.YMin |
||
ymax = obj.Shape.BoundBox.YMax-obj.Shape.BoundBox.YMin |
|||
if ymax > xmax: |
if ymax > xmax: |
||
Draft.rotate(obj, 90) |
Draft.rotate(obj, 90) |
||
bb = obj.Shape.BoundBox |
|||
FreeCAD.Base.Vector( |
|||
Draft.move(obj, Vector(-bb.XMin, -bb.YMin, 0)) |
|||
bb = obj.Shape.BoundBox ## does not auto-update, have to pick up new obj |
|||
xmax = bb.XMax - bb.XMin |
|||
ymax = bb.YMax - bb.YMin |
|||
scale = min((self.L-4*self.marge) / xmax, (self.H-4*self.marge) / ymax) |
scale = min((self.L-4*self.marge) / xmax, (self.H-4*self.marge) / ymax) |
||
Line 447: | Line 640: | ||
if id_ == 0 or not self.onedrawing: |
if id_ == 0 or not self.onedrawing: |
||
# Init. |
## Init. |
||
PrintMessage('Drawing2d: init\n') |
|||
self.TopX_H = self.marge*2 |
self.TopX_H = self.TopY_H = self.marge * 2 |
||
TopX, TopY = self.TopX_H, self.TopY_H |
|||
TopX = self.TopX_H |
|||
TopY = self.TopY_H |
|||
self.TopX_H = self.TopX_H + xmax * scale + self.marge |
self.TopX_H = self.TopX_H + xmax * scale + self.marge |
||
self.TopY_H = self.TopY_H |
self.TopY_H = self.TopY_H |
||
self.TopX_Hmax = max(self.TopX_Hmax, self.TopX_H) |
self.TopX_Hmax = max(self.TopX_Hmax, self.TopX_H) |
||
self.TopY_Hmax = max(self.TopY_Hmax, |
self.TopY_Hmax = max(self.TopY_Hmax, |
||
self.TopY_H + ymax*scale + self.marge) |
|||
self.TopX_Vmax = max(self.TopX_Vmax, self.TopX_Hmax) |
self.TopX_Vmax = max(self.TopX_Vmax, self.TopX_Hmax) |
||
self.TopX_V = max(self.TopX_Vmax, self.TopX_V) |
self.TopX_V = max(self.TopX_Vmax, self.TopX_V) |
||
self.TopY_V = self.marge * 2 |
self.TopY_V = self.marge * 2 |
||
elif self.onedrawing: |
elif self.onedrawing: |
||
if self.TopX_H + xmax * scale < self.L: |
if self.TopX_H + xmax * scale < self.L: |
||
if self.TopY_H + ymax * scale + self.marge*2 < self.H: |
if self.TopY_H + ymax * scale + self.marge*2 < self.H: |
||
# H Add at right on same horizontal line. |
## H Add at right on same horizontal line. |
||
PrintMessage('Drawing2d: horizontal\n') |
|||
TopX = self.TopX_H |
TopX, TopY = self.TopX_H, self.TopY_H |
||
TopY = self.TopY_H |
|||
self.TopX_H = self.TopX_H + xmax * scale + self.marge |
self.TopX_H = self.TopX_H + xmax * scale + self.marge |
||
self.TopX_Hmax = max(self.TopX_Hmax, self.TopX_H) |
self.TopX_Hmax = max(self.TopX_Hmax, self.TopX_H) |
||
self.TopY_Hmax = max(self.TopY_Hmax, |
self.TopY_Hmax = max(self.TopY_Hmax, |
||
self.TopY_H + ymax*scale + self.marge) |
|||
self.TopX_Vmax = max(self.TopX_Hmax, self.TopX_Vmax) |
self.TopX_Vmax = max(self.TopX_Hmax, self.TopX_Vmax) |
||
self.TopX_Vmax = max(self.TopX_Vmax, self.TopX_Hmax) |
self.TopX_Vmax = max(self.TopX_Vmax, self.TopX_Hmax) |
||
self.TopX_V = max(self.TopX_Vmax, self.TopX_V) |
self.TopX_V = max(self.TopX_Vmax, self.TopX_V) |
||
else: |
else: |
||
# |
## V Add at right on same horizontal line |
||
PrintMessage('Drawing2d: vertival\n') |
|||
if (self.TopX_V + ymax * scale + 2 * self.marge < self.L |
|||
and self.TopY_V + xmax * scale + 2*self.marge < self.H): |
|||
if self.TopX_V + ymax * scale + 2 * self.marge < self.L and self.TopY_V + xmax * scale + 2*self.marge < self.H: |
|||
Draft.rotate(obj, 90) |
Draft.rotate(obj, 90) |
||
bb = obj.Shape.BoundBox |
|||
Draft.move(obj, Vector(-bb.XMin, -bb.YMin, 0)) |
|||
self.TopX_V = max(self.TopX_Vmax, self.TopX_V) |
self.TopX_V = max(self.TopX_Vmax, self.TopX_V) |
||
TopX = self.TopX_V |
TopX, TopY = self.TopX_V, self.TopY_V |
||
TopY = self.TopY_V |
|||
self.TopX_V = self.TopX_V + ymax * scale + self.marge |
self.TopX_V = self.TopX_V + ymax * scale + self.marge |
||
self.TopY_Vmax = max(self.TopY_Vmax, |
self.TopY_Vmax = max(self.TopY_Vmax, |
||
self.TopY_V + xmax * scale + self.marge) |
|||
else: |
else: |
||
obj_l.append([obj, 'name']) |
obj_l.append([obj, 'name']) |
||
return obj_l |
return obj_l |
||
else: |
else: |
||
# H Carriage return. |
## H Carriage return. |
||
if (self.TopY_Hmax + ymax * scale + self.marge*2 < self.H): |
if (self.TopY_Hmax + ymax * scale + self.marge*2 < self.H): |
||
msg = 'Drawing2d: carriage return: {} > {}\n' |
|||
PrintMessage(msg.format(self.TopY_H + ymax * scale, self.H)) |
|||
TopX = self.marge*2 |
TopX = self.marge*2 |
||
TopY = self.TopY_Hmax |
TopY = self.TopY_Hmax |
||
Line 502: | Line 696: | ||
self.TopX_V = max(self.TopX_Vmax, self.TopX_V) |
self.TopX_V = max(self.TopX_Vmax, self.TopX_V) |
||
else: |
else: |
||
# V Add at right on same horizontal line. |
## V Add at right on same horizontal line. |
||
msg = 'Drawing2d: vertical: {}, {}\n' |
|||
PrintMessage(msg.format(self.TopX_V, self.TopX_Vmax)) |
|||
if (self.TopX_V + ymax * scale + 2*self.marge < self.L |
|||
and self.TopY_V + xmax * scale + 2*self.marge < self.H): |
|||
Draft.rotate(obj, 90) |
Draft.rotate(obj, 90) |
||
bb = obj.Shape.BoundBox |
|||
Draft.move(obj, Vector(-bb.XMin, -bb.YMin, 0)) |
|||
TopY = self.TopY_V |
TopX, TopY = self.TopX_V, self.TopY_V |
||
self.TopX_V = self.TopX_V + ymax * scale + self.marge |
self.TopX_V = self.TopX_V + ymax * scale + self.marge |
||
self.TopY_Vmax = max(self.TopY_Vmax, |
self.TopY_Vmax = max(self.TopY_Vmax, |
||
self.TopY_V + xmax * scale + self.marge) |
|||
else: |
else: |
||
obj_l.append([obj, 'name']) |
obj_l.append([obj, 'name']) |
||
return obj_l |
return obj_l |
||
page = |
page = self.doc.getObject(self.page_name) |
||
## Drawing wb (untouched) |
|||
Text = FreeCAD.activeDocument().addObject('Drawing::FeatureViewAnnotation', objname + '_txt') |
|||
Text = self.doc.addObject('Drawing::FeatureViewAnnotation', objname + '_txt') |
|||
Text.Text = objname |
Text.Text = objname |
||
Text.X = TopX + xmax / 2 * scale |
Text.X = TopX + xmax / 2 * scale |
||
Text.Y = TopY + ymax / 2 * scale |
Text.Y = TopY + ymax / 2 * scale |
||
Text.Scale = |
Text.Scale = 7 if self.a3 else 5 |
||
TopView = |
TopView = self.doc.addObject('Drawing::FeatureViewPart', 'TopView') |
||
TopView.Source = obj |
TopView.Source = obj |
||
TopView.Direction = (0.0, 0.0, 1) |
TopView.Direction = (0.0, 0.0, 1) |
||
Line 533: | Line 731: | ||
page.addObject(TopView) |
page.addObject(TopView) |
||
page.addObject(Text) |
page.addObject(Text) |
||
FreeCAD.activeDocument().recompute() |
|||
self.doc.recompute() |
|||
page.ViewObject.doubleClicked() |
|||
return obj_l |
return obj_l |
||
##################################### |
##################################### |
||
# Dialog Box |
### Dialog Box |
||
##################################### |
##################################### |
||
fields = [['Group Name', 'Unfolding']] |
fields = [['Group Name', 'Unfolding']] |
||
Line 553: | Line 754: | ||
fields_l.append(QtGui.QLineEdit(fields[id_][1])) |
fields_l.append(QtGui.QLineEdit(fields[id_][1])) |
||
la.addWidget(fields_l[id_]) |
la.addWidget(fields_l[id_]) |
||
makedwg_check = QtGui.QCheckBox(DialogBox) |
|||
makedwg_check.setObjectName('checkBox') |
|||
makedwg_check.setChecked(True) |
|||
la.addWidget(QtGui.QLabel('Make drawing')) |
|||
la.addWidget(makedwg_check) |
|||
leglay_check = QtGui.QCheckBox(DialogBox) |
|||
leglay_check.setObjectName('checkBox') |
|||
leglay_check.setChecked(False) |
|||
la.addWidget(QtGui.QLabel('Legacy layout')) |
|||
la.addWidget(leglay_check) |
|||
scale_check = QtGui.QCheckBox(DialogBox) |
scale_check = QtGui.QCheckBox(DialogBox) |
||
Line 582: | Line 795: | ||
la.addWidget(QtGui.QLabel('Sewed surfaces')) |
la.addWidget(QtGui.QLabel('Sewed surfaces')) |
||
sewed_check.setChecked(True) |
sewed_check.setChecked(True) |
||
sewed_check.setEnabled(False) |
|||
la.addWidget(sewed_check) |
la.addWidget(sewed_check) |
||
Revision as of 21:44, 28 July 2022
Description |
---|
The macro allows to unfold the surfaces of a box of any shape and to draw them on a page. Macro version: 1.1 Last modified: 2022-07-28 Download: ToolBar Icon Author: Hervé B., heda |
Author |
Hervé B., heda |
Download |
ToolBar Icon |
Links |
Macros recipes How to install macros How to customize toolbars |
Macro Version |
1.1 |
Date last modified |
2022-07-28 |
FreeCAD Version(s) |
Default shortcut |
None |
See also |
None |
Description
The macro allows to unfold the surfaces of a box of any shape and to draw them on a page.
Macro_unfoldBox
Installation
Available in Add-on manager.
Cf Macro for unfolding box surfaces
Options
- Scale manual or automatic
- Page format: a3/a4, cartridge (cf FreeCAD templates)
- Group drawings in the same page as possible.
- Sew or not the edges of the pieces.
Instruction for use
- Select a box made with Part::Loft tool for example.
- Explode it (cf Draft menu) into plan pieces
- Select the surfaces
- Execute the macro
The unfolding algorithm will place the faces on the xy-plane, however it seldom does the unfolding correctly. Thus some manual post-processing is needed to get to desired result, as shown in the picture below.
Starting point is a box like the upper left picture.
- Select all faces and run the macro
- Orient to Top View
- Toggle visibilty on the created set of faces, the individual clones are to be visible, not the compound
- Use Draft/Move and Draft/Rotate to reposition the folded cloned faces (a handfull of clicks per face when snapping is used)
- The drawing updates automatically to the new positions
The finished result is shown in the lower right picture above.
Script
Macro_unfoldBox.FCMacro
# -*- coding: utf-8 -*- """ FreeCAD Macro unfoldBox. Unfolding of planar surfaces """ ################################################## # SEE https://wiki.freecadweb.org/Macro_Unfold_Box # *************************************************************************** # * * # * Copyright (c) 2013 - DoNovae/Herve BAILLY <hbl13@donovae.com> * # * Copyright (c) 2022 - heda <heda@fc-forum> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** __Name__ = 'Unfold Box' __Comment__ = 'Unfolds planar surfaces and draws them on a page.' __Author__ = 'Hervé B., heda' __Version__ = '1.1' __Date__ = '2022-07-28' __License__ = 'LGPL-2.0-or-later' __Web__ = 'https://wiki.freecad.org/Macro_Unfold_Box' __Wiki__ = 'https://wiki.freecad.org/Macro_Unfold_Box' __Icon__ = '' __Help__ = ('Select surfaces, Explode them (cf Draft menu Downgrade), ' 'Select the exploded surfaces, Execute the macro') __Status__ = '' __Requires__ = '' __Communication__ = '' __Files__ = '' __doc__ = """ select a face, or several and run the macro. a shell/solid needs to be draft/downgraded to get the faces as separate objects the macro is intended to unfold a set of planar faces, in current state, most of the times it does not place the faces correctly. thus one needs to do the final placement of the clones manually, with Draft/Move & Rotate regardless, the macro saves a lot of clicks compared to a fully manual unfold settings are not context aware, all settings not applicable are ignored. as example, using autoscaling ignores the scale-value in the form sew is always enabled, thus the drawing is always the sewed shape on a single page v1.1 (2022-07-28) py3/qt5 compat, cosmetic code changes, minor code tweaks for evolved fc-api added option to skip drawing, made layout engine with techdraw, the drawing wb layout engine is now called "legacy" v1.0.1 (2020-03-10) - on wiki v1.0 (2013-09-14) - on wiki note: - unfolding occasionally work as expected, but mostly not - anyone is free to improve functionality """ import os, math from PySide import QtGui, QtCore import FreeCAD, FreeCADGui import Draft Vector = FreeCAD.Base.Vector Units = FreeCAD.Units PrintMessage = FreeCAD.Console.PrintMessage PrintError = FreeCAD.Console.PrintError fields_l = [] unroll_l = [] dwgtpllegacy = 'Mod/Drawing/Templates' dwgtpl = 'Mod/TechDraw/Templates' ##################################### ### Functions ##################################### def errorDialog(msg): diag = QtGui.QMessageBox(QtGui.QMessageBox.Critical, 'Error Message', msg) diag.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) diag.exec_() def proceed(): QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) PrintMessage('===========================================\n') PrintMessage('unfoldBox: start.\n') try: file_name = fields_l[0].text() makedwg = makedwg_check.isChecked() leglay = leglay_check.isChecked() scale = float(fields_l[1].text()) scale_auto = scale_check.isChecked() a3 = a3_check.isChecked() cartridge = cartridge_check.isChecked() onedrawing = onedrawing_check.isChecked() sewed = sewed_check.isChecked() PrintMessage('unfoldBox.file_name: {}\n'.format(file_name)) PrintMessage('unfoldBox.makedwg: {}\n'.format(makedwg)) PrintMessage('unfoldBox.leglay: {}\n'.format(leglay)) PrintMessage('unfoldBox.scale: {}\n'.format(scale)) PrintMessage('unfoldBox.scale_check: {}\n'.format(scale_auto)) PrintMessage('unfoldBox.a3_check: {}\n'.format(a3)) PrintMessage('unfoldBox.cartridge: {}\n'.format(cartridge)) PrintMessage('unfoldBox.onedrawing: {}\n'.format(onedrawing)) PrintMessage('unfoldBox.sewed: {}\n'.format(sewed)) except: msg = 'unfoldBox: wrong inputs...\n' PrintError(msg) errorDialog(msg) QtGui.QApplication.restoreOverrideCursor() DialogBox.hide() ## Get selection sel = FreeCADGui.Selection.getSelection() if not sel or len(sel) < 2: PrintMessage('unfoldBox: requires at least 2 selected faces, ending.\n') return doc = FreeCAD.ActiveDocument objnames_l=[] grp = doc.addObject('App::DocumentObjectGroup', str(file_name)) for objid in range(len(sel)): obj = Draft.make_clone(sel[objid]) grp.addObject(obj) objnames_l.append([ obj, sel[objid].Name ]) print('xxx', obj, obj.Placement) doc.recompute() unfold = unfoldBox(doc) if sewed: objnames_l = unfold.done(objnames_l) grp.addObject(objnames_l[0][0]) else: for objid in range(len(objnames_l)): unfold.moveXY(objnames_l[objid][0]) if not makedwg: return if leglay: idx = 0 while len(objnames_l) > 0: draw = Drawing2dLegacy(scale, scale_auto, a3, cartridge, onedrawing, doc.Name, 'Page'+str(idx)) objnames_l = draw.all_(objnames_l) idx += 1 PrintMessage('unfoldBox: obj_l= {}\n'.format(len(objnames_l))) else: draw = Drawing2d(scale, scale_auto, a3, cartridge) draw.drawpage(objnames_l[0], "{}Page".format(file_name)) PrintMessage('unfoldBox: end.\n') PrintMessage('===========================================\n') def close(): DialogBox.hide() def getType(obj): return type(obj).__name__ def mkmm(l): return Units.Quantity(l, Units.Length) class unfoldBox: def __init__(self, doc): PrintMessage('unfoldBox.unfoldBox\n') self.doc = doc self.LIMIT = 0.0001 def done(self, objnames_l): tree_l = self.makeTree(objnames_l) for idx in range(len(objnames_l)): face = objnames_l[idx] self.moveXY(face[0]) self.sew(objnames_l, tree_l) return self.fusion(objnames_l) def getEndPoints(self, edge): return [v.Point for v in edge.Vertexes] def makeTree(self, objnames_l): ## Initialisation of tree_l. tree_l = [] for k in range(len(objnames_l)): facek = objnames_l[k][0] facekEdges = facek.Shape.Edges facek_l = [] for i in range(len(facekEdges)): if False and getType(facekEdges[i].Curve) != 'GeomLineSegment': ## this is a no-op... facek_l.append([-1, -1]) else: ## Search face link to the ith edge #vki0 = facekEdges[i].Curve.StartPoint #vki1 = facekEdges[i].Curve.EndPoint vki0, vki1 = self.getEndPoints(facekEdges[i]) found = False for l in range(k+1, len(objnames_l)): facel = objnames_l[l][0] facelEdges = facel.Shape.Edges for j in range(len(facelEdges)): #vlj0 = facelEdges[j].Curve.StartPoint #vlj1 = facelEdges[j].Curve.EndPoint vlj0, vlj1 = self.getEndPoints(facelEdges[j]) if (vki0.isEqual(vlj0, self.LIMIT) and vki1.isEqual(vlj1, self.LIMIT)): arelinked = False isfacek = isfacel = False for kk in range(k-1): for ii in range(len(tree_l[kk])): isfacek = tree_l[kk][ii][0] == k isfacel = tree_l[kk][ii][0] == l if isfacek and isfacel: arelinked = True break if not arelinked: facek_l.append([l, j]) found = True break if found: break if not found: facek_l.append([-1, -1]) tree_l.append(facek_l) return tree_l def sew(self, objnames_l, tree_l): placed_l = [] for k in range(len(tree_l)): iskplaced = False for p in range(len(placed_l)): iskplaced = placed_l[p] == k if not iskplaced: placed_l.append(k) facek = tree_l[k] objk = objnames_l[k][0] for i in range(len(facek)): edgeki = facek[i] l, j = edgeki[:2] islplaced = False for p in range(len(placed_l)): if placed_l[p] == l: islplaced = True break if not islplaced: placed_l.append(l) if l >= 0 and not (islplaced and iskplaced): iskplaced = True ## Move facel.edgelj to facek.edgeki. objl = objnames_l[l][0] #vki0 = objk.Shape.Edges[i].Curve.StartPoint #vki1 = objk.Shape.Edges[i].Curve.EndPoint vki0, vki1 = self.getEndPoints(objk.Shape.Edges[i]) #vlj0 = objl.Shape.Edges[j].Curve.StartPoint #vlj1 = objl.Shape.Edges[j].Curve.EndPoint vlj0, vlj1 = self.getEndPoints(objk.Shape.Edges[j]) vk = vki1.sub(vki0) vl = vlj1.sub(vlj0) alpk = vk.getAngle(vl) * 180 / math.pi alpl = vl.getAngle(vk) * 180 / math.pi self.isPlanZ(objk) if islplaced: Draft.move(objk, vlj0.sub(vki0)) else: Draft.move(objl, vki0.sub(vlj0)) self.isPlanZ(objk) if math.fabs(vk.dot(Vector(-vl.y, vl.x, 0))) > self.LIMIT: if islplaced: Draft.rotate(objk, -alpl, vlj0, self.vecto(vl, vk)) else: Draft.rotate(objl, -alpk, vki0, self.vecto(vk, vl)) elif vk.dot(vl) < 0: if islplaced: Draft.rotate(objk, 180, vlj0, self.vecto(vl, Vector(-vl.y, vl.x, 0))) else: Draft.rotate(objl, 180, vki0, self.vecto(vk, Vector(-vk.y, vk.x, 0))) ## Verifications. #vki0 = objk.Shape.Edges[i].Curve.StartPoint #vki1 = objk.Shape.Edges[i].Curve.EndPoint vki0, vki1 = self.getEndPoints(objk.Shape.Edges[i]) #vlj0 = objl.Shape.Edges[j].Curve.StartPoint #vlj1 = objl.Shape.Edges[j].Curve.EndPoint vli0, vli1 = self.getEndPoints(objk.Shape.Edges[j]) vk = vki1.sub(vki0) vl = vlj1.sub(vlj0) self.isPlanZ(objk) ## Flip or not. bbl, bbk = objl.Shape.BoundBox, objk.Shape.BoundBox L = max(bbl.XMax, bbk.XMax) - min(bbl.XMin, bbk.XMin) W = max(bbl.YMax, bbk.YMax) - min(bbl.YMin, bbk.YMin) S1 = L * W if islplaced: Draft.rotate(objk, 180, vlj0, vl) else: Draft.rotate(objl, 180, vki0, vk) bbl, bbk = objl.Shape.BoundBox, objk.Shape.BoundBox L = max(bbl.XMax, bbk.XMax) - min(bbl.XMin, bbk.XMin) W = max(bbl.YMax, bbk.YMax) - min(bbl.YMin, bbk.YMin) S2 = L * W if S2 <= S1: if islplaced: Draft.rotate(objk, 180, vlj0, vl) else: Draft.rotate(objl, 180, vki0, vk) self.isPlanZ(objk) def isPlanZ(self, obj): bb = obj.Shape.BoundBox L = bb.XMax - bb.XMin W = bb.YMax - bb.YMin H = bb.ZMax - bb.ZMin return H < self.LIMIT def fusion(self, objnames_l): ## Init. obj_l, objna_l =[], [] obj0, name = objnames_l[0] objfuse = self.doc.addObject('Part::MultiFuse', 'Unfolding') for k in range(len(objnames_l)): objk = objnames_l[k][0] obj_l.append(objk) objfuse.Shapes = obj_l self.doc.recompute() objna_l.append([objfuse, name]) return objna_l def get2Vectors(self, shape): """not used in v1.1""" v0, v1 = Vector(), Vector() edges = shape.Edges for idx in range(len(edges) - 1): e1, e2 = edges[idx], edges[idx + 1] ## .EndPoint errors out... va = e1.Curve.EndPoint.sub(e1.Curve.StartPoint) vb = e2.Curve.EndPoint.sub(e2.Curve.StartPoint) if vb.sub(va).Length > v1.sub(v0).Length: v0, v1 = self.vect_copy(va), self.vect_copy(vb) return [v0, v1] def vecto(self, vect1, vect2): '''Function vecto.''' v = Vector() v.x = vect1.y * vect2.z - vect1.z * vect2.y v.y = vect1.z * vect2.x - vect1.x * vect2.z v.z = vect1.x * vect2.y - vect1.y * vect2.x return v def vect_copy(self, vect): '''Return a copy of vector.''' return vect.add(Vector()) def moveXY(self, obj): ## Move to origin bb = obj.Shape.BoundBox Draft.move(obj, Vector(-bb.XMin, -bb.YMin, -bb.ZMin)) ## Find 2 vectors defining the plan of surface #tab = self.get2Vectors(obj.Shape) #v0, v1 = tab[:2] #norm = self.vecto(v0, v1) #norm.normalize() ## above gives null vector, and errors out... ## probably sprung out of some api-change over time ## probably part.line vs part.linesegment... ## a part.line does not have edge.Curve.StartPoint, or .EndPoint any more ## the semantics is to get first & second point from a line, ## so edge.Curve.value(edge.Curve.FirstParameter) should get the sought values ## however easier to just use edge.Vertexes... ## which appears to have same orientation norm = obj.Shape.findPlane().Axis ## works for planar surfaces #norm = obj.Shape.Surface.Axis ## gives worse results... norm.normalize() #print(obj, obj.Shape, obj.Shape.findPlane(), norm, norm.normalize()) ## Rotate. nx, ny, nz = (math.fabs(xyz) for xyz in norm) if nx < self.LIMIT and nz < self.LIMIT: Draft.rotate(obj, 90, Vector(0, 0, 0), Vector(1, 0, 0)) elif ny < self.LIMIT and nz < self.LIMIT: Draft.rotate(obj, 90, Vector(0, 0, 0), Vector(0, 1, 0)) else: ## Rotate following the angle to the normal direction of the plan. oz = Vector(0, 0, 1) alp = oz.getAngle(norm) * 180 / math.pi print('yyy', oz, alp, self.vecto(oz, norm)) vecto = self.vecto(oz, norm) rotv = oz if vecto.isEqual(Vector(), self.LIMIT) else self.vecto(oz, norm) #rotv = norm if vecto.isEqual(Vector(), self.LIMIT) else self.vecto(oz, norm) ## flipping here seems to give worse results as well... Draft.rotate(obj, -alp, Vector(0, 0, 0), rotv) ## Move to z = 0. Draft.move(obj, Vector(0, 0, -obj.Shape.BoundBox.ZMin)) class Scale: """keeps autoscaling to integers""" def __init__(self, scale): self.scale = scale if scale >= 1 else 1 / scale self.scale = int(self.scale) self.inverted = scale >= 1 def get(self): if self.inverted: return self.scale, '{}:1'.format(self.scale) else: return 1/self.scale, '1:{}'.format(self.scale) class Drawing2d: def __init__(self, scale, scale_auto, a3, cartridge): """techdraw based layout for one page only""" self.scale = scale self.scale_auto = scale_auto self.a3 = a3 self.cartridge = cartridge if a3: self.WH = 420, 297 else: self.WH = 297, 210 self.doc = FreeCAD.ActiveDocument def newPage(self, page_name): freecad_dir = os.path.join(FreeCAD.getResourceDir(), dwgtpl) page = self.doc.addObject('TechDraw::DrawPage', page_name) template = self.doc.addObject('TechDraw::DrawSVGTemplate', 'Template') size = 'A3' if self.a3 else 'A4' frame = 'TD' if self.cartridge else '_blank' template.Template = freecad_dir + '/{}_Landscape{}.svg'.format(size, frame) page.Template = template return page def drawpage(self, objname, page_name): page = self.newPage(page_name) faceset, name = objname bb = faceset.Shape.BoundBox ## bb does not auto-update, have to pick up new bb after manipulation if bb.YLength > bb.XLength: ## auto rotate Draft.rotate(faceset, 90) bb = faceset.Shape.BoundBox Draft.move(faceset, Vector(-bb.XMin, -bb.YMin, 0)) bb = faceset.Shape.BoundBox W, H = self.WH xr, yr = W / bb.XLength, H / bb.YLength adjust = 0.7 if self.cartridge else 0.85 scale = min(xr, yr) * adjust if self.scale_auto else self.scale scale, scr = Scale(scale).get() bb.scale(scale, scale, 1) ## faceset in xy-plane TopView = self.doc.addObject('TechDraw::DrawViewPart', 'TopView') page.addView(TopView) TopView.Source = faceset TopView.Direction = (0, 0, 1) TopView.XDirection = (1, 0, 0) TopView.Scale = scale Text = self.doc.addObject('TechDraw::DrawViewAnnotation', name) page.addView(Text) Text.Text = name Text.recompute() # for size bb.scale(scale, scale, scale) yt = (H - bb.YLength) / 2 - Text.TextSize.Value * 1.5 Text.Y = max(1, yt) self.doc.recompute() page.ViewObject.doubleClicked() FreeCADGui.runCommand('TechDraw_ToggleFrame', 0) class Drawing2dLegacy: def __init__(self, scale, scale_auto, a3, cartridge, onedrawing, drawing_name, page_name): """Function __init__ - scale - scale_auto - a3 - cartridge - onedrawing v1.1 - renamed to legacy, functional wise untouched """ self.TopX_H = self.TopY_H = 0 self.TopX_V = self.TopY_V = 0 self.TopX_Hmax = self.TopY_Hmax = 0 self.TopX_Vmax = self.TopY_Vmax = 0 self.a3 = a3 self.scale = scale self.scale_auto = scale_auto self.cartridge = cartridge self.onedrawing = onedrawing self.marge = 6 if self.a3: self.L, self.H = 420, 297 else: self.L, self.H = 297, 210 self.page_name = page_name self.drawing_name = drawing_name self.doc = FreeCAD.ActiveDocument def newPage(self): freecad_dir = os.path.join(FreeCAD.getResourceDir(), dwgtpllegacy) page = self.doc.addObject('Drawing::FeaturePage', self.page_name) size = 'A3' if self.a3 else 'A4' frame = '' if self.cartridge else '_plain' page.Template = freecad_dir + '/{}_Landscape{}.svg'.format(size, frame) return page def all_(self, objnames_l): obj_l = [] for objid in range(len(objnames_l)): if objid == 0 or not self.onedrawing: self.newPage() obj_l.extend(self.done(objid, objnames_l[objid])) return obj_l def done(self, id_, objname): ## Init. obj_l = [] obj, objname = objname bb = obj.Shape.BoundBox xmax, ymax = bb.XMax - bb.XMin, bb.YMax - bb.YMin if ymax > xmax: Draft.rotate(obj, 90) bb = obj.Shape.BoundBox Draft.move(obj, Vector(-bb.XMin, -bb.YMin, 0)) bb = obj.Shape.BoundBox ## does not auto-update, have to pick up new obj xmax = bb.XMax - bb.XMin ymax = bb.YMax - bb.YMin scale = min((self.L-4*self.marge) / xmax, (self.H-4*self.marge) / ymax) if (not self.scale_auto) or (self.onedrawing): scale = self.scale if id_ == 0 or not self.onedrawing: ## Init. PrintMessage('Drawing2d: init\n') self.TopX_H = self.TopY_H = self.marge * 2 TopX, TopY = self.TopX_H, self.TopY_H self.TopX_H = self.TopX_H + xmax * scale + self.marge self.TopY_H = self.TopY_H self.TopX_Hmax = max(self.TopX_Hmax, self.TopX_H) self.TopY_Hmax = max(self.TopY_Hmax, self.TopY_H + ymax*scale + self.marge) self.TopX_Vmax = max(self.TopX_Vmax, self.TopX_Hmax) self.TopX_V = max(self.TopX_Vmax, self.TopX_V) self.TopY_V = self.marge * 2 elif self.onedrawing: if self.TopX_H + xmax * scale < self.L: if self.TopY_H + ymax * scale + self.marge*2 < self.H: ## H Add at right on same horizontal line. PrintMessage('Drawing2d: horizontal\n') TopX, TopY = self.TopX_H, self.TopY_H self.TopX_H = self.TopX_H + xmax * scale + self.marge self.TopX_Hmax = max(self.TopX_Hmax, self.TopX_H) self.TopY_Hmax = max(self.TopY_Hmax, self.TopY_H + ymax*scale + self.marge) self.TopX_Vmax = max(self.TopX_Hmax, self.TopX_Vmax) self.TopX_Vmax = max(self.TopX_Vmax, self.TopX_Hmax) self.TopX_V = max(self.TopX_Vmax, self.TopX_V) else: ## V Add at right on same horizontal line PrintMessage('Drawing2d: vertival\n') if (self.TopX_V + ymax * scale + 2 * self.marge < self.L and self.TopY_V + xmax * scale + 2*self.marge < self.H): Draft.rotate(obj, 90) bb = obj.Shape.BoundBox Draft.move(obj, Vector(-bb.XMin, -bb.YMin, 0)) self.TopX_V = max(self.TopX_Vmax, self.TopX_V) TopX, TopY = self.TopX_V, self.TopY_V self.TopX_V = self.TopX_V + ymax * scale + self.marge self.TopY_Vmax = max(self.TopY_Vmax, self.TopY_V + xmax * scale + self.marge) else: obj_l.append([obj, 'name']) return obj_l else: ## H Carriage return. if (self.TopY_Hmax + ymax * scale + self.marge*2 < self.H): msg = 'Drawing2d: carriage return: {} > {}\n' PrintMessage(msg.format(self.TopY_H + ymax * scale, self.H)) TopX = self.marge*2 TopY = self.TopY_Hmax self.TopX_H = TopX + xmax * scale + self.marge self.TopY_H = TopY self.TopX_Hmax = max(self.TopX_Hmax, self.TopX_H) self.TopY_Hmax = self.TopY_Hmax + ymax*scale+self.marge self.TopX_Vmax = max(self.TopX_Vmax, self.TopX_Hmax) self.TopX_V = max(self.TopX_Vmax, self.TopX_V) else: ## V Add at right on same horizontal line. msg = 'Drawing2d: vertical: {}, {}\n' PrintMessage(msg.format(self.TopX_V, self.TopX_Vmax)) if (self.TopX_V + ymax * scale + 2*self.marge < self.L and self.TopY_V + xmax * scale + 2*self.marge < self.H): Draft.rotate(obj, 90) bb = obj.Shape.BoundBox Draft.move(obj, Vector(-bb.XMin, -bb.YMin, 0)) TopX, TopY = self.TopX_V, self.TopY_V self.TopX_V = self.TopX_V + ymax * scale + self.marge self.TopY_Vmax = max(self.TopY_Vmax, self.TopY_V + xmax * scale + self.marge) else: obj_l.append([obj, 'name']) return obj_l page = self.doc.getObject(self.page_name) ## Drawing wb (untouched) Text = self.doc.addObject('Drawing::FeatureViewAnnotation', objname + '_txt') Text.Text = objname Text.X = TopX + xmax / 2 * scale Text.Y = TopY + ymax / 2 * scale Text.Scale = 7 if self.a3 else 5 TopView = self.doc.addObject('Drawing::FeatureViewPart', 'TopView') TopView.Source = obj TopView.Direction = (0.0, 0.0, 1) TopView.Rotation = 0 TopView.X = TopX TopView.Y = TopY TopView.ShowHiddenLines = True TopView.Scale = scale page.addObject(TopView) page.addObject(Text) self.doc.recompute() page.ViewObject.doubleClicked() return obj_l ##################################### ### Dialog Box ##################################### fields = [['Group Name', 'Unfolding']] fields.append(['Scale', '1']) DialogBox = QtGui.QDialog() DialogBox.resize(250, 250) DialogBox.setWindowTitle('unfoldBox') la = QtGui.QVBoxLayout(DialogBox) # Input fields. for id_ in range(len(fields)): la.addWidget(QtGui.QLabel(fields[id_][0])) fields_l.append(QtGui.QLineEdit(fields[id_][1])) la.addWidget(fields_l[id_]) makedwg_check = QtGui.QCheckBox(DialogBox) makedwg_check.setObjectName('checkBox') makedwg_check.setChecked(True) la.addWidget(QtGui.QLabel('Make drawing')) la.addWidget(makedwg_check) leglay_check = QtGui.QCheckBox(DialogBox) leglay_check.setObjectName('checkBox') leglay_check.setChecked(False) la.addWidget(QtGui.QLabel('Legacy layout')) la.addWidget(leglay_check) scale_check = QtGui.QCheckBox(DialogBox) scale_check.setObjectName('checkBox') scale_check.setChecked(True) la.addWidget(QtGui.QLabel('Scale auto')) la.addWidget(scale_check) a3_check = QtGui.QCheckBox(DialogBox) a3_check.setObjectName('checkBox') la.addWidget(QtGui.QLabel('A3 Format')) a3_check.setChecked(False) la.addWidget(a3_check) cartridge_check = QtGui.QCheckBox(DialogBox) cartridge_check.setObjectName('checkBox') la.addWidget(QtGui.QLabel('Cartridge')) cartridge_check.setChecked(False) la.addWidget(cartridge_check) onedrawing_check = QtGui.QCheckBox(DialogBox) onedrawing_check.setObjectName('checkBox') la.addWidget(QtGui.QLabel('Group drawings in page')) onedrawing_check.setChecked(True) la.addWidget(onedrawing_check) sewed_check = QtGui.QCheckBox(DialogBox) sewed_check.setObjectName('checkBox') la.addWidget(QtGui.QLabel('Sewed surfaces')) sewed_check.setChecked(True) sewed_check.setEnabled(False) la.addWidget(sewed_check) box = QtGui.QDialogButtonBox(DialogBox) box = QtGui.QDialogButtonBox(DialogBox) box.setOrientation(QtCore.Qt.Horizontal) box.setStandardButtons(QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok) la.addWidget(box) QtCore.QObject.connect(box, QtCore.SIGNAL('accepted()'), proceed) QtCore.QObject.connect(box, QtCore.SIGNAL('rejected()'), close) QtCore.QMetaObject.connectSlotsByName(DialogBox) DialogBox.show()