Repository navigation
Expand file tree
/
Copy pathgcode-viewer.html
More file actions
2715 lines (2511 loc) · 120 KB
/
Copy pathgcode-viewer.html
File metadata and controls
2715 lines (2511 loc) · 120 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>CNC Program Viewer — G-code / .anc / .xcs / .xxl</title>
<style>
:root{
--bg:#0f1420; --panel:#161d2e; --panel2:#1c2438; --border:#2a3450;
--text:#e8ecf6; --dim:#8b96b3; --accent:#4f8cff; --accent2:#39d3a7;
--danger:#ff6b6b; --rapid:#5a6478; --linear:#39d3a7; --arc:#ffb454; --drill:#ff6bcb;
}
*{box-sizing:border-box;}
html,body{height:100%;margin:0;}
body{
background:var(--bg); color:var(--text);
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
font-size:13px; display:flex; flex-direction:column; overflow:hidden;
}
header{
padding:10px 16px; border-bottom:1px solid var(--border); display:flex; align-items:center; gap:12px;
background:var(--panel); flex:0 0 auto;
}
header h1{font-size:15px; margin:0; font-weight:600;}
header .sub{color:var(--dim); font-size:12px;}
#layout{flex:1 1 auto; display:flex; min-height:0;}
#filesPanel{width:230px; flex:0 0 auto; border-right:1px solid var(--border); display:flex; flex-direction:column; background:var(--panel);}
#infoPanel{width:290px; flex:0 0 auto; border-right:1px solid var(--border); display:flex; flex-direction:column; background:var(--panel); overflow-y:auto;}
#viewerPanel{flex:1 1 auto; display:flex; flex-direction:column; min-width:0;}
#dropzone{
margin:10px; padding:16px 10px; border:2px dashed var(--border); border-radius:8px;
text-align:center; color:var(--dim); cursor:pointer; font-size:12px; transition:.15s;
}
#dropzone.drag{border-color:var(--accent); color:var(--accent); background:rgba(79,140,255,.08);}
#fileList{flex:1 1 auto; overflow-y:auto; padding:0 8px 8px;}
.fileItem{position:relative; padding:8px 26px 8px 10px; border-radius:6px; cursor:grab; margin-bottom:4px; border:1px solid transparent;}
.fileItem:hover{background:var(--panel2);}
.fileItem.active{background:rgba(79,140,255,.15); border-color:var(--accent);}
.fileItem.dragging{opacity:.4;}
.fileItem.drag-over{outline:2px dashed var(--accent); outline-offset:-2px;}
.fileItem .name{font-weight:600; font-size:12px; word-break:break-all;}
.fileItem .meta{color:var(--dim); font-size:11px; margin-top:3px;}
.fileItem .err{color:var(--danger); font-size:11px; margin-top:3px;}
.fileDeleteBtn{
position:absolute; top:6px; right:6px; background:none; border:none; color:var(--dim);
font-size:12px; cursor:pointer; padding:3px 6px; border-radius:4px; line-height:1;
}
.fileDeleteBtn:hover{color:#ff6b6b; background:rgba(255,107,107,.14);}
.fileAlertIcon{display:inline-flex; align-items:center; justify-content:center; margin-left:6px; font-size:11px;
color:#ffb454; cursor:help; vertical-align:middle;}
.fileAlertIcon.severe{color:#ff6b6b;}
#hoverTooltip{display:none; position:fixed; z-index:1000; max-width:260px; background:#10151f; color:var(--text);
border:1px solid var(--border); border-radius:6px; padding:8px 10px; font-size:11.5px; line-height:1.5;
box-shadow:0 6px 20px rgba(0,0,0,.4); pointer-events:none;}
input[type=file]{display:none;}
.badge{
display:inline-block; padding:1px 6px; border-radius:10px; font-size:9.5px; font-weight:700;
background:var(--panel2); color:var(--accent2); border:1px solid var(--border); margin-right:4px;
}
.panelHeader{padding:10px 12px; border-bottom:1px solid var(--border); font-weight:600; font-size:11px; color:var(--dim); text-transform:uppercase; letter-spacing:.04em;}
.infoBlock{padding:8px 12px; border-bottom:1px solid var(--border); font-size:12px;}
.infoRow{display:flex; justify-content:space-between; padding:2px 0; color:var(--dim);}
.infoRow span.v{color:var(--text); font-weight:600;}
.toolItem{padding:6px 12px; border-bottom:1px solid rgba(255,255,255,.03); cursor:pointer; font-size:12px;}
.toolItem:hover{background:var(--panel2);}
.toolItem.active{background:rgba(57,211,167,.12); border-left:3px solid var(--accent2);}
.toolItem .tname{font-weight:600;}
.toolItem .tmeta{color:var(--dim); font-size:11px;}
.partOps{padding-left:10px; background:rgba(0,0,0,.15); display:none;}
.partHeader.stacked{background:rgba(255,107,107,.08); border-left:3px solid #ff6b6b;}
.partHeader.stacked:hover{background:rgba(255,107,107,.15);}
.partHeader.stacked.active{background:rgba(255,107,107,.2);}
.opItem .tname{font-size:11.5px;}
.hidden{display:none !important;}
.auditItem{position:relative; margin:8px 10px; padding:10px 12px; border-radius:6px; cursor:pointer; font-size:12px;
background:rgba(255,180,84,.07); border:1px solid rgba(255,180,84,.32); border-left:4px solid #ffb454;}
.auditItem:hover{background:rgba(255,180,84,.13);}
.auditItem.sev-review{background:rgba(255,107,107,.08); border-color:rgba(255,107,107,.35); border-left-color:#ff6b6b;}
.auditItem.sev-review:hover{background:rgba(255,107,107,.14);}
.auditItem.active{outline:2px solid var(--accent); outline-offset:-1px;}
.auditItem.applied{opacity:.55; background:rgba(57,211,167,.06); border-color:rgba(57,211,167,.3); border-left-color:var(--accent2);}
.auditItem.none{background:none; border:none; padding:8px 12px; cursor:default;}
.auditItem .aTop{display:flex; align-items:center; gap:6px; font-weight:600;}
.auditItem .atitle{color:var(--text);}
.auditItem .abadge{display:inline-block; font-size:9.5px; font-weight:700; padding:1px 6px; border-radius:10px; text-transform:uppercase; letter-spacing:.03em; flex:0 0 auto;}
.abadge.fix{background:rgba(57,211,167,.18); color:var(--accent2);}
.abadge.review{background:rgba(255,107,107,.2); color:#ff8080;}
.auditItem .tline{color:var(--dim); font-size:11px; margin-top:4px;}
.auditItem .aRow{display:flex; align-items:center; justify-content:space-between; gap:10px; margin-top:8px;}
.auditItem label{display:flex; align-items:center; gap:6px; cursor:pointer; font-size:11.5px;}
.auditItem .aApplyBtn{font-size:11px; padding:3px 10px; border-radius:4px; border:1px solid var(--accent); background:rgba(79,140,255,.1); color:var(--accent); cursor:pointer;}
.auditItem .aApplyBtn:hover{background:rgba(79,140,255,.22);}
.auditItem .aApplyBtn:disabled{opacity:.5; cursor:default;}
#auditControlsRow{display:flex; gap:8px; padding:8px 12px 0;}
#auditControlsRow button{flex:1; font-size:11.5px; padding:6px;}
#auditDownloadRow{padding:6px 12px 12px;}
#auditDownloadBtn.primary{width:100%; background:var(--accent2); color:#04231b; font-weight:700; border:none; padding:9px; border-radius:6px; cursor:pointer; font-size:12.5px;}
#auditDownloadBtn.primary:hover{opacity:.9;}
.note{font-size:11px; color:var(--dim); line-height:1.5; margin-top:8px;}
#resumeSectionEl select{width:100%; background:var(--panel2); color:var(--text); border:1px solid var(--border); border-radius:6px; padding:6px; font-size:12px; margin-bottom:8px;}
#resumeSectionEl button{width:100%;}
.codeLine.removed{text-decoration:line-through; color:#ff8080; background:rgba(255,80,80,.08);}
#helpBtn{
margin-left:auto; background:var(--panel2); border:1px solid var(--border); color:var(--text);
border-radius:6px; padding:5px 12px; cursor:pointer; font-size:12px; flex:0 0 auto;
}
#helpBtn:hover{border-color:var(--accent);}
.modalOverlay{position:fixed; inset:0; background:rgba(6,9,16,.65); display:flex; align-items:center; justify-content:center; z-index:2000;}
.modalOverlay.hidden{display:none;}
.modalCard{
background:var(--panel); border:1px solid var(--border); border-radius:10px;
width:min(720px, 92vw); max-height:85vh; display:flex; flex-direction:column;
box-shadow:0 20px 60px rgba(0,0,0,.5);
}
.modalCard .modalHeaderRow{display:flex; align-items:center; justify-content:space-between; padding:14px 20px; border-bottom:1px solid var(--border); flex:0 0 auto;}
.modalCard .modalHeaderRow h2{margin:0; font-size:15px;}
.modalCard .modalCloseBtn{background:none; border:none; color:var(--dim); font-size:20px; cursor:pointer; line-height:1; padding:2px 6px;}
.modalCard .modalCloseBtn:hover{color:var(--text);}
.modalBody{padding:8px 20px 20px; overflow-y:auto; font-size:12.5px; line-height:1.65;}
.modalBody h3{font-size:13.5px; margin:22px 0 8px; color:var(--text); border-bottom:1px solid var(--border); padding-bottom:6px;}
.modalBody h3:first-child{margin-top:8px;}
.modalBody h4{font-size:12.5px; margin:16px 0 6px; color:var(--accent2);}
.modalBody p{margin:8px 0; color:var(--text);}
.modalBody ul, .modalBody ol{margin:8px 0; padding-left:22px;}
.modalBody li{margin:5px 0;}
.modalBody code{background:var(--panel2); border:1px solid var(--border); border-radius:4px; padding:1px 5px; font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:11.5px;}
.modalBody table{border-collapse:collapse; width:100%; margin:10px 0; font-size:11.5px;}
.modalBody th, .modalBody td{border:1px solid var(--border); padding:6px 8px; text-align:left; vertical-align:top;}
.modalBody th{background:var(--panel2); color:var(--dim); font-weight:600;}
.modalBody strong{color:var(--text);}
#toolbar{display:flex; align-items:center; gap:14px; padding:8px 14px; border-bottom:1px solid var(--border); background:var(--panel); flex-wrap:wrap;}
#toolbar label{display:flex; align-items:center; gap:5px; color:var(--dim); font-size:12px; cursor:pointer;}
#toolbar button{
background:var(--panel2); border:1px solid var(--border); color:var(--text); border-radius:6px;
padding:5px 10px; cursor:pointer; font-size:12px;
}
#toolbar button:hover{border-color:var(--accent);}
#zoomLabel{color:var(--dim); font-size:12px; margin-left:auto;}
.legendDot{display:inline-block; width:9px; height:9px; border-radius:2px; margin-right:4px;}
#canvasWrap{flex:1 1 auto; position:relative; min-height:0; min-width:0; background:#0b101a;}
#canvas{width:100%; height:100%; display:block; cursor:grab;}
#canvas.grabbing{cursor:grabbing;}
#hoverInfo{
position:absolute; top:8px; left:8px; background:rgba(22,29,46,.9); border:1px solid var(--border);
border-radius:6px; padding:6px 10px; font-size:11px; color:var(--dim); pointer-events:none;
}
#scrubRow{display:flex; align-items:center; gap:10px; padding:8px 14px; border-top:1px solid var(--border); background:var(--panel); flex:0 0 auto;}
#scrubRow input[type=range]{flex:1;}
#scrubLabel{color:var(--accent2); font-size:12px; min-width:170px; text-align:right; font-variant-numeric:tabular-nums;}
#viewerBody{flex:1 1 auto; display:flex; min-height:0; min-width:0;}
#viewerBody.mode-bottom{flex-direction:column;}
#viewerBody.mode-right{flex-direction:row;}
#resizeHandle{background:var(--border); flex:0 0 auto; position:relative; z-index:2;}
#resizeHandle:hover, #resizeHandle.active{background:var(--accent);}
#viewerBody.mode-bottom #resizeHandle{height:6px; width:100%; cursor:ns-resize;}
#viewerBody.mode-right #resizeHandle{width:6px; height:100%; cursor:ew-resize;}
#viewerBody.mode-bottom #codePanelWrap{width:100%;}
#viewerBody.mode-right #codePanelWrap{height:100%;}
#codePanelWrap{flex:0 0 auto; display:flex; flex-direction:column; min-height:0; min-width:0; border-top:1px solid var(--border); background:#0c111c;}
#viewerBody.mode-right #codePanelWrap{border-top:none; border-left:1px solid var(--border);}
#codePanel{flex:1 1 auto; overflow-y:auto; font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:11.5px;}
#codeSearchBar{display:flex; align-items:center; gap:6px; padding:6px 8px; border-bottom:1px solid var(--border); background:var(--panel); flex:0 0 auto;}
#codeSearchBar input{flex:1 1 auto; min-width:0; background:var(--panel2); border:1px solid var(--border); color:var(--text); border-radius:5px; padding:4px 8px; font-size:11.5px;}
#codeSearchBar input:focus{outline:none; border-color:var(--accent);}
#codeSearchCount{color:var(--dim); font-size:10.5px; white-space:nowrap; min-width:34px; text-align:center; flex:0 0 auto;}
#codeSearchBar button{background:var(--panel2); border:1px solid var(--border); color:var(--text); border-radius:5px; padding:3px 7px; font-size:10.5px; cursor:pointer; line-height:1; flex:0 0 auto;}
#codeSearchBar button:hover{border-color:var(--accent);}
#codeSearchBar button:disabled{opacity:.4; cursor:default;}
#codeSearchBar button:disabled:hover{border-color:var(--border);}
.codeLine{display:flex; padding:1px 12px; white-space:pre; cursor:pointer;}
.codeLine.searchMatch{background:rgba(255,180,84,.16);}
.codeLine.searchActive{background:rgba(255,180,84,.42) !important; outline:1px solid #ffb454; outline-offset:-1px;}
.codeLine .ln{color:var(--dim); width:44px; flex:0 0 auto; text-align:right; margin-right:10px; user-select:none;}
.codeLine.current{background:rgba(79,140,255,.18);}
.codeLine.past{opacity:.45;}
.codeLine:hover{background:rgba(255,255,255,.04);}
#empty{flex:1; display:flex; align-items:center; justify-content:center; color:var(--dim); text-align:center; padding:40px;}
#empty .big{font-size:15px; margin-bottom:8px;}
::-webkit-scrollbar{width:8px; height:8px;}
::-webkit-scrollbar-thumb{background:var(--border); border-radius:4px;}
</style>
</head>
<body>
<header>
<h1>CNC Program Viewer</h1>
<span class="sub">Drop Fanuc .anc/.nc/.tap/.gcode files, Biesse/Maestro .xcs scripts, or SCM Xilog+ .xxl programs — parsed and rendered entirely in your browser</span>
<button id="helpBtn" title="How to use this tool">? Help</button>
</header>
<div id="helpModal" class="modalOverlay hidden">
<div class="modalCard">
<div class="modalHeaderRow">
<h2>CNC Program Viewer — Help</h2>
<button id="helpCloseBtn" class="modalCloseBtn" title="Close">✕</button>
</div>
<div class="modalBody">
<p>A single-file, browser-based viewer for CNC toolpath programs. Drop in a file and it parses, renders, and lets you step through the program — no install, no server, nothing leaves your browser.</p>
<h3>Supported formats</h3>
<table>
<thead><tr><th>Format</th><th>Typical extensions</th><th>Notes</th></tr></thead>
<tbody>
<tr><td>Fanuc-style G-code</td><td><code>.anc</code>, <code>.nc</code>, <code>.tap</code>, <code>.gcode</code>, <code>.txt</code>, <code>.ncf</code>, <code>.cnc</code></td><td>G0/G1/G2/G3, R- and I/J-based arcs, G41/G42 cutter compensation, tool changes</td></tr>
<tr><td>Biesse / Maestro</td><td><code>.xcs</code></td><td>Scripted CAM format (<code>CreatePolyline</code>, <code>CreateRoughFinish</code>, <code>CreateDrill</code>, <code>CreatePart</code>, etc.)</td></tr>
<tr><td>SCM Xilog+</td><td><code>.xxl</code></td><td>SCM router post format</td></tr>
<tr><td>ISO-ESAGV</td><td><code>.i00</code></td><td>Same G-code vocabulary as Fanuc, but with absolute (not relative) I/J arc centers</td></tr>
</tbody>
</table>
<p>The format is auto-detected from file contents — you don't need to pick it manually.</p>
<h3>Getting started</h3>
<ol>
<li>Open <code>gcode-viewer.html</code> in any modern browser (double-click it, or host it somewhere and open the URL).</li>
<li>Drag one or more program files onto the drop zone, or click it to browse. You can load several files at once and switch between them in the left-hand file list.</li>
<li>The first successfully-parsed file is opened automatically.</li>
</ol>
<h3>Layout</h3>
<ul>
<li><strong>Files panel (far left)</strong> — every loaded file, with a size/format badge. Files with audit problems show a warning icon — hover it for a summary. Drag a file to reorder the list, or click its ✕ to remove it.</li>
<li><strong>Info panel</strong> — job/panel details (material, panel size, origin), program stats (counts, ranges), and either a <strong>Tool changes</strong> list (G-code/Xilog/ESAGV) or a <strong>Parts</strong> list (xcs).</li>
<li><strong>Viewer</strong> — the toolpath itself, plus a synced code panel showing the raw file.</li>
</ul>
<h3>Viewing the toolpath</h3>
<ul>
<li><strong>Fit to view</strong> re-centers and re-scales the drawing.</li>
<li><strong>Scrub slider + Play</strong> animate the program move-by-move; the code panel highlights the current line and scrolls to follow.</li>
<li>Click anywhere in the <strong>code panel</strong> to jump the viewer to that line.</li>
<li><strong>Code panel: Bottom / Right</strong> toggles whether the code panel docks under or beside the canvas; drag the divider between them to resize.</li>
<li><strong>Show rapids</strong> toggles whether rapid (non-cutting) travel moves are drawn.</li>
<li>Mouse wheel to zoom, click-drag to pan.</li>
</ul>
<h4>Searching the code panel</h4>
<p>The search bar docked above the code panel highlights every line containing your text as you type (case-insensitive). Use the ▲/▼ buttons — or <code>Enter</code> / <code>Shift+Enter</code> right from the input — to step to the next or previous match, with a counter showing your position (e.g. <code>3 / 12</code>). <code>Escape</code> or the ✕ button clears the search.</p>
<h4>Parts list (xcs files)</h4>
<p>For Maestro <code>.xcs</code> files, the secondary panel lists every part on the sheet instead of tool changes:</p>
<ul>
<li>Click a part to highlight it, zoom the viewer to just that part, and jump the code panel to that part's line.</li>
<li><strong>◀ Part / Part ▶</strong> buttons in the toolbar step through parts one at a time (wraps around at either end) — handy for reviewing a whole nest without hunting through the list.</li>
<li>Expand a part to see its individual operations (drills, routing passes) and jump straight to the line that produces each one.</li>
<li><strong>Stacked-part alert:</strong> if two parts occupy essentially the same footprint (≥95% of each other's bounding-box area) — almost always a duplicate or mis-nested part rather than normal edge-to-edge nesting — both are highlighted in red with a warning icon. Hover the icon to see which part(s) it overlaps.</li>
</ul>
<h3>Corner & compensation audit (G-code / ISO-ESAGV)</h3>
<p>For Fanuc-style and ISO-ESAGV files, the info panel includes an audit of geometry that's known to break cutter-radius compensation (G41/G42) mid-cut:</p>
<ul>
<li><strong>Colinear runs</strong> — a string of points that are effectively one straight line, split across multiple G-code blocks. These collapse safely into a single segment with no path change, and are marked <strong>auto-fix</strong>.</li>
<li><strong>Short-sharp segments</strong> — a segment shorter than the currently-active tool radius sitting at a real corner. These can't be resolved automatically and are marked <strong>review</strong> for you to inspect manually.</li>
</ul>
<p>Each finding is its own card. You can:</p>
<ul>
<li><strong>Apply this fix</strong> on an individual card, or check several and use <strong>Apply selected</strong> (there's also a <strong>Check all</strong> button).</li>
<li>Once at least one fix has been applied, a <strong>Download fixed file</strong> button appears — it downloads a new file with only the confirmed lines removed. The originally-loaded file is never modified; applied fixes are shown as struck-through lines in the code panel so you can compare before/after.</li>
</ul>
<h4>Resume export</h4>
<p>Also under the audit section: pick a tool change and an operation from the dropdowns, then <strong>Export from selected operation</strong> to download a version of the file that replays that tool's setup (tool change, spindle start, length offset) and then jumps straight to the chosen operation — for restarting a job partway through a sheet without re-running everything from the top. Nothing is recalculated; only existing lines are kept or skipped. Always review the exported file before running it on a machine.</p>
<h3>Nesting-label export (xcs only)</h3>
<p>Maestro files place a <code>SetNestingPartLabel(...)</code> call per part to auto-print a label. If you need the controller to skip that (e.g. pre-printed labels, or a different labeling workflow), the <strong>Nesting labels</strong> section provides a one-click <strong>Comment out N label lines & download</strong> button. It prefixes every <code>SetNestingPartLabel</code> line with <code>//</code> and downloads a new file — again, without touching the loaded original.</p>
<h3>A note on safety</h3>
<p>This tool only reads and displays files, and any "fix" or "export" action produces a <strong>new</strong> downloaded file — it never overwrites what you loaded. That said, this is machine-facing G-code: always review a modified/exported file yourself before sending it to a controller.</p>
</div>
</div>
</div>
<div id="layout">
<div id="filesPanel">
<div id="dropzone">Drag & drop program files here<br>or click to browse<br><span style="opacity:.6">.anc .nc .tap .gcode .xcs .xxl .i00</span></div>
<input type="file" id="fileInput" multiple accept=".anc,.nc,.tap,.gcode,.txt,.ncf,.cnc,.xcs,.xxl,.i00" />
<div id="fileList"></div>
</div>
<div id="infoPanel" style="display:none;">
<div class="panelHeader">Job & panel</div>
<div class="infoBlock" id="headerBlock"></div>
<div class="panelHeader">Program info</div>
<div class="infoBlock" id="statsBlock"></div>
<div class="panelHeader" id="secondaryHeader">Tool changes</div>
<div id="toolListEl"></div>
<div class="panelHeader" id="labelHeader" style="display:none;">Nesting labels</div>
<div id="labelSectionEl" style="display:none; padding:10px 12px;"></div>
<div class="panelHeader" id="auditHeader" style="display:none;">Corner & compensation audit</div>
<div class="infoBlock" id="auditSummary" style="display:none;"></div>
<div id="auditControlsRow" class="hidden">
<button id="auditCheckAllBtn">Check all</button>
<button id="auditApplySelectedBtn" disabled>Apply selected</button>
</div>
<div id="auditListEl"></div>
<div id="auditDownloadRow" class="hidden">
<button id="auditDownloadBtn" class="primary">Download fixed file</button>
<div class="note">Original file is untouched — this downloads a new copy with only the applied fixes removed.</div>
</div>
<div class="panelHeader" id="resumeHeader" style="display:none;">Resume export (skip already-cut ops)</div>
<div id="resumeSectionEl" style="display:none; padding:10px 12px;"></div>
</div>
<div id="viewerPanel">
<div id="empty">
<div>
<div class="big">No program loaded yet</div>
<div>Drop one or more program files on the left to preview a toolpath.</div>
</div>
</div>
</div>
</div>
<script>
const state = {
files: [],
activeFileId: null,
view: { scale: 1, offsetX: 0, offsetY: 0 },
scrub: 0,
playing: false,
playTimer: null,
selectedPartId: null,
codePanelMode: 'bottom',
codePanelSize: 190,
};
loadLayoutPrefs();
const dropzone = document.getElementById('dropzone');
const fileInput = document.getElementById('fileInput');
const fileListEl = document.getElementById('fileList');
const infoPanel = document.getElementById('infoPanel');
const headerBlock = document.getElementById('headerBlock');
const statsBlock = document.getElementById('statsBlock');
const toolListEl = document.getElementById('toolListEl');
const viewerPanel = document.getElementById('viewerPanel');
// ---------- Help modal wiring ----------
const helpModal = document.getElementById('helpModal');
document.getElementById('helpBtn').addEventListener('click', ()=> helpModal.classList.remove('hidden'));
document.getElementById('helpCloseBtn').addEventListener('click', ()=> helpModal.classList.add('hidden'));
helpModal.addEventListener('click', e=>{ if(e.target === helpModal) helpModal.classList.add('hidden'); });
window.addEventListener('keydown', e=>{ if(e.key === 'Escape' && !helpModal.classList.contains('hidden')) helpModal.classList.add('hidden'); });
// ---------- Drag & drop wiring ----------
['dragenter','dragover'].forEach(evt=>{
window.addEventListener(evt, e=>{ e.preventDefault(); dropzone.classList.add('drag'); });
});
['dragleave','drop'].forEach(evt=>{
window.addEventListener(evt, e=>{ e.preventDefault(); if(evt==='drop' || e.target===document.documentElement) dropzone.classList.remove('drag'); });
});
window.addEventListener('drop', e=>{
e.preventDefault();
dropzone.classList.remove('drag');
const dt = e.dataTransfer;
if(dt && dt.files && dt.files.length) handleFiles(dt.files);
});
dropzone.addEventListener('click', ()=> fileInput.click());
fileInput.addEventListener('change', e=>{
if(e.target.files && e.target.files.length) handleFiles(e.target.files);
fileInput.value = '';
});
let fileCounter = 0;
async function handleFiles(fileList){
for(const f of Array.from(fileList)){
const id = 'f' + (fileCounter++);
const entry = { id, name: f.name, size: f.size, error: null, program: null, text: null, issues: null, auditActiveIssueId: null };
state.files.push(entry);
renderFileList();
try{
const text = await f.text();
entry.text = text;
const fmt = detectFormat(text);
entry.program = fmt === 'xcs' ? parseXCS(text) : (fmt === 'xilog' ? parseXilog(text) : (fmt === 'esagv' ? parseEsagv(text) : parseGcode(text)));
ensureAuditIssues(entry);
}catch(err){
console.error(err);
entry.error = (err && err.message) ? err.message : String(err);
}
renderFileList();
if(!state.activeFileId && entry.program) selectFile(id);
}
}
function detectFormat(text){
if(/CreateFinishedWorkpieceBox\s*\(/.test(text) || /SetMachiningParameters\s*\(/.test(text)) return 'xcs';
if(/^H\s+DX=/m.test(text) || /\bXL2P\b/.test(text) || /\bFINEPROG\b/.test(text)) return 'xilog';
if(/ISO-ESAGV/i.test(text) || /\?%E[TO]K\[/.test(text)) return 'esagv';
return 'gcode';
}
// ============================================================
// SHARED GEOMETRY HELPERS
// ============================================================
function arcCenterFromRadius(x1,y1,x2,y2,r,cw){
const dx = x2-x1, dy = y2-y1;
const d = Math.sqrt(dx*dx+dy*dy);
if(d === 0) return null;
const rr = Math.abs(r);
let h2 = rr*rr - (d/2)*(d/2);
if(h2 < 0) h2 = 0;
const h = Math.sqrt(h2);
const mx = (x1+x2)/2, my = (y1+y2)/2;
const ux = -dy/d, uy = dx/d;
let sign;
if(cw) sign = (r>=0) ? -1 : 1;
else sign = (r>=0) ? 1 : -1;
return { cx: mx + sign*ux*h, cy: my + sign*uy*h };
}
function arcPoints(x1,y1,x2,y2,cx,cy,cw){
const r = Math.hypot(x1-cx, y1-cy);
let a1 = Math.atan2(y1-cy, x1-cx);
let a2 = Math.atan2(y2-cy, x2-cx);
let sweep;
if(cw){
sweep = a1 - a2;
if(sweep < 0) sweep += Math.PI*2;
} else {
sweep = a2 - a1;
if(sweep < 0) sweep += Math.PI*2;
}
if(sweep < 1e-9) sweep = Math.PI*2; // full circle case
const n = Math.max(2, Math.ceil(sweep / (Math.PI/24)));
const pts = [];
for(let i=0;i<=n;i++){
const t = i/n;
const angle = cw ? (a1 - sweep*t) : (a1 + sweep*t);
pts.push({ x: cx + r*Math.cos(angle), y: cy + r*Math.sin(angle) });
}
pts[pts.length-1] = { x: x2, y: y2 };
return pts;
}
// Endpoint + radius + two flags -> arc points, using the standard SVG elliptical-arc
// endpoint-to-center parameterization (circular case, no rotation). The flag mapping
// (largeArcFlag = !rawFlagA, sweepFlag = rawFlagB) was determined empirically by
// checking tangent-continuity at real arc-to-arc junctions in sample .xcs files —
// with this mapping, adjoining arcs blend to within ~0.02 degrees; the naive
// (largeArcFlag=rawFlagA, sweepFlag=rawFlagB) mapping produces ~125 degree kinks.
function svgArcPoints(x1,y1,x2,y2,r,largeArcFlag,sweepFlag){
const x1p = (x1-x2)/2, y1p = (y1-y2)/2;
let num = r*r - x1p*x1p - y1p*y1p;
if(num < 0) num = 0;
const denom = x1p*x1p + y1p*y1p;
let co = denom > 0 ? Math.sqrt(num/denom) : 0;
if(largeArcFlag === sweepFlag) co = -co;
const cxp = co*y1p, cyp = -co*x1p;
const cx = cxp + (x1+x2)/2, cy = cyp + (y1+y2)/2;
const theta1 = Math.atan2(y1-cy, x1-cx);
const theta2 = Math.atan2(y2-cy, x2-cx);
let dTheta = theta2 - theta1;
if(!sweepFlag && dTheta > 0) dTheta -= Math.PI*2;
if(sweepFlag && dTheta < 0) dTheta += Math.PI*2;
const n = Math.max(2, Math.ceil(Math.abs(dTheta) / (Math.PI/24)));
const pts = [];
for(let i=0;i<=n;i++){
const t = i/n;
const ang = theta1 + dTheta*t;
pts.push({ x: cx + r*Math.cos(ang), y: cy + r*Math.sin(ang) });
}
pts[pts.length-1] = { x: x2, y: y2 };
return pts;
}
function pointInPolygon(pt, poly){
let inside = false;
for(let i=0,j=poly.length-1;i<poly.length;j=i++){
const xi=poly[i].x, yi=poly[i].y, xj=poly[j].x, yj=poly[j].y;
const intersect = ((yi>pt.y)!==(yj>pt.y)) && (pt.x < (xj-xi)*(pt.y-yi)/((yj-yi)||1e-12)+xi);
if(intersect) inside = !inside;
}
return inside;
}
function pointToSegDist(px,py,x1,y1,x2,y2){
const dx=x2-x1, dy=y2-y1;
const len2 = dx*dx+dy*dy;
let t = len2>0 ? ((px-x1)*dx+(py-y1)*dy)/len2 : 0;
t = Math.max(0, Math.min(1,t));
const cx=x1+t*dx, cy=y1+t*dy;
return Math.hypot(px-cx, py-cy);
}
function minDistToPolygon(pt, poly){
let mn = Infinity;
for(let i=0,j=poly.length-1;i<poly.length;j=i++){
mn = Math.min(mn, pointToSegDist(pt.x,pt.y, poly[j].x,poly[j].y, poly[i].x,poly[i].y));
}
return mn;
}
function assignPart(pt, parts){
let best=null, bestScore=Infinity;
for(const part of parts){
const inside = pointInPolygon(pt, part.points);
const score = inside ? -1 : minDistToPolygon(pt, part.points);
if(score < bestScore){ bestScore = score; best = part; }
}
return best;
}
function partLabel(part){
const m = String(part.id).match(/(\d+)\s*$/);
return m ? 'Part ' + m[1] : part.id;
}
function mmIn(mm){
return mm.toFixed(2) + ' mm (' + (mm/25.4).toFixed(2) + ' in)';
}
function partBBox(part){
const xs = part.points.map(p=>p.x), ys = part.points.map(p=>p.y);
const minX = Math.min(...xs), maxX = Math.max(...xs), minY = Math.min(...ys), maxY = Math.max(...ys);
return { minX, maxX, minY, maxY, width: maxX-minX, height: maxY-minY };
}
// Flags parts that occupy essentially the SAME footprint — i.e. the overlap
// covers nearly all of BOTH parts' bounding-box area, not just a shared edge
// or a fraction of one part. This is meant to catch true duplicate/stacked
// placements (two parts nested directly on top of each other), not normal
// edge-to-edge nesting where parts merely touch or partially overlap.
// Returns { partId: [otherPart, ...] }.
function computeStackedPartInfo(program){
const parts = program.parts || [];
const bboxes = parts.map(p=>partBBox(p));
const overlapsOf = {};
const IDENTICAL_OVERLAP_THRESHOLD = 0.95; // fraction of EACH part's area that must be covered
for(let i=0;i<parts.length;i++){
for(let j=i+1;j<parts.length;j++){
const a = bboxes[i], b = bboxes[j];
const ox = Math.min(a.maxX,b.maxX) - Math.max(a.minX,b.minX);
const oy = Math.min(a.maxY,b.maxY) - Math.max(a.minY,b.minY);
if(ox <= 0 || oy <= 0) continue;
const overlapArea = ox*oy;
const areaA = a.width*a.height, areaB = b.width*b.height;
if(areaA <= 0 || areaB <= 0) continue;
const fracOfA = overlapArea/areaA;
const fracOfB = overlapArea/areaB;
if(Math.min(fracOfA, fracOfB) > IDENTICAL_OVERLAP_THRESHOLD){
(overlapsOf[parts[i].id] = overlapsOf[parts[i].id] || []).push(parts[j]);
(overlapsOf[parts[j].id] = overlapsOf[parts[j].id] || []).push(parts[i]);
}
}
}
return overlapsOf;
}
// ============================================================
// G-CODE PARSER (Fanuc-style .anc/.nc/.tap/.gcode)
// ============================================================
function parseGcode(text, opts){
opts = opts || {};
const lines = text.split(/\r\n|\r|\n/);
const modal = {
units: 'mm',
distance: 'abs', // G90 / G91
motion: null, // 'rapid' | 'linear' | 'arcCW' | 'arcCCW'
};
let pos = { x: 0, y: 0, z: 0 };
const moves = []; // one entry per motion line that actually moves something
const toolChanges = []; // { lineNo, tool, label }
const events = []; // misc informational events (work offsets, program stop/end)
let lastComment = null;
let minX=Infinity, maxX=-Infinity, minY=Infinity, maxY=-Infinity;
let rapidCount=0, linearCount=0, arcCount=0;
let pendingToolLine = null;
let originCode = null; // first G54-G59 work offset encountered
const wordRe = /([A-Za-z])\s*(-?\d*\.?\d+)/g;
// Header metadata is typically emitted as boilerplate comments near the top of the
// file, e.g.:
// (------- MATERIAL NAME: 0.75 Plum Creek MDF 4x8 -------)
// (PANEL LENGTH: 1058.0675 PANEL WIDTH: 301.8231 PANEL THICKNESS: 19.0500)
// (JOB NAME: WOOD-100 KITCHEN AND ISLAND WOOD-100 7_20_2026 0436PM)
const materialMatch = text.match(/MATERIAL NAME:\s*([^\r\n-]+?)\s*-{2,}/i) || text.match(/MATERIAL NAME:\s*([^\r\n)]+)/i);
const panelMatch = text.match(/PANEL LENGTH:\s*([\d.]+)\s*PANEL WIDTH:\s*([\d.]+)\s*PANEL THICKNESS:\s*([\d.]+)/i);
const jobMatch = text.match(/JOB NAME:\s*([^\r\n)]+)/i);
for(let li=0; li<lines.length; li++){
const lineNo = li+1;
let raw = lines[li];
if(raw == null) continue;
// pull out parenthetical comments
let comment = null;
const commentMatch = raw.match(/\(([^)]*)\)/);
if(commentMatch) comment = commentMatch[1].trim();
let code = raw.replace(/\([^)]*\)/g, '');
// semicolon comments
const semi = code.indexOf(';');
if(semi >= 0){ if(!comment) comment = code.slice(semi+1).trim(); code = code.slice(0, semi); }
code = code.trim();
if(comment && code === ''){
lastComment = comment; // pure comment-only line: remember for the next tool/op line
}
if(code === ''){ continue; }
// collect words
const words = [];
let m;
wordRe.lastIndex = 0;
while((m = wordRe.exec(code)) !== null){
words.push({ letter: m[1].toUpperCase(), value: parseFloat(m[2]) });
}
if(!words.length) continue;
let gCodes = [];
let mCodes = [];
let X=null, Y=null, Z=null, I=null, J=null, K=null, R=null, T=null, F=null;
let hasHome = false;
for(const w of words){
switch(w.letter){
case 'G': gCodes.push(w.value); break;
case 'M': mCodes.push(w.value); break;
case 'X': X = w.value; break;
case 'Y': Y = w.value; break;
case 'Z': Z = w.value; break;
case 'I': I = w.value; break;
case 'J': J = w.value; break;
case 'K': K = w.value; break;
case 'R': R = w.value; break;
case 'T': T = w.value; break;
case 'F': F = w.value; break;
default: break;
}
}
for(const g of gCodes){
if(g === 20) modal.units = 'in';
else if(g === 21) modal.units = 'mm';
else if(g === 90) modal.distance = 'abs';
else if(g === 91) modal.distance = 'incr';
else if(g === 0) modal.motion = 'rapid';
else if(g === 1) modal.motion = 'linear';
else if(g === 2) modal.motion = 'arcCW';
else if(g === 3) modal.motion = 'arcCCW';
else if(g === 28) hasHome = true;
else if(g >= 54 && g <= 59){
events.push({ lineNo, type:'offset', text:'G'+g+' work offset selected' });
if(originCode === null) originCode = g;
}
}
for(const mc of mCodes){
if(mc === 6){ pendingToolLine = { lineNo, comment }; }
else if(mc === 0){ events.push({ lineNo, type:'stop', text:'M00 program stop' + (comment?(' — '+comment):'') }); }
else if(mc === 1){ events.push({ lineNo, type:'stop', text:'M01 optional stop' + (comment?(' — '+comment):'') }); }
else if(mc === 30 || mc === 2){ events.push({ lineNo, type:'end', text:'Program end' }); }
}
if(T !== null && pendingToolLine){
toolChanges.push({
lineNo: pendingToolLine.lineNo,
tool: T,
label: pendingToolLine.comment || comment || lastComment || ('T'+T)
});
pendingToolLine = null;
}
if(hasHome){
// Reference-point return (G28): not a plotted cutting/rapid move in program space
continue;
}
const axisGiven = (X!==null || Y!==null || Z!==null);
if(!axisGiven || !modal.motion) continue;
const start = { x: pos.x, y: pos.y, z: pos.z };
let nx = pos.x, ny = pos.y, nz = pos.z;
if(modal.distance === 'incr'){
if(X!==null) nx = pos.x + X;
if(Y!==null) ny = pos.y + Y;
if(Z!==null) nz = pos.z + Z;
} else {
if(X!==null) nx = X;
if(Y!==null) ny = Y;
if(Z!==null) nz = Z;
}
pos = { x: nx, y: ny, z: nz };
const end = { x: nx, y: ny, z: nz };
let move = null;
if(modal.motion === 'rapid'){
move = { type:'rapid', lineNo, start, end, tool: T };
rapidCount++;
} else if(modal.motion === 'linear'){
move = { type:'linear', lineNo, start, end, tool: T };
linearCount++;
} else if(modal.motion === 'arcCW' || modal.motion === 'arcCCW'){
const cw = modal.motion === 'arcCW';
let cx, cy;
if(I!==null || J!==null){
// Standard Fanuc convention treats I/J as an offset relative to the arc's
// start point. Some control dialects (e.g. ISO-ESAGV) instead emit I/J as
// the arc center's absolute machine coordinates — using the relative
// interpretation on those files blows the center out to nonsense positions
// and renders arcs as huge loops far outside the panel. opts.absoluteIJ
// switches to that interpretation for formats known to need it.
if(opts.absoluteIJ){
cx = I!==null ? I : start.x;
cy = J!==null ? J : start.y;
} else {
cx = start.x + (I||0);
cy = start.y + (J||0);
}
} else if(R!==null){
const c = arcCenterFromRadius(start.x, start.y, end.x, end.y, R, cw);
if(!c){ move = { type:'linear', lineNo, start, end, tool: T }; linearCount++; }
else { cx = c.cx; cy = c.cy; }
} else {
move = { type:'linear', lineNo, start, end, tool: T };
linearCount++;
}
if(!move){
const pts = arcPoints(start.x, start.y, end.x, end.y, cx, cy, cw);
move = { type: cw?'arcCW':'arcCCW', lineNo, start, end, center:{x:cx,y:cy}, points: pts, tool: T };
arcCount++;
}
}
if(move){
moves.push(move);
const xs = move.points ? move.points.map(p=>p.x).concat([start.x,end.x]) : [start.x, end.x];
const ys = move.points ? move.points.map(p=>p.y).concat([start.y,end.y]) : [start.y, end.y];
xs.forEach(v=>{ if(v<minX) minX=v; if(v>maxX) maxX=v; });
ys.forEach(v=>{ if(v<minY) minY=v; if(v>maxY) maxY=v; });
}
}
if(!isFinite(minX)){ minX=0; maxX=1; minY=0; maxY=1; }
let originLabel;
if(originCode === 55) originLabel = 'G55 (0, 0 origin)';
else if(originCode === 56) originLabel = 'G56 (4" × 4" origin)';
else if(originCode !== null) originLabel = 'G' + originCode + ' (other work offset)';
else originLabel = 'Not specified';
const header = opts.parseHeader ? opts.parseHeader(text) : {
jobName: jobMatch ? jobMatch[1].trim() : null,
materialName: materialMatch ? materialMatch[1].trim() : null,
panelLength: panelMatch ? parseFloat(panelMatch[1]) : null,
panelWidth: panelMatch ? parseFloat(panelMatch[2]) : null,
panelThickness: panelMatch ? parseFloat(panelMatch[3]) : null,
originCode, originLabel,
};
return {
format: opts.formatTag || 'gcode',
lines, moves, toolChanges, events, header,
parts: [], sheet: null,
units: modal.units,
bbox: { minX, maxX, minY, maxY, width: maxX-minX, height: maxY-minY },
counts: { rapid: rapidCount, linear: linearCount, arc: arcCount, total: moves.length },
};
}
// ============================================================
// ISO-ESAGV PARSER (.i00 — ESA GV control ISO post, ISO-ESAGV(2) header)
// ============================================================
// Same G0/G1/G2/G3 motion vocabulary as plain Fanuc gcode, buried in a lot of
// control-specific furniture (?%ETK[..]=.. / ?%EOK[..]=.. variable assignments,
// @T=../@M..-style tool/macro directives, G161 kinematic-transform lines with
// inline arithmetic expressions, G305/G310/G4F/SYN and other setup codes). None
// of that furniture carries axis words the generic tokenizer would mistake for
// geometry (arithmetic expressions like "X((-2440.400)+(31.800))" start with an
// open-paren right after the axis letter, so they never match the number pattern
// and are silently skipped) — so the shared parseGcode line-scanner already
// handles rapids/linears/drills for this dialect correctly. The one real
// difference is that this control's G2/G3 I/J give the arc center's ABSOLUTE
// coordinates rather than an offset from the start point (confirmed by checking
// that start-to-center and end-to-center distances match for every arc in a real
// sample file, to within 0.01mm, only under the absolute interpretation).
function parseEsagvHeader(text){
const dxMatch = text.match(/\?%EOK211=([\d.]+)/);
const dyMatch = text.match(/\?%EOK212=([\d.]+)/);
const dzMatch = text.match(/\?%EOK213=([\d.]+)/);
return {
jobName: null,
materialName: null,
panelLength: dxMatch ? parseFloat(dxMatch[1]) : null,
panelWidth: dyMatch ? parseFloat(dyMatch[1]) : null,
panelThickness: dzMatch ? parseFloat(dzMatch[1]) : null,
originCode: null,
originLabel: 'Not specified',
};
}
function parseEsagv(text){
return parseGcode(text, { absoluteIJ: true, parseHeader: parseEsagvHeader, formatTag: 'esagv' });
}
// ============================================================
// CORNER / COMPENSATION AUDIT (gcode & esagv formats)
//
// Finds two classes of G41/G42-breaking defects in the toolpath:
// 1. "Colinear runs" — maximal chains of consecutive linear segments whose
// direction barely changes (default < 5°). These can be safely collapsed
// to one direct segment by deleting every interior point's line, since
// doing so doesn't change the cut shape, only removes redundant noise.
// 2. Residual short segments — any segment shorter than the currently active
// tool radius (parsed from the M06 tool-change comment, e.g. "1/2in
// Upshear Rougher") that ISN'T resolved by a colinear-run collapse, i.e.
// it sits between two genuinely sharp, unrelated corners. These are
// flagged for manual review rather than auto-fixed, since deleting an
// endpoint there would visibly change the design, not just clean up noise.
//
// Validated against a real customer file pair (an original .anc and the
// customer's own hand-fixed copy): this reproduces their one manual line
// deletion exactly (byte-for-byte), and surfaces two further un-fixed
// instances of the same defect elsewhere in the same file.
// ============================================================
function parseDiameterMm(label){
if(!label) return null;
const fracM = label.match(/(\d+)\s*\/\s*(\d+)\s*in/i);
if(fracM) return (parseFloat(fracM[1])/parseFloat(fracM[2])) * 25.4;
const decM = label.match(/([\d.]+)\s*in/i);
if(decM) return parseFloat(decM[1]) * 25.4;
const mmM = label.match(/([\d.]+)\s*mm/i);
if(mmM) return parseFloat(mmM[1]);
return null;
}
function activeToolRadiusAt(toolChanges, lineNo){
let d = null;
for(const tc of toolChanges){ if(tc.lineNo <= lineNo) d = tc.diameterMm; else break; }
return d!=null ? d/2 : null;
}
function detectAuditIssues(program, opts){
opts = opts || {};
const COLINEAR_DEG = opts.colinearDeg != null ? opts.colinearDeg : 5;
const EPS = 1e-6;
const toolChanges = program.toolChanges.map(tc=>({ lineNo: tc.lineNo, diameterMm: parseDiameterMm(tc.label) }));
const xyMoves = [];
for(let i=0;i<program.moves.length;i++){
const mv = program.moves[i];
if(mv.type !== 'linear') continue;
const dx = mv.end.x-mv.start.x, dy = mv.end.y-mv.start.y, dz = mv.end.z-mv.start.z;
if(Math.abs(dx)<EPS && Math.abs(dy)<EPS) continue; // Z-only plunge/retract
xyMoves.push({ idx:i, lineNo: mv.lineNo, x1:mv.start.x, y1:mv.start.y, x2:mv.end.x, y2:mv.end.y, dz, len: Math.hypot(dx,dy) });
}
function angleBetween(v1,v2){
const dot = v1.x*v2.x + v1.y*v2.y;
const mag = Math.hypot(v1.x,v1.y)*Math.hypot(v2.x,v2.y);
if(mag < 1e-9) return 0;
let c = dot/mag; c = Math.max(-1, Math.min(1,c));
return Math.acos(c) * 180/Math.PI;
}
const turns = new Array(xyMoves.length).fill(null);
for(let i=1;i<xyMoves.length;i++){
const a = xyMoves[i-1], b = xyMoves[i];
if(b.idx !== a.idx+1) continue; // something else (rapid/arc) sits between them
if(Math.abs(a.x2-b.x1) > EPS || Math.abs(a.y2-b.y1) > EPS) continue;
if(Math.abs(a.dz) > EPS || Math.abs(b.dz) > EPS) continue; // a real depth change at this vertex — leave it alone
turns[i] = angleBetween({x:a.x2-a.x1,y:a.y2-a.y1}, {x:b.x2-b.x1,y:b.y2-b.y1});
}
const runs = [];
let i = 1;
while(i < xyMoves.length){
if(turns[i] != null && turns[i] < COLINEAR_DEG){
let start = i-1, end = i;
while(end+1 < xyMoves.length && turns[end+1] != null && turns[end+1] < COLINEAR_DEG){ end++; }
runs.push({ startSegIdx:start, endSegIdx:end });
i = end+1;
} else i++;
}
const issues = [];
const runSegIdxSet = new Set();
runs.forEach((r,ri)=>{
for(let k=r.startSegIdx;k<=r.endSegIdx;k++) runSegIdxSet.add(k);
const segs = xyMoves.slice(r.startSegIdx, r.endSegIdx+1);
const deleteLines = segs.slice(0,-1).map(s=>s.lineNo);
const keepLine = segs[segs.length-1].lineNo;
const from = { x:segs[0].x1, y:segs[0].y1 };
const to = { x:segs[segs.length-1].x2, y:segs[segs.length-1].y2 };
const involvedShort = segs.some(s=>{ const rad = activeToolRadiusAt(toolChanges, s.lineNo); return rad!=null && s.len < rad; });
issues.push({
id: 'run'+ri, type:'colinear', defaultChecked:true,
deleteLines, keepLine, from, to,
segs: segs.map(s=>({lineNo:s.lineNo, x1:s.x1,y1:s.y1,x2:s.x2,y2:s.y2,len:s.len})),
involvedShort,
title: (segs.length===2 ? 'Redundant point' : (segs.length-1)+' redundant points') + (involvedShort ? ' (creates a sub-radius segment)' : ''),
detail: 'Line'+(deleteLines.length>1?'s ':' ')+deleteLines.join(', ')+' '+(deleteLines.length>1?'are':'is')+' nearly colinear with the next move (turn angle < '+COLINEAR_DEG+'°) — safe to delete, merging directly into line '+keepLine+'.',
});
});
xyMoves.forEach((s, idx)=>{
if(runSegIdxSet.has(idx)) return;
const radius = activeToolRadiusAt(toolChanges, s.lineNo);
if(radius!=null && s.len < radius){
issues.push({
id:'short'+idx, type:'shortSharp', defaultChecked:false,
deleteLines:[], keepLine:s.lineNo, from:{x:s.x1,y:s.y1}, to:{x:s.x2,y:s.y2},
segs:[{lineNo:s.lineNo,x1:s.x1,y1:s.y1,x2:s.x2,y2:s.y2,len:s.len}],
involvedShort:true, radius,
title: 'Short segment at a sharp corner (needs review)',
detail: 'Line '+s.lineNo+' is only '+s.len.toFixed(3)+'mm, shorter than the active tool radius ('+radius.toFixed(3)+'mm), and both neighboring corners are sharp turns rather than a gentle bend — deleting an endpoint here would change the cut shape, not just remove noise, so this needs a manual decision rather than an automatic fix.',
});
}
});
issues.sort((a,b)=> (a.segs[0].lineNo) - (b.segs[0].lineNo));
return issues;
}
// ============================================================
// RESUME-FROM-OPERATION EXPORT (gcode & esagv formats)
//
// Groups the file into tool blocks (each starting at an M06 Tn line) and,
// within each block, lists every rapid move to a new XY position as a
// candidate "operation" boundary (one drill, or one routing contour). To
// resume at a chosen operation: keep the file's universal header (through
// the post-processor's own "RESTART LINE AT TOOL CHANGE" boilerplate if
// present), replay that tool's own block-start setup lines (M06 / work
// plane / spindle start / tool-length-offset — copied verbatim from the
// original file, never synthesized) so tool, spindle and Z clearance are
// correctly re-established, then splice in the file UNCHANGED starting at
// the chosen operation's own rapid line through EOF.
// ============================================================
function findToolBlocks(program, lines){
const blocks = [];
program.toolChanges.forEach((tc, ti)=>{
let setupEndLine = null;
for(let ln=tc.lineNo; ln<=lines.length; ln++){
const l = lines[ln-1] || '';
if(/^\s*G90\s+G43\s+H\d+/i.test(l)){ setupEndLine = ln; break; }
if(ti+1 < program.toolChanges.length && ln >= program.toolChanges[ti+1].lineNo) break;
}
if(setupEndLine == null) setupEndLine = tc.lineNo;
const blockEndLine = (ti+1 < program.toolChanges.length) ? program.toolChanges[ti+1].lineNo - 1 : lines.length;
let ownSetupStartLine = tc.lineNo;
let scanned = 0;
while(ownSetupStartLine-1 >= 1 && scanned < 6){
const prev = lines[ownSetupStartLine-2] || '';
if(/^\s*M05\s*$/i.test(prev) || /^\s*G5\.1\s*Q0\s*$/i.test(prev) || /^\s*\([^)]*\)\s*$/.test(prev)){
ownSetupStartLine--; scanned++;
} else break;
}
blocks.push({ toolLineNo: tc.lineNo, label: tc.label, tool: tc.tool, ownSetupStartLine, setupEndLine, blockEndLine, ops: [] });
});
program.moves.forEach(mv=>{
if(mv.type !== 'rapid') return;
const dx = mv.end.x-mv.start.x, dy = mv.end.y-mv.start.y;
if(Math.abs(dx) < 1e-6 && Math.abs(dy) < 1e-6) return; // pure Z rapid
for(const b of blocks){
if(mv.lineNo >= b.toolLineNo && mv.lineNo <= b.blockEndLine){
b.ops.push({ lineNo: mv.lineNo, x: mv.end.x, y: mv.end.y });
break;
}
}
});
return blocks;
}
function findHeaderEndLine(lines){
for(let i=0;i<lines.length;i++){
if(/RESTART LINE AT TOOL CHANGE/i.test(lines[i])){
for(let j=i+1;j<lines.length;j++){
if(/^\s*M06\b/i.test(lines[j]) || /^\s*\(.*SEQUENCE.*\)/i.test(lines[j]) || /^\s*\(ROUTE/i.test(lines[j])){
return j;
}
}
}
}
return null;
}
function buildResumeExport(program, lines, blockIdx, opLineNo, eol){
eol = eol || '\n';
const blocks = findToolBlocks(program, lines);
const block = blocks[blockIdx];
if(!block) return null;
let headerEndIdx = findHeaderEndLine(lines);
if(headerEndIdx == null){ headerEndIdx = block.ownSetupStartLine - 1; }
const headerLines = lines.slice(0, headerEndIdx);
const setupStartIdx = Math.max(headerEndIdx, block.ownSetupStartLine - 1);
const setupLines = lines.slice(setupStartIdx, block.setupEndLine);
const tailStartLine = (opLineNo <= block.setupEndLine) ? block.setupEndLine + 1 : opLineNo;
const tailLines = lines.slice(tailStartLine - 1);
const out = headerLines.concat(setupLines).concat(tailLines);