This repository has been archived by the owner on Jan 29, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 45
/
gcode-parser.js
1325 lines (1163 loc) · 61.3 KB
/
gcode-parser.js
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
/*
AUTHOR: John Lauer
-- S??? (laser intensity) Parameter Handling added by AUTHOR: Peter van der Walt
*/
// This is a simplified and updated version of http://gcode.joewalnes.com/ that works with the latest version of Three.js (v68).
// Updated with code from http://chilipeppr.com/tinyg's 3D viewer to support more CNC type Gcode
var tototaltimemax = '';
totaltimemax = 0;
function GCodeParser(handlers) {
handlers = handlers || {};
lastArgs = {cmd: null};
lastFeedrate = null;
isUnitsMm = true;
parseLine = function (text, info) {
//console.log('parseLine: '+text+', '+info);
//text = text.replace(/;.*$/, '').trim(); // Remove comments
//text = text.replace(/\(.*$/, '').trim(); // Remove comments
//text = text.replace(/<!--.*?-->/, '').trim(); // Remove comments
var origtext = text;
// remove line numbers if exist
if (text.match(/^N/i)) {
// yes, there's a line num
text = text.replace(/^N\d+\s*/ig, "");
}
// collapse leading zero g cmds to no leading zero
text = text.replace(/G00/i, 'G0');
text = text.replace(/G0(\d)/i, 'G$1');
// add spaces before g cmds and xyzabcijkf params
text = text.replace(/([gmtxyzabcijkfst])/ig, " $1");
// remove spaces after xyzabcijkf params because a number should be directly after them
text = text.replace(/([xyzabcijkfst])\s+/ig, "$1");
// remove front and trailing space
text = text.trim();
// see if comment
var isComment = false;
if (text.match(/^(;|\(|<)/)) {
text = origtext;
isComment = true;
} else {
// make sure to remove inline comments
text = text.replace(/\(.*?\)/g, "");
}
//console.log("gcode txt:", text);
if (text && !isComment) {
//console.log("there is txt and it's not a comment");
//console.log("");
// preprocess XYZIJ params to make sure there's a space
//text = text.replace(/(X|Y|Z|I|J|K)/ig, "$1 ");
//console.log("gcode txt:", text);
// strip off end of line comment
text = text.replace(/(;|\().*$/, ""); // ; or () trailing
//text = text.replace(/\(.*$/, ""); // () trailing
var tokens = text.split(/\s+/);
//console.log("tokens:", tokens);
if (tokens) {
var cmd = tokens[0];
cmd = cmd.toUpperCase();
// check if a g or m cmd was included in gcode line
// you are allowed to just specify coords on a line
// and it should be assumed that the last specified gcode
// cmd is what's assumed
isComment = false;
if (!cmd.match(/^(G|M|T)/i)) {
// if comment, drop it
/*
if (cmd.match(/(;|\(|<)/)) {
// is comment. do nothing.
isComment = true;
text = origtext;
//console.log("got comment:", cmd);
} else {
*/
//console.log("no cmd so using last one. lastArgs:", this.lastArgs);
// we need to use the last gcode cmd
cmd = this.lastArgs.cmd;
//console.log("using last cmd:", cmd);
tokens.unshift(cmd); // put at spot 0 in array
//console.log("tokens:", tokens);
//}
} else {
// we have a normal cmd as opposed to just an xyz pos where
// it assumes you should use the last cmd
// however, need to remove inline comments (TODO. it seems parser works fine for now)
}
var args = {
'cmd': cmd,
'text': text,
'origtext': origtext,
'indx': info,
'isComment': isComment,
'feedrate': null,
'plane': undefined
};
//console.log("args:", args);
if (tokens.length > 1 && !isComment) {
tokens.splice(1).forEach(function (token) {
//console.log("token:", token);
if (token && token.length > 0) {
var key = token[0].toLowerCase();
var value = parseFloat(token.substring(1));
//console.log("value:", value, "key:", key);
//if (isNaN(value))
// console.error("got NaN. val:", value, "key:", key, "tokens:", tokens);
args[key] = value;
} else {
//console.log("couldn't parse token in foreach. weird:", token);
}
});
}
var handler = handlers[cmd] || handlers['default'];
// don't save if saw a comment
if (!args.isComment) {
lastArgs = args;
//console.log("just saved lastArgs for next use:", this.lastArgs);
} else {
//console.log("this was a comment, so didn't save lastArgs");
}
//console.log("calling handler: cmd:", cmd, "args:", args, "info:", info);
if (handler) {
// do extra check here for units. units are
// specified via G20 or G21. We need to scan
// each line to see if it's inside the line because
// we were only catching it when it was the first cmd
// of the line.
if (args.text.match(/\bG20\b/i)) {
console.log("SETTING UNITS TO INCHES from pre-parser!!!");
this.isUnitsMm = false; // false means inches cuz default is mm
} else if (args.text.match(/\bG21\b/i)) {
console.log("SETTING UNITS TO MM!!! from pre-parser");
this.isUnitsMm = true; // true means mm
}
// scan for feedrate
if (args.text.match(/F([\d.]+)/i)) {
// we have a new feedrate
var feedrate = parseFloat(RegExp.$1);
//console.log("got feedrate on this line. feedrate:", feedrate, "args:", args);
args.feedrate = feedrate;
this.lastFeedrate = feedrate;
} else {
// use feedrate from prior lines
args.feedrate = this.lastFeedrate;
//if (args.feedrate
}
//console.log("about to call handler. args:", args, "info:", info, "this:", this);
return handler(args, info, this);
} else {
console.error("No handler for gcode command!!!");
}
}
} else {
// it was a comment or the line was empty
// we still need to create a segment with xyz in p2
// so that when we're being asked to /gotoline we have a position
// for each gcode line, even comments. we just use the last real position
// to give each gcode line (even a blank line) a spot to go to
var args = {
'cmd': 'empty or comment',
'text': text,
'origtext': origtext,
'indx': info,
'isComment': isComment
};
var handler = handlers['default'];
return handler(args, info, this);
}
}
this.parse = function(gcode) {
$('#renderprogressholder').show();
$("#gcodelinestbody").empty();
lines = gcode.split(/\r{0,1}\n/);
count = lines.length;
maxTimePerChunk = 500;
index = 0;
function now() {
return new Date().getTime();
}
var tbody = '';
function doChunk() {
//console.log('Render line: '+index)
var startTime = now();
while (index < count && (now() - startTime) <= maxTimePerChunk) {
// callback called with args (value, index, array)
//fn.call(context, array[index], index, array);
var progress = Math.round((index / count) * 100.0);
$('#renderprogressholder .progress-bar').width(progress + "%");
$('#renderprogressholder .progress-bar').text(progress + "%");
//console.log('[GCODE PARSE] Line:'+i+' of '+lines.length);
if (parseLine(lines[index], index) === false) {
//break;
}
tbody += '<tr id="tr'+[index]+'"><td>'+[index]+'</td><td>'+lines[index]+'</td></tr>';//code here using lines[i] which will give you each line
++index;
}
if (index < count) {
// set Timeout for async iteration
setTimeout(doChunk, 1);
} else {
console.log('[GCODE PARSE] Done ');
$('#renderprogressholder').hide();
object = drawobject();
object.translateX(laserxmax /2 * -1);
object.translateY(laserymax /2 * -1);
scene.add(object);
$('#gcodelinestable > tbody:last-child').append(tbody);//code here using lines[i] which will give you each line
}
}
doChunk();
}
/*
this.parse = function (gcode) {
$('#renderprogressholder').show();
this.lines = gcode.split(/\r{0,1}\n/);
this.currentIndex = 0;
this.timer = null;
this.count = this.lines.length;
// this.timer = window.setInterval(this.loop.bind(this), 10);
timer = window.setInterval(parseloop.bind(this), 1);
};
parseloop = function () {
if (this.currentIndex < this.count) {
var progress = Math.round((this.currentIndex / this.count) * 100.0);
$('#renderprogressholder .progress-bar').width(progress + "%");
$('#renderprogressholder .progress-bar').text(progress + "%");
//console.log('[GCODE PARSE] Line:'+i+' of '+lines.length);
// Good spot to report on progress
if (parseLine(this.lines[this.currentIndex], this.currentIndex) === false) {
//break;
}
this.currentIndex++
} else {
console.log('[GCODE PARSE] Done ');
window.clearInterval(timer);
$('#renderprogressholder').hide();
object = drawobject();
object.translateX(laserxmax /2 * -1);
object.translateY(laserymax /2 * -1);
scene.add(object);
//parsestop();
}
};
*/
/* this.parse = function (gcode) {
var lines = gcode.split(/\r{0,1}\n/);
for (var i = 0; i < lines.length; i++) {
//console.log('[GCODE PARSE] Line:'+i+' of '+lines.length);
// Good spot to report on progress
if (parseLine(lines[i], i) === false) {
break;
}
}
} */
};
colorG0: 0x00ff00;
colorG1: 0x0000ff;
colorG2: 0x999900;
createObjectFromGCode = function (gcode, indxMax) {
//debugger;
// Credit goes to https://github.com/joewalnes/gcode-viewer
// for the initial inspiration and example code.
//
// GCode descriptions come from:
// http://reprap.org/wiki/G-code
// http://en.wikipedia.org/wiki/G-code
// SprintRun source code
// these are extra Object3D elements added during
// the gcode rendering to attach to scene
this.extraObjects = [];
this.extraObjects["G17"] = [];
this.extraObjects["G18"] = [];
this.extraObjects["G19"] = [];
this.offsetG92 = {x:0, y:0, z:0, e:0};
var lastLine = {
x: 0,
y: 0,
z: 0,
e: 0,
f: 0,
feedrate: null,
extruding: false
};
// we have been using an approach where we just append
// each gcode move to one monolithic geometry. we
// are moving away from that idea and instead making each
// gcode move be it's own full-fledged line object with
// its own userData info
// G2/G3 moves are their own child of lots of lines so
// that even the simulator can follow along better
new3dObj = new THREE.Group();
plane = "G17"; //set default plane to G17 - Assume G17 if no plane specified in gcode.
layers = [];
layer = undefined;
lines = [];
totalDist = 0;
bbbox = {
min: {
x: 100000,
y: 100000,
z: 100000
},
max: {
x: -100000,
y: -100000,
z: -100000
}
};
bbbox2 = {
min: {
x: 100000,
y: 100000,
z: 100000
},
max: {
x: -100000,
y: -100000,
z: -100000
}
};
newLayer = function (line) {
//console.log("layers:", layers, "layers.length", layers.length);
layer = {
type: {},
layer: layers.length,
z: line.z,
};
layers.push(layer);
};
getLineGroup = function (line, args) {
//console.log("getLineGroup:", line);
if (layer == undefined) newLayer(line);
var speed = Math.round(line.e / 1000);
var opacity = line.s;
var tool = parseInt(line.t, 10);
// /console.log('Speed: ' , speed , ' opacity: ', opacity);
var grouptype = speed + opacity;
var color = null;
//var color = new THREE.Color(0x990000);
if(typeof line.s === 'undefined'){
opacity = 0.3;
} else {
if (firmware.indexOf('Grbl') == 0) {
opacity = line.s / 255;
} else if (firmware.indexOf('Smooth') == 0) {
opacity = line.s;
//console.log(opacity+', '+line.x);
//console.log(opacity);
} else if (firmware.indexOf('Lasaur') == 0) {
opacity = line.s / 255;
//console.log(opacity+', '+line.x);
} else {
opacity = line.s / 100;
//console.log(opacity+', '+line.x);
}
}
//console.log(opacity);
// LaserWeb 3D Viewer Colors
// LaserWeb 3D Viewer Colors
if(typeof line.extruding === 'undefined' && typeof line.s === 'undefined'){
//console.log('G1 without extrude', line);
grouptype = "g0";
opacity = 0.3;
color = new THREE.Color(0x00ff00);
} else {
//console.log('G1 with extrude', line);
if (line.g0) {
grouptype = "g0";
//color = new THREE.Color(0x00ff00);
opacity = 0.3;
color = new THREE.Color(0x00ff00);
} else if (line.g2) {
grouptype = "g2";
//color = new THREE.Color(0x999900);
color = new THREE.Color(0x990000);
} else if (line.t == 0) {
grouptype = "t0";
//color = new THREE.Color(0x999900);
color = new THREE.Color(0x0000ff);
} else if (line.t == 1) {
grouptype = "t1";
//color = new THREE.Color(0x999900);
color = new THREE.Color(0xff00ff);
} else if (line.arc) {
grouptype = "arc";
color = new THREE.Color(0x990000);
} else {
color = new THREE.Color(0x990000);
}
}
// see if we have reached indxMax, if so draw, but
// make it ghosted
//if (args.indx > indxMax) {
// grouptype = "ghost";
// //console.log("args.indx > indxMax", args, indxMax);
// color = new THREE.Color(0x000000);
// }
//if (line.color) color = new THREE.Color(line.color);
if (layer.type[grouptype] == undefined) {
layer.type[grouptype] = {
type: grouptype,
feed: line.e,
extruding: line.extruding,
color: color,
segmentCount: 0,
material: new THREE.LineBasicMaterial({
opacity: opacity,
//opacity: line.extruding ? 0.5: line.g2 ? 0.2 : 0.3,
transparent: true,
linewidth: 1,
vertexColors: THREE.FaceColors
}),
geometry: new THREE.Geometry(),
}
//if (args.indx > indxMax) {
// layer.type[grouptype].material.opacity = 0.05;
//}
}
return layer.type[grouptype];
};
drawArc = function(aX, aY, aZ, endaZ, aRadius, aStartAngle, aEndAngle, aClockwise, plane) {
//console.log("drawArc:", aX, aY, aZ, aRadius, aStartAngle, aEndAngle, aClockwise);
var ac = new THREE.ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise);
//console.log("ac:", ac);
var acmat = new THREE.LineBasicMaterial({
color: 0x00aaff,
opacity: 0.5,
transparent: true
});
var acgeo = new THREE.Geometry();
var ctr = 0;
var z = aZ;
ac.getPoints(20).forEach(function (v) {
//console.log(v);
z = (((endaZ - aZ) / 20) * ctr) + aZ;
acgeo.vertices.push(new THREE.Vector3(v.x, v.y, z));
ctr++;
});
var aco = new THREE.Line(acgeo, acmat);
//aco.position.set(pArc.x, pArc.y, pArc.z);
//console.log("aco:", aco);
this.extraObjects[plane].push(aco);
return aco;
};
this.drawArcFrom2PtsAndCenter = function(vp1, vp2, vpArc, args) {
//console.log("drawArcFrom2PtsAndCenter. vp1:", vp1, "vp2:", vp2, "vpArc:", vpArc, "args:", args);
//var radius = vp1.distanceTo(vpArc);
//console.log("radius:", radius);
// Find angle
var p1deltaX = vpArc.x - vp1.x;
var p1deltaY = vpArc.y - vp1.y;
var p1deltaZ = vpArc.z - vp1.z;
var p2deltaX = vpArc.x - vp2.x;
var p2deltaY = vpArc.y - vp2.y;
var p2deltaZ = vpArc.z - vp2.z;
switch(args.plane){
case "G18":
var anglepArcp1 = Math.atan(p1deltaZ / p1deltaX);
var anglepArcp2 = Math.atan(p2deltaZ / p2deltaX);
break;
case "G19":
var anglepArcp1 = Math.atan(p1deltaZ / p1deltaY);
var anglepArcp2 = Math.atan(p2deltaZ / p2deltaY);
break;
default:
var anglepArcp1 = Math.atan(p1deltaY / p1deltaX);
var anglepArcp2 = Math.atan(p2deltaY / p2deltaX);
}
// Draw arc from arc center
var radius = vpArc.distanceTo(vp1);
var radius2 = vpArc.distanceTo(vp2);
//console.log("radius:", radius);
if (Number((radius).toFixed(2)) != Number((radius2).toFixed(2))) console.log("Radiuses not equal. r1:", radius, ", r2:", radius2, " with args:", args, " rounded vals r1:", Number((radius).toFixed(2)), ", r2:", Number((radius2).toFixed(2)));
// arccurve
var clwise = true;
if (args.clockwise === false) clwise = false;
//if (anglepArcp1 < 0) clockwise = false;
switch(args.plane){
case "G19":
if (p1deltaY >= 0) anglepArcp1 += Math.PI;
if (p2deltaY >= 0) anglepArcp2 += Math.PI;
break;
default:
if (p1deltaX >= 0) anglepArcp1 += Math.PI;
if (p2deltaX >= 0) anglepArcp2 += Math.PI;
}
if (anglepArcp1 === anglepArcp2 && clwise === false)
// Draw full circle if angles are both zero,
// start & end points are same point... I think
switch(args.plane){
case "G18":
var threeObj = this.drawArc(vpArc.x, vpArc.z, (-1*vp1.y), (-1*vp2.y), radius, anglepArcp1, (anglepArcp2 + (2*Math.PI)), clwise, "G18");
break;
case "G19":
var threeObj = this.drawArc(vpArc.y, vpArc.z, vp1.x, vp2.x, radius, anglepArcp1, (anglepArcp2 + (2*Math.PI)), clwise, "G19");
break;
default:
var threeObj = this.drawArc(vpArc.x, vpArc.y, vp1.z, vp2.z, radius, anglepArcp1, (anglepArcp2 + (2*Math.PI)), clwise, "G17");
}
else
switch(args.plane){
case "G18":
var threeObj = this.drawArc(vpArc.x, vpArc.z, (-1*vp1.y), (-1*vp2.y), radius, anglepArcp1, anglepArcp2, clwise, "G18");
break;
case "G19":
var threeObj = this.drawArc(vpArc.y, vpArc.z, vp1.x, vp2.x, radius, anglepArcp1, anglepArcp2, clwise, "G19");
break;
default:
var threeObj = this.drawArc(vpArc.x, vpArc.y, vp1.z, vp2.z, radius, anglepArcp1, anglepArcp2, clwise, "G17");
}
return threeObj;
};
addSegment = function (p1, p2, args) {
//console.log("");
//console.log("addSegment p2:", p2);
// add segment to array for later use
lines.push({
p2: p2,
'args': args
});
var group = getLineGroup(p2, args);
var geometry = group.geometry;
group.segmentCount++;
// see if we need to draw an arc
if (p2.arc) {
//console.log("");
//console.log("drawing arc. p1:", p1, ", p2:", p2);
//var segmentCount = 12;
// figure out the 3 pts we are dealing with
// the start, the end, and the center of the arc circle
// radius is dist from p1 x/y/z to pArc x/y/z
//if(args.clockwise === false || args.cmd === "G3"){
// var vp2 = new THREE.Vector3(p1.x, p1.y, p1.z);
// var vp1 = new THREE.Vector3(p2.x, p2.y, p2.z);
//}
//else {
var vp1 = new THREE.Vector3(p1.x, p1.y, p1.z);
var vp2 = new THREE.Vector3(p2.x, p2.y, p2.z);
//}
var vpArc;
// if this is an R arc gcode command, we're given the radius, so we
// don't have to calculate it. however we need to determine center
// of arc
if (args.r != null) {
//console.log("looks like we have an arc with R specified. args:", args);
//console.log("anglepArcp1:", anglepArcp1, "anglepArcp2:", anglepArcp2);
radius = parseFloat(args.r);
// First, find the distance between points 1 and 2. We'll call that q,
// and it's given by sqrt((x2-x1)^2 + (y2-y1)^2).
var q = Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2) + Math.pow(p2.z - p1.z, 2));
// Second, find the point halfway between your two points. We'll call it
// (x3, y3). x3 = (x1+x2)/2 and y3 = (y1+y2)/2.
var x3 = (p1.x + p2.x) / 2;
var y3 = (p1.y + p2.y) / 2;
var z3 = (p1.z + p2.z) / 2;
// There will be two circle centers as a result of this, so
// we will have to pick the correct one. In gcode we can get
// a + or - val on the R to indicate which circle to pick
// One answer will be:
// x = x3 + sqrt(r^2-(q/2)^2)*(y1-y2)/q
// y = y3 + sqrt(r^2-(q/2)^2)*(x2-x1)/q
// The other will be:
// x = x3 - sqrt(r^2-(q/2)^2)*(y1-y2)/q
// y = y3 - sqrt(r^2-(q/2)^2)*(x2-x1)/q
var pArc_1 = undefined;
var pArc_2 = undefined;
var calc = Math.sqrt((radius * radius) - Math.pow(q / 2, 2));
var angle_point = undefined;
switch(args.plane){
case "G18":
pArc_1 = {
x: x3 + calc * (p1.z - p2.z) / q,
y: y3 + calc * (p2.y - p1.y) / q,
z: z3 + calc * (p2.x - p1.x) / q };
pArc_2 = {
x: x3 - calc * (p1.z - p2.z) / q,
y: y3 - calc * (p2.y - p1.y) / q,
z: z3 - calc * (p2.x - p1.x) / q };
angle_point = Math.atan2(p1.z, p1.x) - Math.atan2(p2.z, p2.x);
if(((p1.x-pArc_1.x)*(p1.z+pArc_1.z))+((pArc_1.x-p2.x)*(pArc_1.z+p2.z)) >=
((p1.x-pArc_2.x)*(p1.z+pArc_2.z))+((pArc_2.x-p2.x)*(pArc_2.z+p2.z))){
var cw = pArc_1;
var ccw = pArc_2;
}
else{
var cw = pArc_2;
var ccw = pArc_1;
}
break;
case "G19":
pArc_1 = {
x: x3 + calc * (p1.x - p2.x) / q,
y: y3 + calc * (p1.z - p2.z) / q,
z: z3 + calc * (p2.y - p1.y) / q };
pArc_2 = {
x: x3 - calc * (p1.x - p2.x) / q,
y: y3 - calc * (p1.z - p2.z) / q,
z: z3 - calc * (p2.y - p1.y) / q };
if(((p1.y-pArc_1.y)*(p1.z+pArc_1.z))+((pArc_1.y-p2.y)*(pArc_1.z+p2.z)) >=
((p1.y-pArc_2.y)*(p1.z+pArc_2.z))+((pArc_2.y-p2.y)*(pArc_2.z+p2.z))){
var cw = pArc_1;
var ccw = pArc_2;
}
else{
var cw = pArc_2;
var ccw = pArc_1;
}
break;
default:
pArc_1 = {
x: x3 + calc * (p1.y - p2.y) / q,
y: y3 + calc * (p2.x - p1.x) / q,
z: z3 + calc * (p2.z - p1.z) / q };
pArc_2 = {
x: x3 - calc * (p1.y - p2.y) / q,
y: y3 - calc * (p2.x - p1.x) / q,
z: z3 - calc * (p2.z - p1.z) / q };
if(((p1.x-pArc_1.x)*(p1.y+pArc_1.y))+((pArc_1.x-p2.x)*(pArc_1.y+p2.y)) >=
((p1.x-pArc_2.x)*(p1.y+pArc_2.y))+((pArc_2.x-p2.x)*(pArc_2.y+p2.y))){
var cw = pArc_1;
var ccw = pArc_2;
}
else{
var cw = pArc_2;
var ccw = pArc_1;
}
}
if((p2.clockwise === true && radius >= 0) || (p2.clockwise === false && radius < 0)) vpArc = new THREE.Vector3(cw.x, cw.y, cw.z);
else vpArc = new THREE.Vector3(ccw.x, ccw.y, ccw.z);
} else {
// this code deals with IJK gcode commands
/*if(args.clockwise === false || args.cmd === "G3")
var pArc = {
x: p2.arci ? p1.x + p2.arci : p1.x,
y: p2.arcj ? p1.y + p2.arcj : p1.y,
z: p2.arck ? p1.z + p2.arck : p1.z,
};
else*/
var pArc = {
x: p2.arci ? p1.x + p2.arci : p1.x,
y: p2.arcj ? p1.y + p2.arcj : p1.y,
z: p2.arck ? p1.z + p2.arck : p1.z,
};
//console.log("new pArc:", pArc);
vpArc = new THREE.Vector3(pArc.x, pArc.y, pArc.z);
//console.log("vpArc:", vpArc);
}
var threeObjArc = this.drawArcFrom2PtsAndCenter(vp1, vp2, vpArc, args);
// still push the normal p1/p2 point for debug
p2.g2 = true;
p2.threeObjArc = threeObjArc;
group = this.getLineGroup(p2, args);
// these golden lines showing start/end of a g2 or g3 arc were confusing people
// so hiding them for now. jlauer 8/15/15
/*
geometry = group.geometry;
geometry.vertices.push(
new THREE.Vector3(p1.x, p1.y, p1.z));
geometry.vertices.push(
new THREE.Vector3(p2.x, p2.y, p2.z));
geometry.colors.push(group.color);
geometry.colors.push(group.color);
*/
} else {
geometry.vertices.push(
new THREE.Vector3(p1.x, p1.y, p1.z));
geometry.vertices.push(
new THREE.Vector3(p2.x, p2.y, p2.z));
geometry.colors.push(group.color);
geometry.colors.push(group.color);
}
if (p2.extruding) {
bbbox.min.x = Math.min(bbbox.min.x, p2.x);
bbbox.min.y = Math.min(bbbox.min.y, p2.y);
bbbox.min.z = Math.min(bbbox.min.z, p2.z);
bbbox.max.x = Math.max(bbbox.max.x, p2.x);
bbbox.max.y = Math.max(bbbox.max.y, p2.y);
bbbox.max.z = Math.max(bbbox.max.z, p2.z);
}
if (p2.g0) {
// we're in a toolhead move, label moves
/*
if (group.segmentCount < 2) {
makeSprite(scene, "webgl", {
x: p2.x,
y: p2.y,
z: p2.z + 0,
text: group.segmentCount,
color: "#ff00ff",
size: 3,
});
}
*/
}
// global bounding box calc
bbbox2.min.x = Math.min(bbbox2.min.x, p2.x);
bbbox2.min.y = Math.min(bbbox2.min.y, p2.y);
bbbox2.min.z = Math.min(bbbox2.min.z, p2.z);
bbbox2.max.x = Math.max(bbbox2.max.x, p2.x);
bbbox2.max.y = Math.max(bbbox2.max.y, p2.y);
bbbox2.max.z = Math.max(bbbox2.max.z, p2.z);
// NEW METHOD OF CREATING THREE.JS OBJECTS
// create new approach for three.js objects which is
// a unique object for each line of gcode, including g2/g3's
// make sure userData is good too
var gcodeObj;
if (p2.arc) {
// use the arc that already got built
gcodeObj = p2.threeObjArc;
} else {
// make a line
var color = 0X0000ff;
if (p2.extruding) {
color = 0xff00ff;
} else if (p2.g0) {
color = 0x00ff00;
} else if (p2.g2) {
//color = 0x999900;
} else if (p2.arc) {
color = 0x0033ff;
}
var material = new THREE.LineBasicMaterial({
color: color,
opacity: 0.5,
transparent: true
});
//var geometry = new THREE.Geometry();
//geometry.vertices.push(
//new THREE.Vector3( p1.x, p1.y, p1.z ),
//ew THREE.Vector3( p2.x, p2.y, p2.z )
//);
var line = new THREE.Line( geometry, material );
gcodeObj = line;
}
gcodeObj.userData.p2 = p2;
gcodeObj.userData.args = args;
new3dObj.add(gcodeObj);
// DISTANCE CALC
// add distance so we can calc estimated time to run
// see if arc
var dist = 0;
if (p2.arc) {
// calc dist of all lines
//console.log("this is an arc to calc dist for. p2.threeObjArc:", p2.threeObjArc, "p2:", p2);
var arcGeo = p2.threeObjArc.geometry;
//console.log("arcGeo:", arcGeo);
var tad2 = 0;
for (var arcLineCtr = 0; arcLineCtr < arcGeo.vertices.length - 1; arcLineCtr++) {
tad2 += arcGeo.vertices[arcLineCtr].distanceTo(arcGeo.vertices[arcLineCtr+1]);
}
//console.log("tad2:", tad2);
// just do straight line calc
var a = new THREE.Vector3( p1.x, p1.y, p1.z );
var b = new THREE.Vector3( p2.x, p2.y, p2.z );
var straightDist = a.distanceTo(b);
//console.log("diff of straight line calc vs arc sum. straightDist:", straightDist);
dist = tad2;
} else {
// just do straight line calc
var a = new THREE.Vector3( p1.x, p1.y, p1.z );
var b = new THREE.Vector3( p2.x, p2.y, p2.z );
dist = a.distanceTo(b);
}
if (dist > 0) {
totalDist += dist;
}
// time to execute this move
// if this move is 10mm and we are moving at 100mm/min then
// this move will take 10/100 = 0.1 minutes or 6 seconds
var timeMinutes = 0;
if (dist > 0) {
var fr;
if (args.feedrate > 0) {
fr = args.feedrate
} else {
fr = 100;
}
timeMinutes = dist / fr;
// adjust for acceleration, meaning estimate
// this will run longer than estimated from the math
// above because we don't start moving at full feedrate
// obviously, we have to slowly accelerate in and out
timeMinutes = timeMinutes * 1.32;
}
// Handle Laser Sxxx parameter
sv = args.s;
//console.log(sv);
totalTime += timeMinutes;
p2.feedrate = args.feedrate;
p2.dist = dist;
p2.distSum = totalDist;
p2.timeMins = timeMinutes;
p2.timeMinsSum = totalTime;
//console.log('Total Time'+totalTime);
totaltimemax += (timeMinutes * 60);
//console.log("calculating distance. dist:", dist, "totalDist:", totalDist, "feedrate:", args.feedrate, "timeMinsToExecute:", timeMinutes, "totalTime:", totalTime, "p1:", p1, "p2:", p2, "args:", args);
}
totalDist = 0;
totalTime = 0;
var relative = false;
var tool = null;
delta = function (v1, v2) {
return relative ? v2 : v2 - v1;
}
absolute = function (v1, v2) {
return relative ? v1 + v2 : v2;
}
addFakeSegment = function(args) {
//line.args = args;
var arg2 = {
isFake : true,
text : args.text,
indx : args.indx
};
if (arg2.text.match(/^(;|\(|<)/)) arg2.isComment = true;
lines.push({
p2: lastLine, // since this is fake, just use lastLine as xyz
'args': arg2
});
}
var cofg = this;
parser = new GCodeParser({
//set the g92 offsets for the parser - defaults to no offset
/* When doing CNC, generally G0 just moves to a new location
as fast as possible which means no milling or extruding is happening in G0.
So, let's color it uniquely to indicate it's just a toolhead move. */
G0: function (args, indx) {
//G1.apply(this, args, line, 0x00ff00);
//console.log("G0", args);
var newLine = {
x: args.x !== undefined ? cofg.absolute(lastLine.x, args.x) + cofg.offsetG92.x : lastLine.x,
y: args.y !== undefined ? cofg.absolute(lastLine.y, args.y) + cofg.offsetG92.y : lastLine.y,
z: args.z !== undefined ? cofg.absolute(lastLine.z, args.z) + cofg.offsetG92.z : lastLine.z,
e: args.e !== undefined ? cofg.absolute(lastLine.e, args.e) + cofg.offsetG92.e : lastLine.e,
f: args.f !== undefined ? cofg.absolute(lastLine.f, args.f) : lastLine.f,
};
newLine.g0 = true;
//cofg.newLayer(newLine);
cofg.addSegment(lastLine, newLine, args);
//console.log("G0", lastLine, newLine, args, cofg.offsetG92);
lastLine = newLine;
},
G1: function (args, indx) {
// Example: G1 Z1.0 F3000
// G1 X99.9948 Y80.0611 Z15.0 F1500.0 E981.64869
// G1 E104.25841 F1800.0
// Go in a straight line from the current (X, Y) point
// to the point (90.6, 13.8), extruding material as the move
// happens from the current extruded length to a length of
// 22.4 mm.
var newLine = {
x: args.x !== undefined ? cofg.absolute(lastLine.x, args.x) + cofg.offsetG92.x : lastLine.x,
y: args.y !== undefined ? cofg.absolute(lastLine.y, args.y) + cofg.offsetG92.y : lastLine.y,
z: args.z !== undefined ? cofg.absolute(lastLine.z, args.z) + cofg.offsetG92.z : lastLine.z,
e: args.e !== undefined ? cofg.absolute(lastLine.e, args.e) + cofg.offsetG92.e : lastLine.e,
f: args.f !== undefined ? cofg.absolute(lastLine.f, args.f) : lastLine.f,
s: args.s !== undefined ? cofg.absolute(lastLine.s, args.s) : lastLine.s,
t: args.t !== undefined ? cofg.absolute(lastLine.t, args.t) : lastLine.t,
};
/* layer change detection is or made by watching Z, it's made by
watching when we extrude at a new Z position */
if (cofg.delta(lastLine.e, newLine.e) > 0) {
newLine.extruding = cofg.delta(lastLine.e, newLine.e) > 0;
if (layer == undefined || newLine.z != layer.z) cofg.newLayer(newLine);
}
cofg.addSegment(lastLine, newLine, args);
newLine.g1 = true;
//console.log("G1", lastLine, newLine, args, cofg.offsetG92);
lastLine = newLine;
},
G2 : function (args, indx, gcp) {
/* this is an arc move from lastLine's xy to the new xy. we'll
show it as a light gray line, but we'll also sub-render the
arc itself by figuring out the sub-segments . */
args.plane = plane; //set the plane for this command to whatever the current plane is
var newLine = {
x: args.x !== undefined ? cofg.absolute(lastLine.x, args.x) + cofg.offsetG92.x : lastLine.x,
y: args.y !== undefined ? cofg.absolute(lastLine.y, args.y) + cofg.offsetG92.y : lastLine.y,
z: args.z !== undefined ? cofg.absolute(lastLine.z, args.z) + cofg.offsetG92.z : lastLine.z,
e: args.e !== undefined ? cofg.absolute(lastLine.e, args.e) + cofg.offsetG92.e : lastLine.e,
f: args.f !== undefined ? cofg.absolute(lastLine.f, args.f) : lastLine.f,
t: args.t !== undefined ? cofg.absolute(lastLine.t, args.t) : lastLine.t,
arci: args.i ? args.i : null,
arcj: args.j ? args.j : null,
arck: args.k ? args.k : null,
arcr: args.r ? args.r : null,
};
//console.log("G2 newLine:", newLine);
//newLine.g2 = true;
newLine.arc = true;
newLine.clockwise = true;
if (args.clockwise === false) newLine.clockwise = args.clockwise;
cofg.addSegment(lastLine, newLine, args);
//console.log("G2", lastLine, newLine, args, cofg.offsetG92);
lastLine = newLine;
//console.log("G2. args:", args);
},
G3: function (args, indx, gcp) {
/* this is an arc move from lastLine's xy to the new xy. same
as G2 but reverse*/
args.arc = true;
args.clockwise = false;
//parser.handler.G2(args, indx, gcp);