-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintFlow.FCMacro
More file actions
3407 lines (2800 loc) · 129 KB
/
Copy pathPrintFlow.FCMacro
File metadata and controls
3407 lines (2800 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- mode: python; eval: (auto-revert-mode 1); fill-column: 78; -*-
"""
PrintFlow: 3MF Export for a fast and efficient 3D Printing Workflow
Keep your whole 3D printing project in FreeCAD: part orientation, bed
layout, designed supports, slicer settings. PrintFlow makes intelligent
use of FreeCAD's organizational structures (Parts, Assemblies, Groups) and
Property system to control the 3D printing process.
Why? 3D printing is sometimes called "rapid prototyping", and this macro is
designed to make it faster, especially by reduceing iteration time. You
spend less time fiddling in the slicer and stay focused on design.
Key Features:
- Choose what to export:
- Easy for simple stuff: put "Export" in the object label
(e.g. "ExportGroup" or "Print_Bed_1_Export")
- Use properties to fine-tune for complex projects
- Select and print: selection overrides everything
- Organize for printing:
- Assembly contents are treated as separete objects. Assemblies are
great for print layout and part orientation.
- StdParts become slicer objects with multi-part support; useful for
multiple extruders or designed supports.
- Groups are FreeCAD organization only (no impact on output structure)
- Choose slicer settings directly in FreeCAD object properties
- Infill, perimeters, layer height, etc.
- Settings are just passed through, so if the slicer can save it in a
3mf file, you can specify it in FreeCAD.
- Set them *once* in FreeCAD so that you don't need to set them in the
slicer every time you tweak the model. Makes it much less painful and
error-prone to work on complex projects with lots of iteration.
Usage:
Basic Usage:
1. Open your FreeCAD document
2. Select objects in Tree View
3. Run the macro: Macro > Execute macro > PrintFlow.FCMacro
4. Macro auto-generates 3MF filename based on your document name
5. Macro exports 3MF and optionally launches your slicer
Advanced Configuration (for complex projects):
Need more control? Add properties to objects for fine-tuned behavior:
Export Control:
- Add "Export" property (Boolean) in "Export" group to control export of
individual object heirarchies
- Right-click object > Properties > Property > Add Property > Group: "Export"
Slicer Settings:
- Add slicer properties like "extruder", "layer_height", "fill_density" in
"Slicer" group
- Property Group: "Slicer" (not "Export" - different group!)
- Settings persist in your FreeCAD file, no need to reconfigure in slicer
Fine-grained Control:
- Properties inherit through the tree
- Object naming, grouping, and export structure can be customized
- See the full manual at: https://wiki.freecad.org/Macro_PrintFlow
Requirements:
- FreeCAD 1.0 or later
- Objects must have valid Shape geometry
- PrusaSlicer installation (optional, for automatic launching)
Slicer Setup (for auto-launch):
- Create a "SlicerCommand" property in your document (or use default
slicer_wrapper script in your macro folder)
- Point it to your slicer: e.g.,
"/Applications/PrusaSlicer.app/Contents/MacOS/PrusaSlicer"
- Advanced: Use the included slicer_wrapper script for enhanced control
"""
__Name__ = "PrintFlow"
__Comment__ = ("Streamlined 3D Printing Workflow - export FreeCAD to 3MF")
__Author__ = "Michael Stenner"
__Version__ = "1.2.0"
__Date__ = "2025-09-05"
__License__ = "MIT"
__Wiki__ = "https://wiki.freecad.org/Macro_PrintFlow"
__Icon__ = "PrintFlow.svg"
__Status__ = "Stable"
import sys
import os
import os.path
import subprocess
import re
import inspect
import datetime
import copy
from collections import defaultdict
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED
from pprint import pformat
try:
import FreeCAD
import FreeCADGui as Gui
from PySide import QtGui
except ImportError:
print('Outside FreeCAD environment')
# So, it turns out you can't pass command line arguments to FreeCAD
# Macros. Who knew? Rather than packing them into the Macro
# definition, you can put them here:
# Configuration (equivalent to old DEFAULT_ARGS = ['-Ds'])
RUN_SLICER = True
DEBUG = 2 # 0=off, 1=error, 2=warn, 3=log, 4=debug
DOC_DEFAULTS = True
APPEND_VERSION = False
SHOW_ERROR_DIALOGS = True # Set to False for development/testing
# you might find it convenient to not call the slicer directly. For
# example, I like to send the keystrokes to PrusaSlicer to clear the
# platter and start a new project (amazingly, not a command line option)
SLICER_COMMAND = None # Set to override default slicer selection
LOGFILE = os.path.join(os.path.dirname(__file__), "PrintFlow.log")
_LOGFILE_FO = None
def dbprint(*args, level=4, source=1):
"""Debug print with function context and optional file logging.
Only prints when DEBUG >= level. Formats output with calling function
context and indents multi-line values for readability in FreeCAD's
report view. Also writes to LOGFILE if defined.
Args:
source: Stack frame depth for source info. None=no source, int=frames back
"""
if DEBUG < level:
return
if source is None:
s = str(args[0])
else:
f = inspect.stack()[source]
fn = os.path.split(f.filename)[1]
s = f'{args[0]} ({fn}:{f.lineno}:{f.function})'
for v in args[1:]:
for l in str(v).splitlines():
s += '\n' + ' ' * 4 + l
if LOGFILE:
global _LOGFILE_FO
if not _LOGFILE_FO:
import datetime
timestamp = datetime.datetime.now().strftime(
"%Y-%m-%d %H:%M:%S")
print(f'Logging to {LOGFILE}')
_LOGFILE_FO = open(LOGFILE, 'w')
msg = (f'=== PrintFlow Started Logging to '
f'{LOGFILE} at {timestamp} ===\n')
_LOGFILE_FO.write(msg)
_LOGFILE_FO.flush()
_LOGFILE_FO.write(s + '\n')
_LOGFILE_FO.flush()
# Strip ANSI escape codes for console output
s = re.sub(r'\x1b\[[0-9;]*m', '', s)
# Use appropriate FreeCAD Console method based on level
if level == 1: # error
FreeCAD.Console.PrintError(s + '\n')
elif level == 2: # warn
FreeCAD.Console.PrintWarning(s + '\n')
elif level == 3: # log
FreeCAD.Console.PrintMessage(s + '\n')
else: # debug
print(s)
def error(title, message=None, details=None):
"""Log error messages (level 1) - critical failures with popup dialog."""
if message is None:
# Single argument case - treat title as the full message
full_message = str(title)
title = "PrintFlow Error"
message = full_message
dbprint(f"{title}: {message}", level=1, source=None)
if details:
dbprint(f"Error details: {details}", level=1, source=None)
# Show popup dialog
if SHOW_ERROR_DIALOGS:
try:
import FreeCADGui as Gui
from PySide import QtGui
msg_box = QtGui.QMessageBox()
msg_box.setIcon(QtGui.QMessageBox.Critical)
msg_box.setWindowTitle(title)
msg_box.setText(message)
if details:
msg_box.setDetailedText(str(details))
msg_box.exec_()
except Exception:
pass # Fallback if GUI not available
def warn(*args):
"""Log warning messages (level 2) - suspicious but recoverable."""
dbprint(*args, level=2, source=None)
def log(*args):
"""Log info messages (level 3) - user-helpful progress info."""
dbprint(*args, level=3, source=None)
def debug(*args):
"""Log debug messages (level 4) - developer debugging details."""
dbprint(*args, level=4, source=2)
def fl(template, lst):
"""Format List: apply a string template to every item in a list
usage: print(fl(template, list_obj))
currently only works for positional arguments; lst must be a list
of tuples, and format must contain un-named format strings.
"""
#print(template, lst)
return ''.join([template.format(*o) for o in lst])
def get_run_slicer():
"""Get RunSlicer setting with precedence: document > parameters > module default."""
# 1. Document-level property
doc = FreeCAD.ActiveDocument
if doc and hasattr(doc, 'RunSlicer'):
return doc.RunSlicer
# 2. FreeCAD Parameters
try:
param_group = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Macros/PrintFlow")
return param_group.GetBool("RunSlicer", RUN_SLICER)
except:
return RUN_SLICER
def get_append_version():
"""Get AppendVersion setting with precedence: document > parameters > module default."""
# 1. Document-level property
doc = FreeCAD.ActiveDocument
if doc and hasattr(doc, 'AppendVersion'):
return doc.AppendVersion
# 2. FreeCAD Parameters
try:
param_group = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Macros/PrintFlow")
return param_group.GetBool("AppendVersion", APPEND_VERSION)
except:
return APPEND_VERSION
def get_slicer_format():
"""Get SlicerFormat setting with precedence: document > parameters > default."""
# 1. Document-level property
doc = FreeCAD.ActiveDocument
if doc and hasattr(doc, 'SlicerFormat') and doc.SlicerFormat:
return doc.SlicerFormat
# 2. FreeCAD Parameters
try:
param_group = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Macros/PrintFlow")
return param_group.GetString("SlicerFormat", "PrusaSlicer")
except:
return "PrusaSlicer"
def get_slicer_path():
"""Get slicer command with precedence: module > document > parameters > browse.
Returns path to slicer executable, prompting user to browse if needed.
"""
# 1. Module-level override
if SLICER_COMMAND is not None:
return SLICER_COMMAND
# 2. Document-level property
doc = FreeCAD.ActiveDocument
if doc and hasattr(doc, 'SlicerPath') and doc.SlicerPath:
return doc.SlicerPath
# 3. FreeCAD Parameters
try:
param_group = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Macros/PrintFlow")
slicer_cmd = param_group.GetString("SlicerPath", "")
if slicer_cmd:
return slicer_cmd
except:
pass
# 4. First-run setup dialog
return setup_first_run()
def setup_first_run():
"""Show first-run setup dialog to configure PrintFlow preferences."""
try:
from PySide import QtGui
# Create main dialog
dialog = QtGui.QDialog()
dialog.setWindowTitle("PrintFlow First-Run Setup")
dialog.setFixedSize(500, 300)
layout = QtGui.QVBoxLayout()
# Welcome message
welcome = QtGui.QLabel("Welcome to PrintFlow! Let's configure your preferences:")
welcome.setWordWrap(True)
layout.addWidget(welcome)
# Slicer configuration
slicer_group = QtGui.QGroupBox("Slicer Configuration")
slicer_layout = QtGui.QVBoxLayout()
# Slicer format selection
format_layout = QtGui.QHBoxLayout()
format_label = QtGui.QLabel("Slicer Format:")
format_combo = QtGui.QComboBox()
format_combo.addItem("PrusaSlicer")
format_layout.addWidget(format_label)
format_layout.addWidget(format_combo)
slicer_layout.addLayout(format_layout)
# Slicer path selection
path_layout = QtGui.QHBoxLayout()
path_label = QtGui.QLabel("Slicer Path:")
slicer_path_edit = QtGui.QLineEdit()
slicer_path_edit.setPlaceholderText("Path to your slicer executable...")
browse_button = QtGui.QPushButton("Browse...")
def browse_for_slicer():
file_dialog = QtGui.QFileDialog()
file_dialog.setWindowTitle("Select 3D Printing Slicer")
file_dialog.setNameFilter("Executables (*)")
if file_dialog.exec_():
selected = file_dialog.selectedFiles()[0]
slicer_path_edit.setText(selected)
browse_button.clicked.connect(browse_for_slicer)
path_layout.addWidget(path_label)
path_layout.addWidget(slicer_path_edit)
path_layout.addWidget(browse_button)
slicer_layout.addLayout(path_layout)
slicer_group.setLayout(slicer_layout)
layout.addWidget(slicer_group)
# Options
options_group = QtGui.QGroupBox("Default Behavior")
options_layout = QtGui.QVBoxLayout()
run_slicer_check = QtGui.QCheckBox("Auto-launch slicer after export")
run_slicer_check.setChecked(RUN_SLICER)
append_version_check = QtGui.QCheckBox("Add version numbers to filenames")
append_version_check.setChecked(APPEND_VERSION)
options_layout.addWidget(run_slicer_check)
options_layout.addWidget(append_version_check)
options_group.setLayout(options_layout)
layout.addWidget(options_group)
# Buttons
button_layout = QtGui.QHBoxLayout()
ok_button = QtGui.QPushButton("OK")
cancel_button = QtGui.QPushButton("Cancel")
def save_settings():
slicer_path = slicer_path_edit.text().strip()
if not slicer_path:
QtGui.QMessageBox.warning(dialog, "Error",
"Please select a slicer executable.")
return
try:
param_group = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Macros/PrintFlow")
param_group.SetString("SlicerPath", slicer_path)
param_group.SetString("SlicerFormat", format_combo.currentText())
param_group.SetBool("RunSlicer", run_slicer_check.isChecked())
param_group.SetBool("AppendVersion", append_version_check.isChecked())
log(f"Saved PrintFlow preferences: path={slicer_path}, "
f"format={format_combo.currentText()}, "
f"run_slicer={run_slicer_check.isChecked()}, "
f"append_version={append_version_check.isChecked()}")
dialog.accept()
except Exception as e:
QtGui.QMessageBox.critical(dialog, "Error",
f"Could not save preferences: {str(e)}")
ok_button.clicked.connect(save_settings)
cancel_button.clicked.connect(dialog.reject)
button_layout.addWidget(ok_button)
button_layout.addWidget(cancel_button)
layout.addLayout(button_layout)
dialog.setLayout(layout)
if dialog.exec_() == QtGui.QDialog.Accepted:
return slicer_path_edit.text().strip()
else:
# User cancelled - return fallback
return os.path.join(os.path.dirname(__file__), "slicer_wrapper")
except Exception as e:
error("First-run setup failed", str(e))
# Fallback to simple file dialog
try:
from PySide import QtGui
dialog = QtGui.QFileDialog()
dialog.setWindowTitle("Select 3D Printing Slicer")
dialog.setNameFilter("Executables (*)")
if dialog.exec_():
selected_path = dialog.selectedFiles()[0]
if selected_path:
# Save to parameters for future use
try:
param_group = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Macros/PrintFlow")
param_group.SetString("SlicerPath", selected_path)
log(f"Saved slicer command to parameters: {selected_path}")
except:
warn("Could not save slicer command to parameters")
return selected_path
except:
warn("Could not show slicer selection dialog")
# Final fallback
return os.path.join(os.path.dirname(__file__), "slicer_wrapper")
def get_fc_props(fcobj,
testfunc=None,
names=None,
groups=None,
defaults=None,
default_group='Default'):
"""get FreeCAD object properties
Arguments:
testfunc(groupname, propname): property will be ignored if
testfunc returns boolean false. Default behavior is to
require prop to be in names (if not None) and group to be
in groups (if not None)
names - if provided, properties whose names are not "in" it
will be ignored
groups - if provided, properties whose groups are not "in" it
will be ignored
defaults - a mapping type providing default values if the
property isn't defined in the object. If this is not
provided, the a property missing from the FreeCAD object
will also be missing from the return. Note that you can
use the same object as both names and defaults.
default_group - a string or mapping type giving the name of
the group to apply to defaults. If it's a mapping type,
it maps property name to that property's group.
Return Values:
prop[name] = value
prop_group[name] = groupname
"""
if testfunc is None:
def testfunc(g, p):
if names is not None and p not in names:
return False
if groups is not None and g not in groups:
return False
return True
prop = {}
prop_group = {}
o = fcobj # the freecad object
if o is None:
return {}, {}
for p in o.PropertiesList:
# p = property name (string)
g = o.getGroupOfProperty(p) # group name (string)
if testfunc(g, p):
prop[p] = o.getPropertyByName(p)
prop_group[p] = g
if defaults is not None:
if type(default_group) is str:
default_group = {k: default_group for k in defaults}
for k, v in defaults.items():
if k not in prop:
prop[k] = v
prop_group = default_group.get(k, 'Default')
return prop, prop_group
class FCObjectWrapper:
"""Wrapper object for individual FreeCAD objects
We don't want to actually modify the FreeCAD objects or tree
structure, so we'll put this thin wrapper around them. It
includes only the essential data and a reference to the FreeCAD
object itself.
We do get a little fancy for Links and eventually "link descendents".
You know how the same object will show up multiple times in the Tree
View, but it's actually the same object? We will actually make
distinct wrappers for each of those "mirror" branches.
"""
def __init__(self, fcobj, link=None):
self.fcobj = fcobj
self.children = [] # will be populated by FCObjectTree
self.link = link
if not link and fcobj and hasattr(fcobj, 'LinkedObject') \
and fcobj.LinkedObject:
self.link = fcobj.LinkedObject
if fcobj is None: # special case for the "root" object
# this isn't a real FreeCAD object - just a container here
self.parent = None
self.label = 'ROOT'
else:
self.parent = None # Will be set later by TreeView structure
# All wrappers use their fcobj's label
self.label = self.fcobj.Label
self._init_attributes()
self.prop, self.prop_group = self._init_properties()
# Initialize iprop early and copy linked object properties for
# Link wrappers
self.iprop = {}
if self.link:
# Copy linked object's slicer properties to iprop
link_props, _ = get_fc_props(self.link, testfunc=self.prop_test)
for key, value in link_props.items():
if not key.startswith('Export'): # Only slicer properties
self.iprop[key] = value
debug(f"LINK INHERIT: Copied {key}={value} from "
f"{self.link.Label} to {self.label}")
def _init_attributes(self):
"""Initialize wrapper attributes from FreeCAD object"""
# Extract key FreeCAD object attributes
self.selected = self.fcobj in Gui.Selection.getSelection()
self.has_shape = hasattr(self.fcobj, 'Shape')
self.visible = getattr(self.fcobj, "Visibility", None)
self.klass = type(self.fcobj).__name__
self.typeid = getattr(self.fcobj, 'TypeId', None)
prop_test = staticmethod(lambda g, p: g in ('Export', 'Slicer'))
def _init_properties(self, test=None):
"""get FreeCAD object properties of interest
Default behavior is to get all properties of groups "Export"
and "Slicer"
"""
if test is None:
test = self.prop_test
return get_fc_props(self.fcobj, testfunc=test)
def tessellate(self, tree_objects=None):
"""Tessellate object shape and apply transformation matrices.
Args:
tree_objects: Dict mapping labels to wrapper objects
(needed for Assembly placement logic)
Returns:
tuple: (transformation_matrix, transformed_vertices,
triangles)
"""
if self.has_shape and self.fcobj and hasattr(self.fcobj, 'Shape'):
try:
vertices, triangles = self.fcobj.Shape.tessellate(0.01)
except Exception as e:
print(f"ERROR: Tessellation failed for {self.label}: {e}")
vertices, triangles = [], []
else:
vertices, triangles = [], []
# Build cumulative placement matrix by walking up parent chain
# Assembly objects can be skipped based on IgnoreAssemblyPlacement
matrix = FreeCAD.Matrix()
current_wrapper = self
while current_wrapper and current_wrapper.parent and tree_objects:
# pw = parent wrapper
pw = tree_objects.get(current_wrapper.parent)
if not pw:
break
# Skip Assembly placement matrices if
# IgnoreAssemblyPlacement=True
skip_placement = False
if (pw.typeid and pw.typeid.startswith('Assembly::')):
if pw.iprop.get('IgnoreAssemblyPlacement', True):
skip_placement = True
if (pw.fcobj and hasattr(pw.fcobj, 'Placement')
and not skip_placement):
matrix = pw.fcobj.Placement.Matrix.multiply(matrix)
current_wrapper = pw
# Transform all vertices using the cumulative placement matrix
transformed_vertices = []
for v in vertices:
# Convert to FreeCAD Vector, apply matrix, convert back
vec = FreeCAD.Vector(v.x, v.y, v.z)
transformed_vec = matrix.multiply(vec)
tv = transformed_vec # transformed vector
transformed_vertices.append((tv.x, tv.y, tv.z))
return matrix, transformed_vertices, triangles
###############################################################
# Debugging Methods
def debug_summary(self):
"""Produce concise state summary for debugging.
Returns:
str: Single-line summary with consistent column formatting
"""
# Build CSEL flags
c_flag = 'C' if self.iprop.get('ExportContainer') else '-'
s_flag = 'S' if self.iprop.get('ExportShape') else '-'
e_flag = 'E' if self.iprop.get('Export') else '-'
l_flag = 'L' if self.link else '-'
flags = f"[{c_flag}{s_flag}{e_flag}{l_flag}]"
# Object name (25 chars)
name_col = f"{self.label:<25}"
# CSEL flags (6 chars)
flags_col = f"{flags:>6}"
# Link info (15 chars)
if self.link:
link_label = self.link.Label if hasattr(self.link,
'Label') else self.link
link_col = f"{link_label:<15}"
else:
link_col = f"{'':15}"
# Children count (5 chars)
children_col = f"{len(self.children):<5}"
# ExportPath (rest)
export_path = self.iprop.get('ExportPath', '')
path_col = f"{export_path}" if export_path else ""
return (f"{name_col} {flags_col} {link_col} "
f"{children_col} {path_col}")
def __deepcopy__(self, memo):
"""Custom deepcopy to exclude unpicklable FreeCAD objects.
Creates a copy with FreeCAD object references replaced by labels.
We really only need this for the "checkpoint" debugging capability.
"""
# Create new instance without calling __init__
cls = self.__class__
new_obj = cls.__new__(cls)
# Copy all attributes except FreeCAD objects
for key, value in self.__dict__.items():
if key == 'fcobj':
# Store just the label instead of the FreeCAD object
new_obj.fcobj = value.Label if value else None
elif key == 'link':
# Store just the label instead of the FreeCAD link object
new_obj.link = value.Label if value else None
else:
# Deep copy other attributes normally
new_obj.__dict__[key] = copy.deepcopy(value, memo)
return new_obj
def get_document_tree_getparent(doc=None): ## UNUSED - SEE NOTE
"""Build document tree using FreeCAD's getParent() method.
This approach uses the internal FreeCAD object hierarchy as reported
by fcobj.getParent(). This reflects the actual object containment
relationships in the FreeCAD document structure.
Note: Objects may also have a 'Group' property that serves as the
complement to getParent() - where getParent() reports an object's
parent, obj.Group lists an object's children.
Args:
doc: FreeCAD document object. If None, uses ActiveDocument.
Returns:
dict: Mapping of {parent_label: [child_labels]}. The special key
'ROOT' contains top-level objects (those with no parent).
Raises:
ValueError: If no document is available.
"""
# NOTE: this function is currently unused. This was the first
# approach I took to building the tree, and it's probably the
# slimplest and cleanest. Unfortunately, it doesn't appear to always
# be CORRECT, so I had to switch to grabbing things from the Tree View
# GUI element itself. Ew... Maybe this will get fixed some day. The
# two functions have the same API (args & return format)
if doc is None:
doc = FreeCAD.ActiveDocument
if not doc:
raise ValueError("No FreeCAD document available")
tree = {None: []}
# Build parent->children mapping from getParent() relationships
for fcobj in doc.Objects:
try:
parent = fcobj.getParent()
parent_label = parent.Label if parent else None
child_label = fcobj.Label
# Initialize parent entry if needed
if parent_label not in tree:
tree[parent_label] = []
# Add child to parent's list
tree[parent_label].append(child_label)
# Initialize child entry (may have children of its own)
if child_label not in tree:
tree[child_label] = []
except Exception as e:
# Log but continue - don't let one bad object break everything
warn(f"Failed to process object {fcobj.Label}: {e}")
return tree
def get_document_tree_treeview(doc=None):
"""Build document tree using FreeCAD's TreeView GUI widget.
This approach walks the actual TreeView widget structure as displayed
in the FreeCAD GUI. This represents the logical organization that
users see and interact with, which may differ from internal object
relationships.
For example, boolean operation operands appear as children of the
boolean operation in the TreeView, but report the parent Part as their
getParent().
Args:
doc: FreeCAD document object. If None, uses ActiveDocument.
Note: This is used only for validation - the TreeView widget
determines which document is actually traversed.
Returns:
dict: Mapping of {parent_label: [child_labels]}. The special key
'ROOT' contains top-level objects in the document.
Raises:
ValueError: If no document is available or TreeView access fails.
RuntimeError: If TreeView widget cannot be found or accessed.
"""
if doc is None:
doc = FreeCAD.ActiveDocument
if not doc:
raise ValueError("No FreeCAD document available")
try:
# Access the TreeView widget through FreeCAD's main window
tree_widget = Gui.getMainWindow().findChildren(QtGui.QTreeWidget)[0]
root = tree_widget.invisibleRootItem()
if root.childCount() == 0:
raise RuntimeError("TreeView widget appears empty")
# Find the document node (should be first child of root)
doc_node = root.child(0)
if not doc_node:
raise RuntimeError("Cannot find document node in TreeView")
tree = {None: []}
def collect_tree_recursive(tree_item, parent_label):
"""Recursively collect TreeView structure."""
if tree_item is None:
return
item_label = tree_item.text(0)
# Add this item to parent's children list
if parent_label not in tree:
tree[parent_label] = []
tree[parent_label].append(item_label)
# Initialize this item's children list
if item_label not in tree:
tree[item_label] = []
# Check if we should stop recursion at this object
fcobjs = doc.getObjectsByLabel(item_label)
fcobj = fcobjs[0] if fcobjs else None
if fcobj and stop_treeview_recursion(fcobj):
# Include this object but don't recurse into its TreeView
# children
return
# Process all children recursively
for i in range(tree_item.childCount()):
child_item = tree_item.child(i)
collect_tree_recursive(child_item, item_label)
# Process all top-level items in the document
for i in range(doc_node.childCount()):
item = doc_node.child(i)
collect_tree_recursive(item, None)
return tree
except Exception as e:
raise RuntimeError(f"Failed to access TreeView widget: {e}")
def stop_treeview_recursion(fcobj):
"""Determine if TreeView recursion should stop at this FreeCAD object.
This prevents TreeView from expanding Link descendants that would cause
duplicate parent assignments. Links themselves are included in the tree,
but their TreeView children are skipped since they're actually children
of the LinkedObject that will be processed naturally during traversal.
It may seem strange that we choose NOT to include these objects here,
and then we effecitvely rebuild them later with the link wrapper
descendents. Lets call that an artifact of history. I implemented
the getParent-based tree first, which DID NOT provide these
duplicates. Then I disovered that the getParent approach wasn't
always right. Here we are.
Args:
fcobj: FreeCAD object to test
Returns:
bool: True if recursion should stop, False if recursion should
continue
"""
if not fcobj:
return False
# Get object properties for decision making
typeid = getattr(fcobj, 'TypeId', '')
linked_obj = getattr(fcobj, 'LinkedObject', None)
element_count = getattr(fcobj, 'ElementCount', 0)
if False:
debug(
f"DEBUG: stop_treeview_recursion({fcobj.Label}): "
f"typeid='{typeid}', "
f"LinkedObject={linked_obj.Label if linked_obj else None}, "
f"ElementCount={element_count}")
# Stop recursion for regular Links (App::Link with LinkedObject)
if typeid == 'App::Link' and linked_obj:
if False:
debug(
f"DEBUG: Stopping recursion at Link {fcobj.Label} -> "
f"{linked_obj.Label}"
)
return True
# Continue recursion for all other objects (including Link arrays for
# now)
return False
class FCObjectTree:
"""Copy the FreeCAD object tree and manipulate the copy
Most of the "logic" is handled in this class, including:
- handling of properties, including
- "default" properties (assumed based on object type)
- internal properties (passed down the tree implicitly)
- selection of which objects to export (based on properties,
selection, etc.))
"""
def __init__(self, doc=None, object_class=None):
if object_class is not None:
self.object_class = object_class
else:
self.object_class = FCObjectWrapper
if doc is not None:
self.doc = doc
else:
self.doc = FreeCAD.ActiveDocument
self.objects = {}
# Build list of selected objects at initialization
try:
import FreeCADGui as Gui
self.selected = [
obj.Label for obj in Gui.Selection.getSelection()
]
if DEBUG and self.selected:
log(f"Selected objects at tree init: {self.selected}")
except ImportError:
# Handle case where GUI is not available (headless mode)
self.selected = []
self._load()
self._create_link_wrappers() # expand the tree for links
self._prune_non_printable() # remove axes, sketches, etc.
self._internal_props() # generate and propagete properties
if DEBUG:
compact_tree = self.print_compact_tree(return_string=True)
debug("Compact object tree:\n" + compact_tree)
tree_output = self.print_tree(True, return_string=True)
debug("Object tree with properties:\n" + tree_output)
def _wrap_document_objects(self):
"""Wrap all FreeCAD objects in FCObjectWrapper instances."""
self.objects[None] = self.object_class(None)
for fcobj in self.doc.Objects:
try:
ow = self.object_class(fcobj) # Auto-detects Links now
if ow.label in self.objects:
warn(f"Duplicate label found: {ow.label}")
self.objects[ow.label] = ow
except Exception as e:
obj_label = getattr(fcobj, 'Label', 'UNKNOWN')
print(f"ERROR: Failed to wrap object {obj_label}: {e}")
def _build_parent_child_relationships(self):
"""Create parent-child relationships using TreeView structure."""
tree = get_document_tree_treeview(self.doc)
for parent_key, children_labels in tree.items():
self._process_parent_children(parent_key, children_labels)
def _process_parent_children(self, parent_key, children_labels):
"""Process parent-child relationships for a specific parent."""
if parent_key in self.objects:
for child_label in children_labels:
if child_label in self.objects:
# Set parent-child relationship for ALL objects
self.objects[parent_key].children.append(child_label)
self.objects[child_label].parent = parent_key
def _load(self):
"""populate self.objects with {label: FCObjectWrapper(fcobj)}
and then complete 'children' lists within each wrapper object
Notes:
- the "None" key in self.objects points to the "ROOT"
object, which isn't a real object, just a meta-object
whose "children" are the top-level objects
- this tree DOES NOT use logical dependencies (inList &
outList). It only uses the nesting of the treeview.
"""
# Phase 1: Wrap all FreeCAD objects
self._wrap_document_objects()
# Phase 2: Build parent-child relationships from TreeView
self._build_parent_child_relationships()
def _create_link_wrappers(self):
"""Create descendents for Link wrappers."""
# Links are now created correctly in _load(), just need
# descendents
# Take snapshot to avoid "dictionary changed size during iteration"
objects_snapshot = list(self.objects.items())
for label, ow in objects_snapshot:
is_descendant = getattr(ow, 'is_link_descendant', False)
if ow and ow.link:
if not is_descendant:
self._create_link_descendents(label)
####################################################################
# Helper Methods for Link handling and Tree Expansion
def _dereference_link_chain(self, fcobj):
"""Follow Link chain to final destination object.
Handles nested Links (Link->Link->Body) by following the chain
until we reach a non-Link object.
Args:
fcobj: FreeCAD object to dereference
Returns:
Final linked FreeCAD object (non-Link)
"""
visited = set()
current = fcobj