-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathkicad_StepUp.FCMacro
executable file
·7167 lines (6794 loc) · 302 KB
/
kicad_StepUp.FCMacro
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/python
# -*- coding: utf-8 -*-
#****************************************************************************
#* *
#* Kicad STEPUP (TM) (3D kicad board and models to STEP) for FreeCAD *
#* 3D exporter for FreeCAD *
#* Kicad STEPUP TOOLS (TM) (3D kicad board and models to STEP) for FreeCAD *
#* Copyright (c) 2015 *
#* Maurice [email protected] *
#* *
#* Kicad STEPUP (TM) is a TradeMark and cannot be freely useable *
#* *
#* code partially based on: *
#* Printed Circuit Board Workbench for FreeCAD FreeCAD-PCB *
#* Copyright (c) 2013, 2014, 2015 *
#* marmni <[email protected]> *
#* *
#* and IDF import for FreeCAD *
#* (c) Milos Koutny ([email protected]) 2012 *
#* and (c) hyOzd ecad-3d-model-generator *
#* *
#* this macro rotates, translates and scales one object *
#* scale for VRML export and open footprint for easy alignement *
#* this sw is a part of kicad StepUp code *
#* all credits and licence details in kicad StepUp code *
#* Macro_Move_Rotate_Scale *
#* ver in ___ver___ *
#* Copyright (c) 2015 *
#* Maurice [email protected] *
#* *
#* Collisions routines from Highlight Common parts Macro *
#* author JMG, galou and other contributors *
#* *
#* IDF_ImporterVersion="3.9.2"
#* ignoring step search associations (too old models)
#* displaying Flat Mode models
#* checking version 3 for both Geometry and Part Number
#* supporting Z position
#* skipping PROP in emp file
#* adding color to shapes opt IDF_colorize
#* adding emp library/single model load support
#* aligning IDF shape to both Geom and PartNBR for exactly match
#* to do: .ROUTE_OUTLINE ECAD, .PLACE_OUTLINE MCAD, .ROUTE_KEPOUT ECAD, .PLACE_KEEPOUT ECAD
#****************************************************************************
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Affero General Public License *
#* as published by the Free Software Foundation to ensure cooperation *
#* with the community in the case of network server software; *
#* for detail see the LICENCE text file. *
#* http://www.gnu.org/licenses/agpl-3.0.en.html *
#* Moreover you have to include the original author copyright *
#* kicad StepUP made by Maurice [email protected] *
#* *
#* 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., *
#* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
#* *
#****************************************************************************
##With kicad StepUp you’ll get an exact representation of your physical board in Native 3D PCB
## kicad StepUp tools
##done
# upgrade kicadstepup version
# resized font size
# add bbox and volume images on the starter guide
# add ksu config more detailed description
# complete volume_minimum config in doc
# improved OSX QtGui File Open
# better arc and line import
# remove test button
# enable confirm on exit
# replace FreeCAD.Console.Message -> say
##todo list
# collision and proximity as microelly
## kicad StepUp
# added messages on missing emn files
# added messages on missing models
# added path to adapt your KISYS3DMOD
# added blacklist for unwanted modules
# added messages on blacklisted modules
# added pcb color attribute
# added bounding box option
# added bounding box white list to leave real model on connector or peripheral models
# added auxorigin, base origin, base point placement option
# added vrml models z-rotation angle
# added virtual models option
# added fusion export option
# added saving in native format, export to STEP
# added arcs and circles for calculate board position
# added idf_to_origin flag for version >6091
# added reset properties for FC 016 bug
# added ${KIPRJMOD} support
# added v3,v4 pcb version support
# added multi 3D vrml model support
# added compatibility to kicad version >=3
# added auto color assigning in bboxes
# added minimum volume per model
# added minimum height per model
# updated findPcbCenter method
# added support for .stp extension beside .step
# added support for .igs extension beside .step
# added support for .iges extension beside .step
# because of hole sovrapposition prob...
# cutting hole by hole instead of hole compound
# added holes_solid var
# to have holes as solid to garantee cutting
# handled single circle
# used OpenSCAD2Dgeom instead of wire + face (best option)
# http://www.freecadweb.org/wiki/index.php?title=Macro_Creating_faces_from_a_DXF_file
# fixed unicode text parsing
# double option .kicad_pcb .emn
# in case of non coincidences .emn is more tolerant
# try to build wires on closed shaped for make the cutting faster
# try to optimize cutting changing creation/type of holes
# manage bklist and volume
# accept with or without /\ at the end of 3Dpath
# search models in KIPRJMOD and in KISYS3DMOD
# removed unicode chars in .kicad_pcb
# exported wrl, step from python
# reload & display ini cfg file
# display/edit ini file with syntax highlight
# msg first ksu config
# added warning for import step multi part fixed v3035
# commented warning in load footprint and in placing step mod if x,y are different from 0 0 0
# added message if scale are different from 1 1 1
# non stopping warning for footprint
# added command line args to load board(/emn)
# avoid argv in memory in case of opened from command line
# used multi cut also for footprint too
# enabled loadB, loadI, loadF with filename=None to align Mod and Macro
# enabled Macro & Mod
# added ico tools info
# added checkbox export_2_step
# added export2STEP var in ini file
# subst print to say
# fixed cursor wait
# angle on pads for footprint pads angle i.e. DB25M_V ok
# improved multipart load checking
# added virtual checkbox
# added VRML with material properties exporter
# added metal grey material
# added multipart VRML option
# improved export resolution from %.3f, %.5f to %g
# added config for material props
# pad & holes as circles when possible
# improved multipart load checking
# removed illegal characters in filenames when exporting VRML and STEP
# message of missing models at the end
# implemented caching for 3D models
# optimized for fusion w/ colors
# added support for alias i.e. :Kicad3D: as for environment variables
# added crease angle for wrl export
# added support for ${KISYS3DMOD}/ in new 3d viewer path resolver
# accepting .wrl .step .stp .iges .igs as 3d models directly in kicad_pcb
# added fixedPosition for aligning part to footprint in assembly2
# message if scale values are not assigned to 1 1 1
# added support for wrl offset in position & rotation when loadboard
# added bbox creation based on scaled values (1mm as base unit)
# added height and volume blacklist for scaled shapes
# added error message in case of scale factor not 1:1 for non scaled box
# fixed base point for lower case settings
# added single instance
# added open file type 'rb' 'ab' and write file 'wb' type binary for utf8 full support
# added fix to rect pads in footprint loader
# non blocking warning only for scale <> 1
# fixed minor issues in FC015 loading fp
# added models3Dprefix as default saving location
# added $HOME support for unix systems (it doesn't resolve on win)
# added OCC >=7 FC 0.17 compatibility for Footprint pads, lines, arcs
# added check if the models3Dprefix is writable, otherwise will write on $HOME
# added 2nd path to resolver prefix3d_2
# most clean code and comments done
##todo
## accept utf8 on 3D prefix path
## load local config if exists
## add transp 25 50 75 to asis in exp wrl or keep transp ?
## allow multipart
# message error for bad config
# enable upper case configparser optionxform
# http://stackoverflow.com/questions/19359556/configparser-reads-capital-keys-and-make-them-lower-case
# use isInside/common ( TopoShape ) to cut only intersection objs
# multi board
# evaluate python occ for step exporting with SCL
# test option placement
# check line 772 abs ZMax = height?
# fix fonts for html and new buttons
# ...
# respect transparency on shapes NOT possible on STEP objects because of FC
# try to close non closed wire
# from Macro_JointWire
# pad type trapez, rect rounded
## try to add this code for utf8 support (see @ #workaround to remove utf8 extra chars )
# import sys
# reload(sys)
# sys.setdefaultencoding('utf8') #to accept utf8 chars
## import statements
import FreeCAD,FreeCADGui,Part,Mesh
#import PySide
from collections import namedtuple
import PySide
from PySide import QtGui, QtCore
from time import sleep
from math import sqrt, tan, atan, atan2, degrees, radians, hypot, sin, cos, pi, fmod
import Draft, Part
from collections import namedtuple
from FreeCAD import Base
import sys, os
from os.path import expanduser
import tempfile, errno
import re
import time
import OpenSCAD2Dgeom
import ImportGui
from math import sqrt, atan, sin, cos, radians, degrees, pi
import argparse
import __builtin__
if FreeCAD.GuiUp:
from PySide import QtCore, QtGui
import OpenSCADFeatures
#from codecs import open #maui to verify
#import unicodedata
pythonopen = __builtin__.open # to distinguish python built-in open function from the one declared here
## Constant definitions
___ver___ = "3.1.1.6" # added single instance and utf8 support
__title__ = "kicad_StepUp"
__author__ = "maurice & mg"
__Comment__ = 'Kicad STEPUP(TM) (3D kicad board and models exported to STEP) for FreeCAD'
___ver_ksu___ = "1.0.1.9 25/11/2015"
IDF_ImporterVersion="3.9.2"
__Icon__ = "stepup.png"
global userCancelled, userOK, show_mouse_pos, min_val, last_file_path, resetP
global start_time, show_messages
global show_messages, applymaterials
global real_board_pos_x, real_board_pos_y, board_base_point_x, board_base_point_y
global ksu_config_fname, ini_content, configFilePath
global models3D_prefix, blacklisted_model_elements, col, colr, colg, colb
global bbox, volume_minimum, height_minimum, idf_to_origin, aux_orig
global base_orig, base_point, bbox_all, bbox_list, whitelisted_model_elements
global fusion, addVirtual, blacklisted_models, exportFusing, min_drill_size
global last_fp_path, last_pcb_path, plcmnt, xp, yp, exportFusing, exportS
global full_placement
exportS=True
last_file_path=''
resetP=True
global rot_wrl, test_flag, test_flag_pads
rot_wrl=0.0
#global module_3D_dir
userCancelled = "Cancelled"
userOK = "OK"
show_mouse_pos = True
#module_3D_dir="C:/Cad/Progetti_K/a_mod"
min_val=0.001
conflict_tolerance=1e-6 #volume tolerance
font_size=8
bbox_r_col=(0.411765, 0.411765, 0.411765) #dimgrey
bbox_c_col=(0.823529, 0.411765, 0.117647) #chocolate
bbox_x_col=(0.862745, 0.862745, 0.862745) #gainsboro
bbox_l_col=(0.333333, 0.333333, 0.333333) #sgidarkgrey
bbox_IC_col=(0.156863, 0.156863, 0.156863) #sgiverydarkgrey
bbox_default_col=(0.439216, 0.501961, 0.564706) #slategrey
mat_section="""
[Materials]
mat = enablematerials
;; VRML models to be or not exported with material properties
;mat = enablematerials\n;mat = nomaterials
"""
test_flag=False
#test_flag=True
test_flag_exit=False #True 4 testing
test_flag_pads=False #False 4 testing
remove_pcbPad=True #False 4 testing
close_doc=False
show_border=False
show_shapes=False
disable_cutting=False
# enable_materials=True not used
test_extrude=False
holes_solid=True
emn_version=3.0
show_messages=True #False 4 testing
#show_messages=False # mauitest
full_placement=True # for offset in xyz and rotation in xyz
FreeCAD.Console.PrintWarning(full_placement)
FreeCAD.Console.PrintWarning('\n')
global export_board_2step
#export_board_2step=False
save_temp_data=False
global ignore_utf8
ignore_utf8=False
current_milli_time = lambda: int(round(time.time() * 1000))
Materials=True
## "PIN-01";"metal grey pins"
## "PIN-02";"gold pins"
## "IC-BODY-EPOXY-04";"black body"
## "RES-SMD-01";"resistor black body"
## "IC-BODY-EPOXY-01";"grey body"
## "CAP-CERAMIC-05";"dark grey body"
## "CAP-CERAMIC-06";"brown body"
## "PLASTIC-GREEN-01";"green body"
## "PLASTIC-BLUE-01";"blue body"
## "PLASTIC-WHITE-01";"white body"
## "IC-LABEL-01";"light brown label"
## LED-GREEN, LED-RED, LED-BLUE
as_is=""
metal_grey_pins="""material DEF PIN-01 Material {
ambientIntensity 0.271
diffuseColor 0.824 0.820 0.781
specularColor 0.328 0.258 0.172
emissiveColor 0.0 0.0 0.0
shininess 0.70
transparency 0.0
}"""
# http://vrmlstuff.free.fr/materials/
metal_grey="""material DEF MET-01 Material {
ambientIntensity 0.249999
diffuseColor 0.298 0.298 0.298
specularColor 0.398 0.398 0.398
emissiveColor 0.0 0.0 0.0
shininess 0.056122
transparency 0.0
}"""
gold_pins="""material DEF PIN-02 Material {
ambientIntensity 0.379
diffuseColor 0.859 0.738 0.496
specularColor 0.137 0.145 0.184
emissiveColor 0.0 0.0 0.0
shininess 0.40
transparency 0.0
}"""
black_body="""material DEF IC-BODY-EPOXY-04 Material {
ambientIntensity 0.293
diffuseColor 0.148 0.145 0.145
specularColor 0.180 0.168 0.160
emissiveColor 0.0 0.0 0.0
shininess 0.35
transparency 0.0
}"""
resistor_black_body="""material DEF RES-SMD-01 Material {
diffuseColor 0.082 0.086 0.094
emissiveColor 0.000 0.000 0.000
specularColor 0.066 0.063 0.063
ambientIntensity 0.638
transparency 0.0
shininess 0.3
}"""
dark_grey_body="""material DEF CAP-CERAMIC-05 Material {
ambientIntensity 0.179
diffuseColor 0.273 0.273 0.273
specularColor 0.203 0.188 0.176
emissiveColor 0.0 0.0 0.0
shininess 0.15
transparency 0.0
}"""
grey_body="""material DEF IC-BODY-EPOXY-01 Material {
ambientIntensity 0.117
diffuseColor 0.250 0.262 0.281
specularColor 0.316 0.281 0.176
emissiveColor 0.0 0.0 0.0
shininess 0.25
transparency 0.0
}"""
brown_body="""material DEF CAP-CERAMIC-06 Material {
ambientIntensity 0.453
diffuseColor 0.379 0.270 0.215
specularColor 0.223 0.223 0.223
emissiveColor 0.0 0.0 0.0
shininess 0.15
transparency 0.0
}"""
light_brown_body="""material DEF RES-THT-01 Material {
ambientIntensity 0.149
diffuseColor 0.883 0.711 0.492
specularColor 0.043 0.121 0.281
emissiveColor 0.0 0.0 0.0
shininess 0.40
transparency 0.0
}"""
blue_body="""material DEF PLASTIC-BLUE-01 Material {
ambientIntensity 0.565
diffuseColor 0.137 0.402 0.727
specularColor 0.359 0.379 0.270
emissiveColor 0.0 0.0 0.0
shininess 0.25
transparency 0.0
}"""
green_body="""material DEF PLASTIC-GREEN-01 Material {
ambientIntensity 0.315
diffuseColor 0.340 0.680 0.445
specularColor 0.176 0.105 0.195
emissiveColor 0.0 0.0 0.0
shininess 0.25
transparency 0.0
}"""
orange_body="""material DEF PLASTIC-ORANGE-01 Material {
ambientIntensity 0.284
diffuseColor 0.809 0.426 0.148
specularColor 0.039 0.102 0.145
emissiveColor 0.0 0.0 0.0
shininess 0.25
transparency 0.0
}"""
red_body="""material DEF RED-BODY Material {
ambientIntensity 0.683
diffuseColor 0.700 0.100 0.050
emissiveColor 0.000 0.000 0.000
specularColor 0.300 0.400 0.150
shininess 0.25
transparency 0.0
}"""
pink_body="""material DEF CAP-CERAMIC-02 Material {
ambientIntensity 0.683
diffuseColor 0.578 0.336 0.352
specularColor 0.105 0.273 0.270
emissiveColor 0.0 0.0 0.0
shininess 0.25
transparency 0.0
}"""
yellow_body="""material DEF PLASTIC-YELLOW-01 Material {
ambientIntensity 0.522
diffuseColor 0.832 0.680 0.066
specularColor 0.160 0.203 0.320
emissiveColor 0.0 0.0 0.0
shininess 0.25
transparency 0.0
}"""
white_body="""material DEF PLASTIC-WHITE-01 Material {
ambientIntensity 0.494
diffuseColor 0.895 0.891 0.813
specularColor 0.047 0.055 0.109
emissiveColor 0.0 0.0 0.0
shininess 0.25
transparency 0.0
}"""
light_brown_label="""material DEF IC-LABEL-01 Material {
ambientIntensity 0.082
diffuseColor 0.691 0.664 0.598
specularColor 0.000 0.000 0.000
emissiveColor 0.0 0.0 0.0
shininess 0.01
transparency 0.0
}"""
led_red="""material DEF LED-RED Material {
ambientIntensity 0.789
diffuseColor 0.700 0.100 0.050
emissiveColor 0.000 0.000 0.000
specularColor 0.300 0.400 0.150
shininess 0.125
transparency 0.10
}"""
led_green="""material DEF LED-GREEN Material {
ambientIntensity 0.789
diffuseColor 0.400 0.700 0.150
emissiveColor 0.000 0.000 0.000
specularColor 0.600 0.300 0.100
shininess 0.05
transparency 0.10
}"""
led_blue="""material DEF LED-BLUE Material {
ambientIntensity 0.789
diffuseColor 0.100 0.250 0.700
emissiveColor 0.000 0.000 0.000
specularColor 0.500 0.600 0.300
shininess 0.125
transparency 0.10
}"""
led_yellow="""material DEF LED-YELLOW Material {
ambientIntensity 0.522
diffuseColor 0.98 0.840 0.066
specularColor 0.160 0.203 0.320
emissiveColor 0.0 0.0 0.0
shininess 0.125
transparency 0.10
}"""
led_white="""material DEF LED-WHITE Material {
ambientIntensity 0.494
diffuseColor 0.895 0.891 0.813
specularColor 0.047 0.055 0.109
emissiveColor 0.0 0.0 0.0
shininess 0.125
transparency 0.10
}"""
material_properties_names=["as is","metal grey pins","metal grey","gold pins","black body","resistor black body",\
"grey body","dark grey body","brown body","light brown body","blue body",\
"green body","orange body","red_body","pink body","yellow body","white body","light brown label",\
"led red","led green","led blue","led yellow","led white"]
material_properties=[as_is,metal_grey_pins,metal_grey,gold_pins,black_body,resistor_black_body,\
grey_body,dark_grey_body,brown_body,light_brown_body,blue_body,\
green_body,orange_body,red_body,pink_body,yellow_body,white_body,light_brown_label,\
led_red,led_green,led_blue,led_yellow,led_white]
material_definitions=""
for mat in material_properties[1:]:
material_definitions+="Shape {\n appearance Appearance {"+mat+"\n }\n}\n"
material_ids=[]
material_ids.append("")
for mat in material_properties[1:]:
m = re.search('DEF\s(.+?)\sMaterial', mat)
if m:
found = m.group(1)
#say(found)
material_ids.append(found)
#say(material_ids)
#say (material_definitions)
def clear_console():
#clearing previous messages
mw=FreeCADGui.getMainWindow()
c=mw.findChild(QtGui.QPlainTextEdit, "Python console")
c.clear()
r=mw.findChild(QtGui.QTextEdit, "Report view")
r.clear()
#if not Mod_ENABLED:
clear_console()
# points: [Vector, Vector, ...]
# faces: [(pi, pi, pi), ], pi: point index
# color: (Red, Green, Blue), values range from 0 to 1.0
Mesh = namedtuple('Mesh', ['points', 'faces', 'color', 'transp'])
from sys import platform as _platform
import ConfigParser
def insert(filename, other):
if os.path.exists(filename):
open(filename)
else:
FreeCAD.Console.PrintError("File does not exist.\n")
reply = QtGui.QMessageBox.information(None,"info", "File does not exist.\n")
def open(filename):
#reply = QtGui.QMessageBox.information(None,"info", filename)
#onLoadBoard_cmd(filename)
ext = os.path.splitext(os.path.basename(filename))[1]
sayw("kicad StepUp version "+str(___ver___))
if ext==".kicad_pcb":
onLoadBoard(filename)
elif ext==".emn":
onLoadBoard_idf(filename)
elif ext==".kicad_mod":
onLoadFootprint(filename)
def say(msg):
FreeCAD.Console.PrintMessage(msg)
def sayw(msg):
FreeCAD.Console.PrintWarning(msg)
FreeCAD.Console.PrintWarning('\n')
def sayerr(msg):
FreeCAD.Console.PrintError(msg)
FreeCAD.Console.PrintWarning('\n')
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 164)
self.buttonBox = QtGui.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(30, 110, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.comboBox = QtGui.QComboBox(Dialog)
self.comboBox.setGeometry(QtCore.QRect(180, 40, 191, 22))
self.comboBox.setMaxVisibleItems(25)
self.comboBox.setObjectName("comboBox")
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(180, 20, 53, 16))
self.label.setObjectName("label")
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(20, 20, 53, 16))
self.label_2.setObjectName("label_2")
self.plainTextEdit = QtGui.QPlainTextEdit(Dialog)
self.plainTextEdit.setEnabled(False)
self.plainTextEdit.setGeometry(QtCore.QRect(20, 40, 31, 31))
self.plainTextEdit.setBackgroundVisible(False)
self.plainTextEdit.setObjectName("plainTextEdit")
self.plainTextEdit_2 = QtGui.QPlainTextEdit(Dialog)
self.plainTextEdit_2.setEnabled(False)
self.plainTextEdit_2.setGeometry(QtCore.QRect(120, 40, 31, 31))
self.plainTextEdit_2.setBackgroundVisible(False)
self.plainTextEdit_2.setObjectName("plainTextEdit_2")
self.label_3 = QtGui.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(120, 20, 41, 16))
self.label_3.setObjectName("label_3")
self.label_4 = QtGui.QLabel(Dialog)
self.label_4.setGeometry(QtCore.QRect(20, 80, 351, 16))
self.label_4.setObjectName("label_4")
QtCore.QObject.connect(self.comboBox, QtCore.SIGNAL("currentIndexChanged(QString)"), self.SIGNAL_comboBox_Changed)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def SIGNAL_comboBox_Changed(self,text):
#say("combo changed "+text)
comboBox_Changed(text)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Material Properties", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog", "Materials", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("Dialog", "Original", None, QtGui.QApplication.UnicodeUTF8))
self.plainTextEdit.setToolTip(QtGui.QApplication.translate("Dialog", "Shape Color", None, QtGui.QApplication.UnicodeUTF8))
self.plainTextEdit_2.setToolTip(QtGui.QApplication.translate("Dialog", "Diffuse Color", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("Dialog", "New", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("Dialog", "Note: set Material will unmatch colors between wrl and STEP ", None, QtGui.QApplication.UnicodeUTF8))
###
def isWritable(path):
try:
testfile = tempfile.TemporaryFile(dir = path)
testfile.close()
#sayw('ok')
return True
except:
#except OSError as e:
#sayw('ko')
sayw('folder not writable!')
pass
return False
#if e.errno == errno.EACCES: # 13
# return False
#e.filename = path
#return False
#raise
sayw('folder not writable!')
return False
###
def comboBox_Changed(text_combo):
global ui
#say(text_combo)
material_index=material_properties_names.index(text_combo)
#say(material_index)
mat_prop = material_properties[material_index].split('\n')
if len(mat_prop)>1:
# say(mat_prop[2])
color_rgb=mat_prop[2].split(' ')
# say (color_rgb)
# say(color_rgb[9]+" "+color_rgb[10]+" "+color_rgb[11])
pal = QtGui.QPalette()
bgc = QtGui.QColor(float(color_rgb[9])*255,float(color_rgb[10])*255, float(color_rgb[11])*255)
pal.setColor(QtGui.QPalette.Base, bgc)
ui.plainTextEdit_2.viewport().setPalette(pal)
###
def cfgParsWrite(configFilePath):
##ksu pre-set
global models3D_prefix, blacklisted_model_elements, col, colr, colg, colb
global bbox, volume_minimum, height_minimum, idf_to_origin, aux_orig, addVirtual
global base_orig, base_point, bbox_all, bbox_list, whitelisted_model_elements
global fusion, addVirtual, blacklisted_models, exportFusing, min_drill_size
global last_fp_path, last_pcb_path, plcmnt, xp, yp, exportFusing, export_board_2step
global enable_materials
configParser.set('last_footprint_path', 'last_fp_path', last_fp_path)
configParser.set('last_pcb_path', 'last_pcb_path', last_pcb_path)
if export_board_2step:
configParser.set('export', 'export_to_step', "yes")
else:
configParser.set('export', 'export_to_step', "no")
if addVirtual==1:
configParser.set('Virtual', 'virt', "addvirtual")
else:
configParser.set('Virtual', 'virt', "novirtual")
if enable_materials==1:
configParser.set('Materials', 'mat', "enablematerials")
else:
configParser.set('Materials', 'mat', "nomaterials")
#configParser.set('last_fp_path', ';; last footprint file path used')
configParser.set('info', default_ksu_msg[0])
configParser.set('prefix3D', default_ksu_msg[1])
configParser.set('PcbColor', default_ksu_msg[2])
configParser.set('Blacklist', default_ksu_msg[3])
configParser.set('BoundingBox', default_ksu_msg[4])
configParser.set('Placement', default_ksu_msg[5])
configParser.set('Virtual', default_ksu_msg[6])
configParser.set('ExportFuse', default_ksu_msg[7])
configParser.set('minimum_drill_size', default_ksu_msg[8])
configParser.set('last_pcb_path', default_ksu_msg[9])
configParser.set('last_footprint_path', default_ksu_msg[10])
configParser.set('export', default_ksu_msg[11])
configParser.set('Materials', default_ksu_msg[12])
# save to the config file
with __builtin__.open(configFilePath, 'wb') as configfile:
configParser.write(configfile)
#configFilePath.close() already closed
###
def cfgParsRead(configFilePath):
##ksu pre-set
global models3D_prefix, models3D_prefix2, blacklisted_model_elements, col, colr, colg, colb
global bbox, volume_minimum, height_minimum, idf_to_origin, aux_orig
global base_orig, base_point, bbox_all, bbox_list, whitelisted_model_elements
global fusion, addVirtual, blacklisted_models, exportFusing, min_drill_size
global last_fp_path, last_pcb_path, plcmnt, xp, yp, exportFusing, export_board_2step
global enable_materials, mat_section
#with __builtin__.open(configFilePath, 'r') as mycfg:
with __builtin__.open(configFilePath, 'rb') as mycfg:
content = mycfg.readlines()
#time.sleep(0.5)
mycfg.close()
#say(content)
if any("Materials" in s for s in content):
say ("Materials section present\n")
else:
#if "Materials" not in content:
enable_materials = 1
say ("missing material section, adding default one\n")
#with __builtin__.open(configFilePath, 'a') as mycfg:
with __builtin__.open(configFilePath, 'ab') as mycfg:
mycfg.write(mat_section)
mycfg.close()
#stop
#cfg_parameters=[]
models3D_prefix = ''
blacklisted_model_elements=''
#col=''; col='0.0,0.5,0.0,green'; # color
col=''; col='0.0,0.0,1.0,blue'; # color
bbox=0
#(0.6,0.4,0.2) brown
volume_minimum=0 #0.8 ##1 #mm^3, 0 skipped #global var default
height_minimum=0 #0.8 ##1 #mm, 0 skipped #global var default
## to debug quickly put show_messages=False
### from release 6091 this flag enables the option to place IDF exported to origin
idf_to_origin=True
#idf_to_origin=False
aux_orig=0;base_orig=0;base_point=0
bbox_all=0; bbox_list=0; whitelisted_model_elements=''
fusion=False; addVirtual=0; enable_materials=0
configParser.read(configFilePath)
models3D_prefix = configParser.get('prefix3D', 'prefix3D_1')
models3D_prefix2=""
try:
models3D_prefix2 = configParser.get('prefix3D', 'prefix3D_2')
say("prefix3D_2 checking\n")
if len (models3D_prefix2) > 0:
say("prefix3D_2 found\n")
if not models3D_prefix2.endswith('/'):
if not models3D_prefix2.endswith('\\'):
models3D_prefix2+='/'
except:
sayw("prefix3D_2 not found")
pass
if not models3D_prefix.endswith('/'):
if not models3D_prefix.endswith('\\'):
models3D_prefix+='/'
#say(models3D_prefix+'\n')
pcb_color = configParser.get('PcbColor', 'pcb_color')
bklist = configParser.get('Blacklist', 'bklist')
bbox_opt = configParser.get('BoundingBox', 'bbox')
plcmnt = configParser.get('Placement', 'placement')
virtual = configParser.get('Virtual', 'virt')
exportFusing = configParser.get('ExportFuse', 'exportFusing')
min_drill_size = float(configParser.get('minimum_drill_size', 'min_drill_size'))
last_pcb_path = configParser.get('last_pcb_path', 'last_pcb_path')
last_fp_path = configParser.get('last_footprint_path', 'last_fp_path')
export2S = configParser.get('export', 'export_to_STEP')
enablematerials = configParser.get('Materials', 'mat')
if "yes" in export2S:
export_board_2step=True
else:
export_board_2step=False
if bklist.find('none') !=-1:
blacklisted_model_elements=''
elif bklist.find('volume') !=-1:
vval=bklist.strip('\r\n')
vvalue=vval.split("=")
volume_minimum=float(vvalue[1])
#reply = QtGui.QMessageBox.information(None,"info ...","volume "+str(volume_minimum))
elif bklist.find('height') !=-1:
vval=bklist.strip('\r\n')
vvalue=vval.split("=")
height_minimum=float(vvalue[1])
#reply = QtGui.QMessageBox.information(None,"info ...","height "+str(height_minimum))
else:
blacklisted_model_elements=bklist.strip('\r\n')
#say(bklist);say('\n')
blacklisted_models=blacklisted_model_elements.split(",")
#say(blacklisted_models);say('\n')
col=pcb_color.strip('\r\n')
if bbox_opt.upper().find('ALL') !=-1:
bbox_all=1
whitelisted_model_elements=''
else:
if bbox_opt.upper().find('LIST') !=-1:
bbox_list=1
whitelisted_model_elements=bbox_opt.strip('\r\n')
#whitelisted_models=whitelisted_model_elements.split(",")
if plcmnt.find('auxorigin') !=-1:
aux_orig=1
#whitelisted_model_elements=''
if plcmnt.lower().find('baseorigin') !=-1:
base_orig=1
if plcmnt.lower().find('basepoint') !=-1:
base_point=1
basepoint=plcmnt.strip('\r\n')
coords_BP=basepoint.split(";")
xp=float(coords_BP[1]);yp=float(coords_BP[2])
if plcmnt.lower().find('autoadjust') !=-1:
idf_to_origin=False
if virtual.lower().find('addvirtual') !=-1:
addVirtual=1
if exportFusing.lower().find('fuseall') !=-1:
fusion=True
if enablematerials.lower().find('enablematerials') !=-1:
enable_materials=1
say('3D models prefix='+models3D_prefix+'\rpcb color='+col+'\r')
#cfg_parameters.append(models3D_prefix)
#cfg_parameters.append(col)
say('blacklist modules '+blacklisted_model_elements+'\r')
#cfg_parameters.append(blacklisted_model_elements)
say('volume '+str(volume_minimum)+' heigh '+str(height_minimum)+'\r')
#cfg_parameters.append(volume_minimum)
say('bounding box option '+str(bbox_all)+' whitelist '+whitelisted_model_elements+'\r')
#cfg_parameters.append(bbox_all);cfg_parameters.append(whitelisted_model_elements)
say('placement board @ '+plcmnt+'\r'); say("idf_to_origin ");say(idf_to_origin);say('\n')
say('last fp path '+last_fp_path+'\r')
say('last brd path '+last_pcb_path+'\r')
#cfg_parameters.append(plcmnt);cfg_parameters.append(last_fp_path)
#cfg_parameters.append(last_pcb_path)
say('virtual models '+virtual+'\r')
say('export fusing option '+exportFusing+'\r')
#cfg_parameters.append(virtual);cfg_parameters.append(exportFusing)
say ('minimum drill size '+str(min_drill_size)+'mm\n')
say ('export to STEP '+str(export_board_2step)+'\n')
say ("materials "+str(enable_materials)+"\n")
#cfg_parameters.append(min_drill_size);
## color
#FreeCADGui.ActiveDocument.getObject("Board_outline").ShapeColor = (0.3333,0.3333,0.4980)
col= col.split(',')
colr=float(col[0]);colg=float(col[1]);colb=float(col[2])
##cfg_parameters = (models3D_prefix,blacklisted_model_elements,col,bbox,volume_minimum,height_minimum
#cfg_parameters.append(colr);cfg_parameters.append(colg);cfg_parameters.append(colb)
#return cfg_parameters
##
def shapeToMesh(shape, color, transp, mesh_deviation, scale=None):
#mesh_deviation=0.1 #the smaller the best quality, 1 coarse
#say(mesh_deviation+'\n')
mesh_data = shape.tessellate(mesh_deviation)
points = mesh_data[0]
if scale != None:
points = map(lambda p: p*scale, points)
newMesh= Mesh(points = points,
faces = mesh_data[1],
color = color, transp=transp)
return newMesh
def exportVRMLmaterials(objects, filepath):
"""Export given list of Mesh objects to a VRML file.
with material properties
`Mesh` structure is defined at root."""
global ui, creaseAngle
#material_list=["as is","metal pins","gold pins","black body","dark brown body","brown body","grey body","green body","white body","black label","white label"]
#material_properties_names=["as is","metal grey pins","gold pins","black body","resistor black body",\
# "grey body","dark grey body","brown body","light brown body","blue body",\
# "green body","orange body","pink body","yellow body","white body","light brown label",\
# "led red","led green","led blue"]
#global color_list_mat, col_index
#with __builtin__.open(filepath, 'w') as f:
with __builtin__.open(filepath, 'wb') as f:
# write the standard VRML header
f.write("#VRML V2.0 utf8\n#kicad StepUp wrl exported\n\n")
f.write(material_definitions)
color_list=[]
color_list_mat=[]
index_color=-1
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
ui.comboBox.addItems(material_properties_names)
material="as is"
for obj in objects:
if creaseAngle==0:
f.write("Shape { geometry IndexedFaceSet \n{ coordIndex [")
else:
f.write("Shape { geometry IndexedFaceSet \n{ creaseAngle %.2f coordIndex [" % creaseAngle)
# write coordinate indexes for each face
f.write(','.join("%d,%d,%d,-1" % f for f in obj.faces))
f.write("]\n") # closes coordIndex
f.write("coord Coordinate { point [")
# write coordinate points for each vertex
#f.write(','.join('%.3f %.3f %.3f' % (p.x, p.y, p.z) for p in obj.points))
f.write(','.join('%g %g %g' % (p.x, p.y, p.z) for p in obj.points))
f.write("]\n}") # closes Coordinate
#shape_col=(1.0, 0.0, 0.0)#, 0.0)
f.write("}\n") # closes points
#say(obj.color)
shape_col=obj.color[:-1] #remove last item
#say(shape_col)
if shape_col not in color_list:
pal = QtGui.QPalette()
bgc = QtGui.QColor(shape_col[0]*255,shape_col[1]*255, shape_col[2]*255)
pal.setColor(QtGui.QPalette.Base, bgc)
ui.plainTextEdit.viewport().setPalette(pal)
#ui.comboBox.clear()
color_list.append(shape_col)
index_color=index_color+1
#say(color_list)
#ui.comboBox.addItems(color_list)
if Materials:
reply=Dialog.exec_()
#Dialog.exec_()
#say(reply)
if reply==1:
material=str(ui.comboBox.currentText())
else:
material="as is"
color_list_mat.append(material)
#say(material)
#else:
#say("searching")
col_index=color_list.index(shape_col)
#say(color_list_mat[col_index])
if not Materials or color_list_mat[col_index]=="as is":
shape_transparency=obj.transp
f.write("appearance Appearance{material Material{diffuseColor %g %g %g\n" % shape_col)
f.write("transparency %g}}" % shape_transparency)
f.write("}\n") # closes Shape
else:
material_index=material_properties_names.index(color_list_mat[col_index])
#say(material_properties[material_index])
#f.write("appearance Appearance{"+material_properties[material_index]+"}}\n")
f.write("appearance Appearance{material USE "+material_ids[material_index]+" }}\n")
say(filepath+' written\n')
#color_list=[]
#color_list_mat=[]
#index_color=-1
#Dialog = QtGui.QDialog()
#ui = Ui_Dialog()
#ui.setupUi(Dialog)
#ui.comboBox.addItems(material_properties_names)
##for obj in componentObjs:
#reply=Dialog.exec_()
###
def exportVRML(objects, filepath):
"""Export given list of Mesh objects to a VRML file.
`Mesh` structure is defined at root."""
global creaseAngle
#with __builtin__.open(filepath, 'w') as f:
with __builtin__.open(filepath, 'wb') as f: