-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathf-engrave.py
9398 lines (8149 loc) · 402 KB
/
f-engrave.py
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
"""
f-engrave G-Code Generator
Copyright (C) <2011-2021> <Scorch>
Source was used from the following works:
engrave-11.py G-Code Generator -- Lawrence Glaister --
GUI framework from arcbuddy.py -- John Thornton --
cxf2cnc.py v0.5 font parsing code --- Ben Lipkowitz(fenn) --
dxf.py DXF Viewer (http://code.google.com/p/dxf-reader/)
DXF2GCODE (http://code.google.com/p/dfxf2gcode/)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
To make it a menu item in Ubuntu use the Alacarte Menu Editor and add
the command python YourPathToThisFile/ThisFilesName.py
make sure you have made the file executable by right
clicking and selecting properties then Permissions and Execute
To use with LinuxCNC see the instructions at:
http://wiki.linuxcnc.org/cgi-bin/emcinfo.pl?Simple_EMC_G-Code_Generators
Version 0.1 Initial code
Version 0.2 - Added V-Carve code
- Fixed potential inf loop
- Added pan and zoom
- Moved Font file read out of calculation loop (increased speed)
Version 0.3 - Bug fix for flip normals and flip text
- Moved depth scalar calc out of for loop
Version 0.4 - Added importing for DXF files
- Added import True Type fonts using the ttf2cxf_stream helper program
- Fixed line thickness display when zooming
Version 0.5 - Added support for more DXF entity types POLYLINE and LEADER (leaders won't have arrow heads)
- Added global accuracy setting
- Added straight line detection in v-carve output (reduces number of G1 commands and output file size)
- Improved handling of closed loops in v-carving
- Added global variable named "Zero" for non-zero checks
Version 0.6 - Added import Portable BitMap (PBM) images using Potrace as a helper program
- Default directory for opening PBM and DXF files is now set to the current font directory
- Default directory for and saving is now set to the users home directory
- Helper programs should now be found if they are in the global search path or F-Engrave
script folder (Previously the helper programs needed to be in f-engrave script folder)
Version 0.7 - Increased speed of v-carve calculation for large designs. Approximately 20 times faster now.
- Added window that displays status and contains a stop button for v-carve calculations
- Fixed display so that it no longer freezes during long calculations
- Fixed divide by zero error for certain fonts (Bug in Versions 0.5 and 0.6)
Version 0.8 - Changed interface when working with image (DXF or PBM) files.
- Added post processing logic to reduce number and distance of rapid moves
- Fixed bug in DXF code that caused failure to import some DXF files.
- Changed settings dialogs to allow recalculation and v-carving from the dialog window to preview settings
- Added some logic for determining default .ngc names and directory when saving
- Remove option for steps around corner (now internally calculated based on step length and bit geometry)
Version 0.9 - Added arc fitting to g-code output
- Fixed extended characters up to 255 (now uses numbers for the font index rather than the character)
- Added option for a second operation g-code output file to clean-up islands and adjacent areas of a v-carving
- Cleaned up some GUI bugs introduced in Version 0.8
- Remove flip border normals option
- Default to check "all" instead of current character "chr"
- Changed the percent complete calculation to use the % of the total segment length rather than the segment count
Version 0.91 - Fixed bug that caused Radius setting from text mode to affect image mode
- Fixed bug that caused some DXF files to fail erroneously
Version 0.92 - Fixed bug that caused some buttons on the v-carve setting to not show up.
Version 0.93 - Fixed bug that caused bad g-code in some cases.
Version 1.00 - Added support for DXF polyline entity "bulges" (CamBam uses polyline bulges in DXF exports)
- Modified code to be compatible with Python 3. (F-Engrave now works with Python 2.5 through 3.3)
- Removed stale references to grid the grid geometry manager
- Made minor user interface changes
Version 1.01 - Fixed bug importing text information from g-code file in Python 3
- Put additional restriction on arc fitting to prevent arcing straight lines
Version 1.02 - Put more restrictions on arc fitting to prevent huge erroneous circles
- Added key binding for CTRL-g to copy g-code to clipboard
Version 1.10 - Added Command line option to set the default directory
- Added setting option for disabling the use of variable in the g-code output
- Added option for b-carving (using a ball end mill in v-carve mode)
- Added the text to be engraved to the top of the ngc file
- Added max depth to the v-carve settings
- Eliminated failure to save g-code file when the image file name contains extended characters.
- Changed the default .ngc/.svg file name when saving. Now it always uses the base of the image file name.
- Changed the default behavior for v-carve step size. now the default in or mm value is always
reset (0.010in or 0.25mm) when switching between unit types. This will ensure that metric users
will start with a good default step size setting.
Version 1.11 - Fixed error when saving clean up g-code.
- Removed Extra spaces from beginning of g-code preamble and post-amble
- Added arc fitting to the variables that are saved to and read from the g-code output file
Version 1.12 - Added logic to add newline to g-code preamble and g-code post-amble whenever a pipe character "|" is input
Version 1.13 - Fixed bug preventing clean up tool-paths when the "Cut Depth Limit" variable is used.
Version 1.14 - Fixed bug preventing the use of the Cut Depth Limit when b-carving
- Updated website info in help menu
Version 1.20 - Added option to enable extended (Unicode) characters
- Also made a small change to the v-carve algorithm to fix a special case.
Version 1.21 - Added more command line options including a batch mode with no GUI
Version 1.22 - Fixed three bugs associated with importing dxf files
- Fixed bug associated with clean up calculations
- Changed minimum allowable line spacing from one to zero
Version 1.30 - When importing DXF files F-Engrave no longer relies on the direction of the
loop (clockwise/counter-clockwise) to determines which side to cut. Now F-Engrave
determines which loops are inside of other loops and flips the directions automatically.
- Added a new option for "V-Carve Loop Accuracy" in v-carve settings. This setting
tells F-Engrave to ignore features smaller than the set value. This allows F-Engrave
to ignore small DXF imperfections that resulted in bad tool paths.
Version 1.31 - Fixed bug that was preventing batch mode from working in V1.30
Version 1.32 - Added limit to the length of the engraved text included in g-code file
comment (to prevent error with long engraved text)
- Changed number of decimal places output when in mm mode to 3 (still 4 places for inches)
- Changed g-code format for G2/G3 arcs to center format arcs (generally preferred format)
- Hard coded G90 and G91.1 into g-code output to make sure the output will be interpreted
correctly by g-code interpreters.
Version 1.33 - Added option to scale original input image size rather than specify a image height
Version 1.34 - Eliminated G91.1 code when arc fitting is disabled. When arc fitting is disabled
the code (G91.1) is not needed and it may cause problems for interpretors that do not
support that code (i.e. ShapeOko)
Version 1.35 - Fixed importing of ellipse features from DXF files. Ellipse end overlapped the beginning
of the ellipse.
- Fixed saving long text to .ncg files. Long text was truncated when a .ngc file was opened.
Version 1.36 - Fixed major bug preventing saving .ncg files when the text was not a long string.
Version 1.37 - Added logic to ignore very small line segments that caused problems v-carving some graphic input files.
Version 1.38 - Changed default origin to the DXF input file origin when height is set by percentage of DXF image size.
Version 1.39 - Fixed bug in v-carving routine resulting in failed v-carve calculation. (Bug introduced in Version 1.37)
Version 1.40 - Added code to increased v-carving speed (based on input from geo01005)
- Windows executable file now generated from Python 2.5 with Psyco support (significant speed increase)
- Changed Default Origin behavior (for DXF/Image files) to be the origin of the DXF file or lower left
corner of the input image.
- Added automatic scaling of all linear dimensions values when changing between units (in/mm)
- Fixed bug in clean up function in the v-carve menu. (the bug resulted in excessive Z motions in some cases)
- Fixed bug resulting in the last step of v-carving for any given loop to be skipped/incorrect.
Version 1.41 - Adjusted global Zero value (previous value resulted in rounding errors in some cases)
- Removed use of accuracy (Acc) in the v-carve circle calculation
Version 1.42 - Changed default to disable variables in g-code output.
Version 1.43 - Fixed bug in v-carve cleanup routing that caused some areas to not be cleaned up.
Version 1.44 - Fixed really bad bug in v-carve cleanup for bitmap images introduced in V1.43
Version 1.45 - Added multi-pass cutting for v-carving
- Removed "Inside Corner Angle" and "Outside Corner Angle" options
Version 1.46 - Fixed bug which cause double cutting of v-carve pattern when multi-pass cutting was disabled
Version 1.47 - Added ability to read more types of DXF files (files using BLOCKS with the INSERT command)
- Fixed errors when running batch mode for v-carving.
- Added .tap to the drop down list of file extensions in the file save dialog
Version 1.48 - Fixed another bug in the multi-pass code resulting in multi-pass cutting when multi-pass cutting was disabled.
Version 1.49 - Added option to suppress option recovery comments in the g-code output
- Added button in "General Settings" to automatically save a configuration (config.ngc) file
Version 1.50 - Modified helper program (ttf2cxf_stream) and F-Engrave interaction with it to better control the line
segment approximation of arcs.
- Added straight cutter support
- Added option to create prismatic cuts (inverse of v-carve). This option opens the
possibility of making v-carve inlays.
- Fixed minor bug in the v-bit cleanup tool-path generation
- Changed the behavior when using inverting normals for v-carving. Now a box is automatically
generated to bound the cutting on the outside of the design/lettering. The size of the box is
controlled by the Box/Circle Gap setting in the general settings.
- Removed v-carve accuracy setting
- Added option for radius format g-code arcs when arc fitting. This will help compatibility
with g-code interpreters that are missing support for center format arcs.
Version 1.51 - Added Plunge feed rate setting (if set to zero the normal feed rate applies)
- Removed default coolant start/stop M codes for the header and footer
- Changed default footer to include a newline character between the M codes another Shapeoko/GRBL problem.
- Fixed some Python 3 incompatibilities with reading configuration files
Version 1.52 - Fixed potential divide by zero error in DXF reader
- Text mode now includes space for leading carriage returns (i.e. Carriage returns before text characters)
Version 1.53 - Changed space for leading carriage returns to only apply at 0,90,270 and 180 degree rotations.
- Added floating tool tips to the options on the main window (hover over the option labels to see the tool tip text)
Version 1.54 - Fixed bug that resulted in errors if the path to a file contained the text of an F-Engrave setting variable
- Reduced time to open existing g-code files by eliminating unnecessary recalculation calls.
- Added configuration variable to remember the last. Folder location used when a configuration file is saved.
- Added support for most jpg, gif, tif and png files (it is still best to use Bitmaps)
- After saving a new configuration file the settings menu will now pop back to the top (sometimes it would get buried under other windows)
- Now searches current folder and home folder for image files when opening existing g-code files.
previously the image file needed to be in the exact path location as when the file was saved
Version 1.55 - Fixed error in line/curve fitting that resulted in bad output with high Accuracy settings
- Fixed missing parentheses on file close commands (resulted in problems when using PyPy
- Suppress comments in g-code should now suppress all full line g-code comments
- Fixed error that resulted in cutting outside the lines with large Accuracy settings
Version 1.56 - Changed line/curve fitting to use Douglas-Peucker curve fitting routine originally from LinuxCNC image2gcode
- Re-enabled the use of #2 variable when engraving with variable enabled (was broken in previous version)
- Fixed SVG export (was broken in previous version)
Version 1.57 - Fixed feed rate. Changes in 1.56 resulted in feed rate not being written to g-code file.
Version 1.58 - Fixed some special cases which resulted in errors being thrown (v-carve single lines)
- Changed the default settings to be more compatible with incomplete g-code interpretors like GRBL
Version 1.59 - Fixed bug in arc fitting
- Rewrote Cleanup operation calculations (fixes a bug that resulted in some areas not being cleaned up
- Changed flip normals behavior, There are now two options: Flip Normals and Add Box (Flip Normals)
- Changed prismatic cut to allow the use of either of the two Flip normals options (one of the two
Flip normals options must be selected for the inlay cuts to be performed properly
- Added DXF Export option (with and without auto closed loops)
Version 1.60 - Fixed divide by zero error in some cleanup sceneries.
Version 1.61 - Fixed a bug that prevented opening DXF files that contain no features with positive Y coordinates
Version 1.62 - Fixed a bug that resulted in bad cleanup tool paths in some situations
Version 1.63 - Removed code that loaded _imaging module. The module is not needed
- Changed "Open F-Engrave G-Code File" "Read Settings From File"
- Added "Save Setting to File" file option in File menu
- Fixed v-bit cleanup step over. Generated step was twice the input cleanup step.
- Updated icon.
- Added console version of application to windows distribution. For batch mode in Windows.
Version 1.64 - Fixed bug that created erroneous lines in some circumstances during v-carving.
- Mapped save function to Control-S for easier g-code saving
Version 1.65 - Fixed bug in sort_for_v_carve that resulted in an error for certain designs.
Version 1.66 - Fixed a problem with the origin when wrapping text in some cases.
- Decreased number of updates while doing computations which increases overall calculation speed.
- Fixed problem that can cause the program to freeze if the saved settings contain errors.
Version 1.67 - Improved DXF import for DXF files with some incomplete data
- Fixed curve fitting upon g-code export. Limited curve fitting angle to avoid curve fitting sharp corners.
Version 1.68 - Fixed typo in code introduced in v1.67 that broke curve fitting.
Version 1.69 - A couple of minor fixes to keep things working in Python 3.x
- Added ability to disable ploting of v-carve toolpath and area
- Fixed problem causing v-carve path to go outside of design bounds for very thin design sections.
Version 1.70 - Fixed a bug introduced in V1.69 that caused v-carving cleanup calculations to fail sometimes.
Version 1.71 - Changed Potrace version that is distributed with F-Engrave from 1.10 to 1.16
- Fixed problem with cleanup cutting wrong area for some cases
Version 1.72 - Fixed a bug that resulted in bad cleanup tool paths in some situations
- Explicitly set the font for the GUI
Version 1.73 - Made importing png images with clear backgrounds work better
- Added PNG and TIF to the image file types that show up by default
Version 1.74 - Improved cleanup calculations using Pyclipper library
- Added "L" loop cleanup option for both straight and v-bit
- Started using PyPy for windows pre-compiled executable distribution
Version 1.75 - Fixed module loading problem under Linux
"""
version = '1.75'
#Setting QUIET to True will stop almost all console messages
QUIET = False
DEBUG = False
import sys
VERSION = sys.version_info[0]
if VERSION == 3:
from tkinter import *
from tkinter.filedialog import *
import tkinter.messagebox
MAXINT = sys.maxsize
else:
from Tkinter import *
from tkFileDialog import *
import tkMessageBox
MAXINT = sys.maxint
if VERSION < 3 and sys.version_info[1] < 6:
def next(item):
return item.next()
try:
import psyco
psyco.full()
except:
pass
PIL = True
if PIL == True:
try:
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
except:
PIL = False
sys.stdout.write("PIL not loaded.\n")
from math import *
from time import time
import os
import re
import binascii
import getopt
from subprocess import Popen, PIPE
if sys.platform == 'win32':
from subprocess import STARTUPINFO, STARTF_USESHOWWINDOW
import webbrowser
import struct
import pyclipper
try:
unichr
except NameError:
unichr = chr
IN_AXIS = "AXIS_PROGRESS_BAR" in os.environ
Zero = 0.00001
STOP_CALC = 0
# macOS Patch - Stephen Houser ([email protected])
# Inject system font directory and default document location
sys.argv.extend(('--fontdir', '/System/Library/Fonts', '--defdir', '~/Documents'))
# Get platform specific default font
def get_default_font_name():
from sys import platform
if platform == "linux" or platform == "linux2":
default_font_name = 'TkDefaultFont'
elif platform == "darwin":
default_font_name = 'systemSystemFont'
elif platform == "win32":
default_font_name = 'TkDefaultFont'
else:
default_font_name = 'TkDefaultFont'
return default_font_name
# Used to invole ttf2cxf_stream, when in bundle on macOS
def ttf2cxf_stream():
ttf2cxf_cmd = 'ttf2cxf_stream'
if getattr(sys, 'frozen', False):
bundle_dir = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))
ttf2cxf_cmd = os.path.join(bundle_dir, ttf2cxf_cmd)
return ttf2cxf_cmd
def potrace():
potrace_cmd = 'potrace'
if getattr(sys, 'frozen', False):
bundle_dir = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))
potrace_cmd = os.path.join(bundle_dir, potrace_cmd)
return potrace_cmd
#raw_input("PAUSED: Press ENTER to continue")
################################################################################
# Function for outputting messages to different locations #
# depending on what options are enabled #
################################################################################
def fmessage(text,newline=True):
global IN_AXIS, QUIET
if (not IN_AXIS and not QUIET):
if newline==True:
try:
sys.stdout.write(text)
sys.stdout.write("\n")
except:
pass
else:
try:
sys.stdout.write(text)
except:
pass
def message_box(title,message):
if VERSION == 3:
tkinter.messagebox.showinfo(title,message)
else:
tkMessageBox.showinfo(title,message)
pass
def message_ask_ok_cancel(title, mess):
if VERSION == 3:
result=tkinter.messagebox.askokcancel(title, mess)
else:
result=tkMessageBox.askokcancel(title, mess)
return result
################################################################################
# Debug Message Box #
################################################################################
def debug_message(message):
global DEBUG
title = "Debug Message"
if DEBUG:
if VERSION == 3:
tkinter.messagebox.showinfo(title,message)
else:
tkMessageBox.showinfo(title,message)
pass
############################################################################
# routine takes an x and a y coords and does a coordinate transformation #
# to a new coordinate system at angle from the initial coordinate system #
# Returns new x,y tuple #
############################################################################
def Transform(x,y,angle):
newx = x * cos(angle) - y * sin(angle)
newy = x * sin(angle) + y * cos(angle)
return newx,newy
############################################################################
# routine takes an sin and cos and returns the angle (between 0 and 360) #
############################################################################
def Get_Angle(s,c):
if (s >= 0.0 and c >= 0.0):
angle = degrees( acos(c) )
elif (s >= 0.0 and c < 0.0):
angle = degrees( acos(c) )
elif (s < 0.0 and c <= 0.0):
angle = 360-degrees( acos(c) )
elif (s < 0.0 and c > 0.0):
angle = 360-degrees( acos(c) )
else:
pass
if angle < 0.001 and s < 0:
angle == 360.0
if angle > 359.999 and s >= 0:
angle == 0.0
return angle
################################################################################
# This routine parses the .cxf font file and builds a font dictionary of #
# line segment strokes required to cut each character. #
# Arcs (only used in some fonts) are converted to a number of line #
# segments based on the angular length of the arc. Since the idea of #
# this font description is to make it support independent x and y scaling, #
# we do not use native arcs in the g-code. #
################################################################################
def parse(file,segarc):
font = {}
key = None
stroke_list = []
xmax, ymax = 0, 0
for text_in in file:
#print(text_in)
text = text_in+" "
# format for a typical letter (lower-case r):
# #comment, with a blank line after it
#
# [r] 3 (or "[0072] r" where 0072 is the HEX value of the character)
# L 0,0,0,6
# L 0,6,2,6
# A 2,5,1,0,90
#
end_char = len(text)
if end_char and key: #save the character to our dictionary
font[key] = Character(key)
font[key].stroke_list = stroke_list
font[key].xmax = xmax
new_cmd = re.match(r'^\[(.*)\]\s', text)
if new_cmd: #new character
key_tmp = new_cmd.group(1)
if len(new_cmd.group(1)) == 1:
key = ord(key_tmp)
else:
if len(key_tmp) == 5:
key_tmp = key_tmp[1:]
if len(key_tmp) == 4:
try:
key=int(key_tmp,16)
except:
key = None
stroke_list = []
xmax, ymax = 0, 0
continue
else:
key = None
stroke_list = []
xmax, ymax = 0, 0
continue
stroke_list = []
xmax, ymax = 0, 0
line_cmd = re.match(r'^L (.*)', text)
if line_cmd:
coords = line_cmd.group(1)
coords = [float(n) for n in coords.split(',')]
stroke_list += [Line(coords)]
xmax = max(xmax, coords[0], coords[2])
arc_cmd = re.match(r'^A (.*)', text)
if arc_cmd:
coords = arc_cmd.group(1)
coords = [float(n) for n in coords.split(',')]
xcenter, ycenter, radius, start_angle, end_angle = coords
# since font defn has arcs as ccw, we need some font foo
if ( end_angle < start_angle ):
start_angle -= 360.0
# approximate arc with line seg every "segarc" degrees
segs = int((end_angle - start_angle) / segarc)+1
angleincr = (end_angle - start_angle)/segs
xstart = cos( radians(start_angle) ) * radius + xcenter
ystart = sin( radians(start_angle) ) * radius + ycenter
angle = start_angle
for i in range(segs):
angle += angleincr
xend = cos( radians(angle) ) * radius + xcenter
yend = sin( radians(angle) ) * radius + ycenter
coords = [xstart,ystart,xend,yend]
stroke_list += [Line(coords)]
xmax = max(xmax, coords[0], coords[2])
ymax = max(ymax, coords[1], coords[3])
xstart = xend
ystart = yend
return font
################################################################################
def parse_dxf(dxf_file,segarc,new_origin=True):
# Initialize / reset
font = {}
key = None
stroke_list = []
xmax, ymax = -1e10, -1e10
xmin, ymin = 1e10, 1e10
dxf_import=DXF_CLASS()
dxf_import.GET_DXF_DATA(dxf_file,tol_deg=segarc)
dxfcoords=dxf_import.DXF_COORDS_GET(new_origin)
##save the character to our dictionary
key = ord("F")
stroke_list=[]
for line in dxfcoords:
XY=line
stroke_list += [ Line([ XY[0],XY[1],XY[2],XY[3] ]) ]
xmax=max(xmax,XY[0],XY[2])
ymax=max(ymax,XY[1],XY[3])
xmin=min(xmin,XY[0],XY[2])
ymin=min(ymin,XY[1],XY[3])
font[key] = Character(key)
font[key].stroke_list = stroke_list
font[key].xmax = xmax
font[key].ymax = ymax
font[key].xmin = xmin
font[key].ymin = ymin
return font
################################################################################
class Character:
def __init__(self, key):
self.key = key
self.stroke_list = []
def __repr__(self):
return "%%s" % (self.stroke_list)
def get_xmax(self):
try: return max([s.xmax for s in self.stroke_list[:]])
except ValueError: return 0
def get_ymax(self):
try: return max([s.ymax for s in self.stroke_list[:]])
except ValueError: return 0
def get_ymin(self):
try: return min([s.ymin for s in self.stroke_list[:]])
except ValueError: return 0
################################################################################
class Line:
def __init__(self, coords):
self.xstart, self.ystart, self.xend, self.yend = coords
self.xmax = max(self.xstart, self.xend)
self.ymax = max(self.ystart, self.yend)
self.ymin = min(self.ystart, self.yend)
def __repr__(self):
return "Line([%s, %s, %s, %s])" % (self.xstart, self.ystart, self.xend, self.yend)
################################################################################
####################################################
## PointClass from dxf2gcode_b02_point.py ##
####################################################
class PointClass:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __str__(self):
return ('X ->%6.3f Y ->%6.3f' %(self.x,self.y))
####################################################
## Begin Excerpts from dxf2gcode_b02_nurbs_calc ##
####################################################
class NURBSClass:
def __init__(self,degree=0,Knots=[],Weights=None,CPoints=None):
self.degree=degree #Spline degree
self.Knots=Knots #Knot Vector
self.CPoints=CPoints #Control points of splines [2D]
self.Weights=Weights #Weighting of the individual points
#Initializing calculated variables
self.HCPts=[] #Homogeneous points vectors [3D]
#Convert Points in Homogeneous points
self.CPts_2_HCPts()
#Creating the BSplineKlasse to calculate the homogeneous points
self.BSpline=BSplineClass(degree=self.degree,\
Knots=self.Knots,\
CPts=self.HCPts)
#Calculate a number of evenly distributed points
def calc_curve_old(self,n=0, cpts_nr=20):
#Initial values for step and u
u=0; Points=[]
step=self.Knots[-1]/(cpts_nr-1)
while u<=self.Knots[-1]:
Pt=self.NURBS_evaluate(n=n,u=u)
Points.append(Pt)
u+=step
return Points
#Calculate a number points using error limiting
def calc_curve(self,n=0, tol_deg=20):
#Initial values for step and u
u=0; Points=[]
tol = radians(tol_deg)
i=1
while self.Knots[i]==0:
i=i+1
step=self.Knots[i]/3
Pt1=self.NURBS_evaluate(n=n,u=0.0)
Points.append(Pt1)
while u<self.Knots[-1]:
if (u+step > self.Knots[-1]):
step = self.Knots[-1]-u
Pt2=self.NURBS_evaluate(n=n,u=u+step)
Pt_test=self.NURBS_evaluate(n=n,u=u + step/2)
###
DX = Pt2.x-Pt1.x
DY = Pt2.y-Pt1.y
cord = sqrt(DX*DX + DY*DY)
DXtest = Pt_test.x-(Pt1.x+Pt2.x)/2.0
DYtest = Pt_test.y-(Pt1.y+Pt2.y)/2.0
t = sqrt(DXtest*DXtest + DYtest*DYtest)
if (abs(t) > Zero):
R = (cord*cord/4 + t*t)/(2.0*t)
else:
R = 0.0
dx1 = (Pt_test.x - Pt1.x)
dy1 = (Pt_test.y - Pt1.y)
L1 = sqrt(dx1*dx1 + dy1*dy1)
dx2 = (Pt2.x - Pt_test.x)
dy2 = (Pt2.y - Pt_test.y)
L2 = sqrt(dx2*dx2 + dy2*dy2)
if L1 > Zero and L2 > Zero and R > Zero:
sin_ratio = (cord/2)/R
if abs(sin_ratio) > 1.0:
sin_ratio = round(sin_ratio,0)
sin_ratio = 0.0
angle = 2.0 * asin(sin_ratio)
else:
angle=0.0
if angle > tol:
step = step/2
else:
u+=step
Points.append(Pt2)
step = step*2
Pt1=Pt2
return Points
#Calculate a point of NURBS
def NURBS_evaluate(self,n=0,u=0):
#Calculate the homogeneous points to the n th derivative
HPt=self.BSpline.bspline_ders_evaluate(n=n,u=u)
#Point back to normal coordinates transform
Point=self.HPt_2_Pt(HPt[0])
return Point
#Convert the NURBS control points and weight in a homogeneous vector
def CPts_2_HCPts(self):
for P_nr in range(len(self.CPoints)):
HCPtVec=[self.CPoints[P_nr].x*self.Weights[P_nr],\
self.CPoints[P_nr].y*self.Weights[P_nr],\
self.Weights[P_nr]]
self.HCPts.append(HCPtVec[:])
#Convert a homogeneous vector point in a point
def HPt_2_Pt(self,HPt):
return PointClass(x=HPt[0]/HPt[-1],y=HPt[1]/HPt[-1])
class BSplineClass:
def __init__(self,degree=0,Knots=[],CPts=[]):
self.degree=degree
self.Knots=Knots
self.CPts=CPts
self.Knots_len=len(self.Knots)
self.CPt_len=len(self.CPts[0])
self.CPts_len=len(self.CPts)
# Incoming inspection, fit the upper node number, etc.
if self.Knots_len< self.degree+1:
fmessage("SPLINE: degree greater than number of control points.")
if self.Knots_len != (self.CPts_len + self.degree+1):
fmessage("SPLINE: Knot/Control Point/degree number error.")
#Modified Version of Algorithm A3.2 from "THE NURBS BOOK" pg.93
def bspline_ders_evaluate(self,n=0,u=0):
#Calculating the position of the node vector
span=self.findspan(u)
#Compute the basis function up to the n th derivative at the point u
dN=self.ders_basis_functions(span,u,n)
p=self.degree
du=min(n,p)
CK=[]
dPts=[]
for i in range(self.CPt_len):
dPts.append(0.0)
for k in range(n+1):
CK.append(dPts[:])
for k in range(du+1):
for j in range(p+1):
for i in range(self.CPt_len):
CK[k][i]+=dN[k][j]*self.CPts[span-p+j][i]
return CK
#Algorithm A2.1 from "THE NURBS BOOK" pg.68
def findspan(self,u):
#Special case when the value is == Endpoint
if(u==self.Knots[-1]):
return self.Knots_len-self.degree-2
# Binary search
# (The interval from high to low is always halved by
# [mid: mi +1] value lies between the interval of Knots)
low=self.degree
high=self.Knots_len
mid=int((low+high)/2)
while ((u<self.Knots[mid])or(u>=self.Knots[mid+1])):
if (u<self.Knots[mid]):
high=mid
else:
low=mid
mid=int((low+high)/2)
if low==high: #new
break #new
return mid
#Algorithm A2.3 from "THE NURBS BOOK" pg.72
def ders_basis_functions(self,span,u,n):
d=self.degree
#Initialize the a matrix
a=[]
zeile=[]
for j in range(d+1):
zeile.append(0.0)
a.append(zeile[:]); a.append(zeile[:])
#Initialize the ndu matrix
ndu=[]
zeile=[]
for i in range(d+1):
zeile.append(0.0)
for j in range(d+1):
ndu.append(zeile[:])
#Initialize the ders matrix
ders=[]
zeile=[]
for i in range(d+1):
zeile.append(0.0)
for j in range(n+1):
ders.append(zeile[:])
ndu[0][0]=1.0
left=[0]
right=[0]
for j in range(1,d+1):
left.append(u-self.Knots[span+1-j])
right.append(self.Knots[span+j]-u)
saved=0.0
for r in range(j):
#Lower Triangle
ndu[j][r]=right[r+1]+left[j-r]
temp=ndu[r][j-1]/ndu[j][r]
#Upper Triangle
ndu[r][j]=saved+right[r+1]*temp
saved=left[j-r]*temp
ndu[j][j]=saved
#Load the basis functions
for j in range(d+1):
ders[0][j]=ndu[j][d]
#This section computes the derivatives (Eq. [2.9])
for r in range(d+1): #Loop over function index
s1=0; s2=1 #Alternate rows in array a
a[0][0]=1.0
for k in range(1,n+1):
der=0.0
rk=r-k; pk=d-k
if(r>=k):
a[s2][0]=a[s1][0]/ndu[pk+1][rk]
der=a[s2][0]*ndu[rk][pk]
if (rk>=-1):
j1=1
else:
j1=-rk
if (r-1<=pk):
j2=k-1
else:
j2=d-r
#Here he is not in the first derivative of pure
for j in range(j1,j2+1):
a[s2][j]=(a[s1][j]-a[s1][j-1])/ndu[pk+1][rk+j]
der+=a[s2][j]*ndu[rk+j][pk]
if(r<=pk):
a[s2][k]=-a[s1][k-1]/ndu[pk+1][r]
der+=a[s2][k]*ndu[r][pk]
ders[k][r]=der
j=s1; s1=s2; s2=j #Switch rows
#Multiply through by the the correct factors
r=d
for k in range(1,n+1):
for j in range(d+1):
ders[k][j] *=r
r*=(d-k)
return ders
####################################################
## End Excerpts from dxf2gcode_b02_nurbs_calc.py ##
####################################################
class Header:
def __init__(self):
self.variables = dict()
self.last_var = None
def new_var(self, kw):
self.variables.update({kw: dict()})
self.last_var = self.variables[kw]
def new_val(self, val):
self.last_var.update({ str(val[0]) : val[1] })
class Entity:
def __init__(self, _type):
self.type = _type
self.data = dict()
def update(self, value):
key = str(value[0])
val = value[1]
if key in self.data:
if type(self.data[key]) != list:
self.data[key] = [self.data[key]]
self.data[key].append(val)
else:
self.data.update({key:val})
class Entities:
def __init__(self):
self.entities = []
self.last = None
def new_entity(self, _type):
e = Entity(_type)
self.entities.append(e)
self.last = e
def update(self, value):
self.last.update(value)
class Block:
def __init__(self, master):
self.master = master
self.data = dict()
self.entities = []
self.le = None
def new_entity(self, value):
self.le = Entity(value)
self.entities.append(self.le)
def update(self, value):
if self.le == None:
val = str(value[0])
self.data.update({val:value[1]})
if val == "2":
self.master.blocks[value[1]] = self
else:
self.le.update(value)
class Blocks:
def __init__(self):
self.blocks = dict()
self.last_var = None
def new_block(self):
b = Block(self)
self.last_block = b
self.last_var = b
def new_entity(self, value):
self.last_block.new_entity(value)
def update(self, value):
self.last_block.update(value)
class DXF_CLASS:
def __init__(self):
self.coords = []
strings = []
floats = []
ints = []
strings += list(range(0, 10)) #String (255 characters maximum; less for Unicode strings)
floats += list(range(10, 60)) #Double precision 3D point
ints += list(range(60, 80)) #16-bit integer value
ints += list(range(90,100)) #32-bit integer value
strings += [100] #String (255 characters maximum; less for Unicode strings)
strings += [102] #String (255 characters maximum; less for Unicode strings
strings += [105] #String representing hexadecimal (hex) handle value
floats += list(range(140, 148)) #Double precision scalar floating-point value
ints += list(range(170, 176)) #16-bit integer value
ints += list(range(280, 290)) #8-bit integer value
strings += list(range(300, 310)) #Arbitrary text string
strings += list(range(310, 320)) #String representing hex value of binary chunk
strings += list(range(320, 330)) #String representing hex handle value
strings += list(range(330, 369)) #String representing hex object IDs
strings += [999] #Comment (string)
strings += list(range(1000, 1010))#String (255 characters maximum; less for Unicode strings)
floats += list(range(1010, 1060)) #Floating-point value
ints += list(range(1060, 1071)) #16-bit integer value
ints += [1071] #32-bit integer value
self.funs = []
for i in range(0,1072):
self.funs.append(self.read_none)
for i in strings:
self.funs[i] = self.read_string