-
Notifications
You must be signed in to change notification settings - Fork 649
/
toolpathworker.js
2090 lines (1917 loc) · 78.6 KB
/
toolpathworker.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
if (typeof window == "undefined") { // Only run as worker
var minimumToolDiaForPreview = 0.04;
var insideCutsColor = 0x660000;
var outsideCutsColor = 0x000066;
var pocketColor = 0x006600;
var toolpathColor = 0x666600;
self.addEventListener('message', function(e) {
// console.log("New message received by worker", e.data.data.length)
importScripts("/lib/clipperjs/clipper_unminified.js", "/lib/threejs/three.min.js", "/lib/gl-matrix.js", "/lib/tbfleming/web-cam-cpp.js");
var toolpaths = JSON.parse(e.data.data.toolpath);
var jobindex = e.data.data.index;
var performanceLimit = e.data.data.performanceLimit;
toolpathsjson = getToolpaths(toolpaths, jobindex, performanceLimit).toJSON();
var data = {
toolpath: JSON.stringify(toolpathsjson),
running: false,
index: jobindex
}
self.postMessage(data);
}, false);
function getToolpaths(toolpath, jobindex, performanceLimit) {
// Process Them
// console.log(toolpath)
var loader = new THREE.ObjectLoader();
var data = {
toolpaths: false,
running: true,
index: jobindex
}
self.postMessage(data);
var toolpath = loader.parse(toolpath);
config = {
index: jobindex,
toolpath: toolpath,
union: toolpath.userData.camUnion,
offset: toolpath.userData.camToolDia / 2,
leadinval: 0,
stepover: parseFloat(toolpath.userData.camStepover, 2),
zstart: parseFloat(toolpath.userData.camZStart, 2),
zstep: parseFloat(toolpath.userData.camZStep, 2),
zdepth: parseFloat(toolpath.userData.camZDepth, 2),
// tabdepth: parseFloat(toolpath.userData.camTabDepth, 2) * -1,
tabdepth: -(parseFloat(toolpath.userData.camZDepth) - parseFloat(toolpath.userData.camTabDepth)),
tabspace: parseFloat(toolpath.userData.camTabSpace, 2),
tabwidth: parseFloat(toolpath.userData.camTabWidth, 2),
direction: toolpath.userData.camDirection,
performanceLimit: performanceLimit,
};
var operation = toolpath.userData.camOperation;
var data = {
toolpaths: false,
running: true,
index: jobindex
}
self.postMessage(data);
if (!operation) {
console.log("Invalid Operation")
} else if (operation == "... Select Operation ...") {
console.log("No operation");
} else if (operation == "Laser: Vector (no path offset)") {
console.log("Laser: Vector (no path offset)");
config.zstart = 0
config.zstep = 0.1
config.zdepth = 0.1
config.offset = 0;
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "Laser: Vector (path inside)") {
console.log("Laser: Vector (path inside)");
config.zstart = 0
config.zstep = 0.1
config.zdepth = 0.1
config.offset = (toolpath.userData.camSpotSize / 2) * -1;
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "Laser: Vector (path outside)") {
config.zstart = 0
config.zstep = 0.1
config.zdepth = 0.1
config.offset = (toolpath.userData.camSpotSize / 2)
console.log("Laser: Vector (path outside)");
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "Laser: Vector (raster fill) (Beta)") {
config.offset = (toolpath.userData.camSpotSize / 2)
console.log("Laser: Vector (raster fill) (Beta)");
config.angle = toolpath.userData.camFillAngle || 0;
toolpath.userData.inflated = fillPath(config);
} else if (operation == "CNC: Vector (no offset)") {
console.log("CNC: Vector (no offset)");
config.offset = 0;
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "CNC: Vector (path inside)") {
console.log("CNC: Vector (path inside)");
config.offset = config.offset * -1;
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "CNC: Vector (path outside)") {
console.log("CNC: Vector (path outside)");
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "CNC: Pocket") {
console.log("CNC: Pocket");
toolpath.userData.inflated = workerPocketPath(config)
} else if (operation == "CNC: V-Engrave") {
console.log("CNC: V-Engrave");
// no op yet
} else if (operation == "Plasma: Vector (path outside)") {
console.log("Plasma: Vector (path outside)");
config.zstart = parseFloat(toolpath.userData.camPlasmaZHeight) * -2
config.zstep = parseFloat(toolpath.userData.camPlasmaZHeight)
config.zdepth = parseFloat(toolpath.userData.camPlasmaZHeight) * -1
config.offset = (toolpath.userData.camPlasmaKerf / 2)
config.leadinval = toolpath.userData.camPlasmaLeadinDist
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "Plasma: Vector (path inside)") {
console.log("Plasma: Vector (path inside)");
// config.offset = config.offset * -1;
config.zstart = parseFloat(toolpath.userData.camPlasmaZHeight) * -2
config.zstep = parseFloat(toolpath.userData.camPlasmaZHeight)
config.zdepth = parseFloat(toolpath.userData.camPlasmaZHeight) * -1
config.offset = (toolpath.userData.camPlasmaKerf / 2) * -1
config.leadinval = toolpath.userData.camPlasmaLeadinDist * -1
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "Plasma: Vector (no path offset)") {
console.log("Plasma: Vector (no path offset)");
config.zstart = parseFloat(toolpath.userData.camPlasmaZHeight) * -2
config.zstep = parseFloat(toolpath.userData.camPlasmaZHeight)
config.zdepth = parseFloat(toolpath.userData.camPlasmaZHeight) * -1
config.offset = 0;
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "Drag Knife: Cutout") {
console.log("Drag Knife: Cutout");
config.offset = toolpath.userData.camDragOffset;
toolpath.userData.inflated = workerDragknifePath(config)
} else if (operation == "Drill: Peck (Centered)") {
console.log("Drill: Peck (Centered)");
toolpath.userData.inflated = workerDrill(config)
} else if (operation == "Drill: Continuous (Centered)") {
console.log("Drill: Continuous (Centered)");
toolpath.userData.inflated = workerDrill(config)
} else if (operation == "Pen Plotter: (no offset)") {
console.log("Pen Plotter: (no offset)");
config.zstep = 0.1
config.zdepth = 0.1
config.offset = 0;
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "Pen Plotter: (path inside)") {
console.log();
config.zstep = 0.1
config.zdepth = 0.1
config.offset = config.offset * -1;
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "Pen Plotter: (path outside)") {
console.log("Pen Plotter: (path outside)");
config.zstep = 0.1
config.zdepth = 0.1
toolpath.userData.inflated = workerInflateToolpath(config)
} else if (operation == "Pen Plotter: (lines fill)") {
console.log("Pen Plotter: (lines fill)");
config.offset = (toolpath.userData.camSpotSize / 2)
config.angle = toolpath.userData.camFillAngle || 0;
toolpath.userData.inflated = fillPath(config);
}
// console.log("Finished " + q+ " of " +toolpaths.length)
var data = {
toolpaths: false,
running: false,
index: jobindex
}
self.postMessage(data);
console.log(toolpath.userData.inflated.children.length)
// console.log('Finished all the toolpaths')
return toolpath
}
function workerInflateToolpath(config) {
//console.log(config)
var inflateGrpZ = new THREE.Group();
var prettyGrp = new THREE.Group();
var clipperPaths = workerGetClipperPaths(config.toolpath)
// clipperPaths = tryFixGeometry(clipperPaths)
// console.log('Original Toolpath: ', JSON.stringify(clipperPaths))
if (config.union == "Yes") {
// simplify this set of paths which is a very powerful Clipper call that figures out holes and path orientations
var newClipperPaths = workerSimplifyPolygons(clipperPaths);
if (newClipperPaths.length < 1) {
console.error("Clipper Simplification Failed!:");
}
if (config.offset != 0) {
var inflatedPaths = workerGetInflatePath(newClipperPaths, config.offset);
} else {
var inflatedPaths = newClipperPaths;
}
if (config.direction == "Climb") {
// reverse here
if (config.offset > 0) {
for (i = 0; i < inflatedPaths.length; i++) {
inflatedPaths[i].reverse();
}
}
} else if (config.direction == "Conventional") {
if (config.offset < 0) {
for (i = 0; i < inflatedPaths.length; i++) {
inflatedPaths[i].reverse();
}
}
}
// console.log(inflatedPaths);
if (config.leadinval != 0) { // plasma lead-in
var leadInPaths = workerGetInflatePath(newClipperPaths, config.leadinval);
//console.log(leadInPaths)
}
for (i = config.zstart + config.zstep; i < config.zdepth + config.zstep; i += config.zstep) {
if (i > config.zdepth) {
var zval = -config.zdepth;
} else {
var zval = -i
}
// console.log(i * config.zstep > config.zdepth, i * config.zstep, i, zval)
// console.log(i, config.zstart, config.zstep, config.zdepth, zval);
var drawClipperPathsconfig = {
performanceLimit: config.performanceLimit,
paths: inflatedPaths,
color: toolpathColor,
opacity: 1,
z: zval,
name: 'inflateGrp',
leadInPaths: leadInPaths,
tabdepth: config.tabdepth,
tabspace: config.tabspace,
tabwidth: config.tabwidth,
toolDia: config.offset * 2,
drawPretty: true,
prettyGrpColor: (config.offset < 0) ? insideCutsColor : outsideCutsColor
}
var drawings = drawClipperPathsWithTool(drawClipperPathsconfig);
inflateGrp = drawings.lines;
inflateGrp.name = 'inflateGrp' + i;
inflateGrp.userData.material = inflateGrp.material;
inflateGrpZ.add(inflateGrp);
if (drawings.pretty) {
prettyGrp.add(drawings.pretty)
prettyGrp.updateMatrixWorld()
}
}
// end config.union = "Yes"
} else { // begin config.union="No"
var newClipperPaths = clipperPaths;
for (j = 0; j < newClipperPaths.length; j++) {
if (config.offset != 0) {
var inflatedPaths = workerGetInflatePath([newClipperPaths[j]], config.offset);
} else {
var inflatedPaths = [newClipperPaths[j]];
}
if (config.direction == "Climb") {
// reverse here
if (config.offset > 0) {
for (i = 0; i < inflatedPaths.length; i++) {
inflatedPaths[i].reverse();
}
}
} else if (config.direction == "Conventional") {
if (config.offset < 0) {
for (i = 0; i < inflatedPaths.length; i++) {
inflatedPaths[i].reverse();
}
}
}
if (inflatedPaths.length < 1) {
console.error("Clipper Inflate Failed!:");
}
// plasma lead-in
if (config.leadinval != 0) {
var leadInPaths = workerGetInflatePath([newClipperPaths[j]], config.leadinval);
//console.log(leadInPaths[0][0])
}
for (i = config.zstart + config.zstep; i < config.zdepth + config.zstep; i += config.zstep) {
if (i > config.zdepth) {
var zval = -config.zdepth;
} else {
var zval = -i
}
// console.log(i, config.zstart, config.zstep, config.zdepth, zval);
var drawClipperPathsconfig = {
performanceLimit: config.performanceLimit,
paths: inflatedPaths,
color: toolpathColor,
opacity: 1,
z: zval,
name: 'inflateGrp',
leadInPaths: leadInPaths,
tabdepth: config.tabdepth,
tabspace: config.tabspace,
tabwidth: config.tabwidth,
toolDia: config.offset * 2,
drawPretty: true,
prettyGrpColor: (config.offset < 0) ? insideCutsColor : outsideCutsColor
}
var drawings = drawClipperPathsWithTool(drawClipperPathsconfig);
inflateGrp = drawings.lines;
inflateGrp.name = 'inflateGrp' + i;
inflateGrp.userData.material = inflateGrp.material;
inflateGrpZ.add(inflateGrp);
if (drawings.pretty) {
prettyGrp.add(drawings.pretty)
prettyGrp.updateMatrixWorld()
}
}
}
} // end config.union="No"
if (config.offset > minimumToolDiaForPreview || config.offset < -minimumToolDiaForPreview) { //Dont show for very small offsets, not worth the processing time
inflateGrpZ.userData.pretty = prettyGrp
};
inflateGrpZ.userData.toolDia = config.offset * 2
return inflateGrpZ;
}
function workerSimplifyPolygons(paths) {
var scale = 10000;
ClipperLib.JS.ScaleUpPaths(paths, scale);
var newClipperPaths = ClipperLib.Clipper.SimplifyPolygons(paths, ClipperLib.PolyFillType.pftEvenOdd);
ClipperLib.JS.ScaleDownPaths(newClipperPaths, scale);
ClipperLib.JS.ScaleDownPaths(paths, scale);
return newClipperPaths;
};
function workerGetInflatePath(paths, delta, joinType) {
//console.log(JSON.stringify(paths));
var scale = 10000;
ClipperLib.JS.Clean(paths, 2);
ClipperLib.JS.ScaleUpPaths(paths, scale);
var miterLimit = 3;
var arcTolerance = 200;
joinType = joinType ? joinType : ClipperLib.JoinType.jtRound;
var co = new ClipperLib.ClipperOffset(miterLimit, arcTolerance);
co.AddPaths(paths, joinType, ClipperLib.EndType.etClosedPolygon);
var offsetted_paths = new ClipperLib.Paths();
co.Execute(offsetted_paths, delta * scale);
// scale back down
ClipperLib.JS.ScaleDownPaths(offsetted_paths, scale);
ClipperLib.JS.ScaleDownPaths(paths, scale);
return offsetted_paths;
};
function workerGetClipperPaths(object) {
object.updateMatrix();
var grp = object;
var clipperPaths = [];
grp.traverse(function(child) {
// console.log('Traverse: ', child)
if (child.name == "inflatedGroup") {
console.log("this is the inflated path from a previous run. ignore.");
return;
} else if (child.type == "Line") {
// let's inflate the path for this line. it may not be closed
// so we need to check that.
var clipperArr = [];
// Fix world Coordinates
for (j = 0; j < child.geometry.vertices.length; j++) {
var localPt = child.geometry.vertices[j];
var worldPt = child.localToWorld(localPt.clone());
var xpos = worldPt.x; // + (sizexmax /2);
var ypos = worldPt.y; // + (sizeymax /2);
var xpos_offset = (parseFloat(child.position.x.toFixed(3)));
var ypos_offset = (parseFloat(child.position.y.toFixed(3)));
if (child.geometry.type == "CircleGeometry") {
xpos = (xpos + xpos_offset);
ypos = (ypos + ypos_offset);
}
clipperArr.push({
X: xpos,
Y: ypos
});
}
clipperPaths.push(clipperArr);
} else {
// console.log("type of ", child.type, " being skipped");
}
});
return clipperPaths
}
drawClipperPaths = function(config) {
if (config.leadInPaths) {
if (config.leadInPaths.length != config.paths.length) {
console.log("Skipping lead-in: Source vector file is broken, and we could not produce a reliable offset")
printLog('Skipping lead-in: Source vector file is broken, and we could not produce a reliable offset', warncolor, "settings");
}
}
// console.log("Compare lead-in: " + paths.length + " / " + leadInPaths.length)
var lineUnionMat = new THREE.LineBasicMaterial({
color: config.color,
transparent: true,
opacity: config.opacity,
});
if (config.z === undefined || config.z == null) {
config.z = 0;
// console.log("config.z not defined")
}
var group = new THREE.Object3D();
if (config.name) group.name = config.name;
for (var i = 0; i < config.paths.length; i++) {
var lineUnionGeo = new THREE.Geometry();
if (config.leadInPaths) {
if (leadInPaths.length == paths.length) {
lineUnionGeo.vertices.push(new THREE.Vector3(config.leadInPaths[i][0].X, config.leadInPaths[i][0].Y, z));
}
}
var totalDist = 0;
var lastTabPos = -config.tabspace;
var lastvert = {
x: 0,
y: 0,
z: 0
}
var lastTabPos = -config.tabspace;
for (var j = 0; j < config.paths[i].length; j++) {
// console.log(j)
totalDist += distanceFormula(lastvert.x, config.paths[i][j].X, lastvert.y, config.paths[i][j].Y)
if (totalDist > (lastTabPos + config.tabspace) && config.z < config.tabdepth) {
if (config.z < -config.tabdepth && j < config.paths[i].length - 1) {
// console.log(i, j)
var d = distanceFormula(config.paths[i][j].X, config.paths[i][j + 1].X, config.paths[i][j].Y, config.paths[i][j + 1].Y)
if (d >= (config.toolDia + config.tabwidth)) {
var numTabs = Math.round(d / (config.tabspace + config.tabwidth));
// if we have a line distance of 100
// and 3 tabs (width 10) in that line per numTabs
// then we want to evenly space them
// so we divide the line distance by numTabs
var spacePerTab = d / numTabs;
// which in this example would be 33.33~
// then in each space per tab we need to center the tab
// which means dividing the difference of the spacePerTab and tabWidth by 2
var tabPaddingPerSpace = (spacePerTab - (config.tabwidth + config.toolDia)) / 2;
// console.log("Adding tab")
// next point
var deltaX = config.paths[i][j + 1].X - config.paths[i][j].X;
var deltaY = config.paths[i][j + 1].Y - config.paths[i][j].Y;
// get the line angle
var ang = Math.atan2(deltaY, deltaX);
// console.log(' ANGLE ' + (ang * 180 / Math.PI));
// convert it to degrees for later math with addDegree
ang = ang * 180 / Math.PI;
lastTabPos = totalDist;
var npt = [config.paths[i][j].X, config.paths[i][j].Y]
for (var r = 0; r < numTabs; r++) {
// then for each tab
// add another point at the current point +tabPaddingPerSpace
npt = newPointFromDistanceAndAngle(npt, ang, tabPaddingPerSpace);
// g += 'G1' + feedrate + ' X' + npt[0] + ' Y' + npt[1] + '\n';
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.z));
// then we raise the z height by config.tabHeight
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.tabdepth));
// g += 'G0 Z' + tabsBelowZ + '\n';
// then add another point at the current point +tabWidth
npt = newPointFromDistanceAndAngle(npt, ang, config.tabwidth + config.toolDia);
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.tabdepth));
// g += 'G0' + feedrate + ' X' + npt[0] + ' Y' + npt[1] + '\n';
// then lower the z height back to zPos at plunge speed
// g += 'G0 F' + plungeSpeed + ' Z' + tabsBelowZ + '\n';
// g += 'G1 F' + plungeSpeed + ' Z' + zpos + '\n';
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.z));
// then add another point at the current point +tabPaddingPerSpace
// with the cut speed
npt = newPointFromDistanceAndAngle(npt, ang, tabPaddingPerSpace);
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.z));
// g += 'G1' + feedrate + ' X' + npt[0] + ' Y' + npt[1] + '\n';
}
} else {
lineUnionGeo.vertices.push(new THREE.Vector3(config.paths[i][j].X, config.paths[i][j].Y, config.z));
}
} else {
lineUnionGeo.vertices.push(new THREE.Vector3(config.paths[i][j].X, config.paths[i][j].Y, config.vz));
}
} else {
lineUnionGeo.vertices.push(new THREE.Vector3(config.paths[i][j].X, config.paths[i][j].Y, config.z));
}
// lineUnionGeo.vertices.push(new THREE.Vector3(paths[i][j].X, paths[i][j].Y, z));
lastvert = {
x: config.paths[i][j].X,
y: config.paths[i][j].Y,
z: config.z
}
}
// close it by connecting last point to 1st point - if its not an open ended vector
if (config.paths[i].length > 2) {
lineUnionGeo.vertices.push(new THREE.Vector3(config.paths[i][0].X, config.paths[i][0].Y, config.z));
}
if (config.leadInPaths) {
if (leadInPaths.length == paths.length) {
lineUnionGeo.vertices.push(new THREE.Vector3(config.leadInPaths[i][0].X, config.leadInPaths[i][0].Y, config.z));
}
}
var lineUnion = new THREE.Line(lineUnionGeo, lineUnionMat);
if (config.name) {
lineUnion.name = config.name;
}
group.add(lineUnion);
}
return group;
};
drawClipperPathsWithTool = function(config) {
// console.log(JSON.stringify(config));
var group = new THREE.Object3D();
if (config.leadInPaths) {
if (config.leadInPaths.length != config.paths.length) {
console.log("Skipping lead-in: Source vector file is broken, and we could not produce a reliable offset")
// printLog('Skipping lead-in: Source vector file is broken, and we could not produce a reliable offset', warncolor, "settings");
}
}
var lineUnionMat = new THREE.LineBasicMaterial({
color: config.color,
transparent: true,
opacity: config.opacity,
});
if (config.z === undefined || config.z == null) {
config.z = 0;
// console.log("with tool config.z not defined")
}
if (config.name) group.name = config.name;
if (config.toolDia < 0) {
config.toolDia = config.toolDia * -1;
}
var clipperPaths = [];
var clipperTabsPaths = [];
for (var i = 0; i < config.paths.length; i++) {
var clipperArr = [];
var clipperTabsArr = [];
var lineUnionGeo = new THREE.Geometry();
if (config.leadInPaths) { // 2021-03-16 This is where the lead-in starts. Added sorting of leadInPaths array to find closest vector to start of Main Vector
if (config.leadInPaths.length == config.paths.length) {
var pointIndex = 0
//console.log(config.leadInPaths[i][0])
config.leadInPaths[i].sort(function(a, b) {
return distanceFormula(a.X, config.paths[i][0].X, a.Y, config.paths[i][0].Y) - distanceFormula(b.X, config.paths[i][0].X, b.Y, config.paths[i][0].Y)
})
//console.log(config.leadInPaths[i][0])
lineUnionGeo.vertices.push(new THREE.Vector3(config.leadInPaths[i][pointIndex].X, config.leadInPaths[i][pointIndex].Y, config.z));
clipperArr.push({
X: config.leadInPaths[i][pointIndex].X,
Y: config.leadInPaths[i][pointIndex].Y
});
}
}
var totalDist = 0;
var lastTabPos = -config.tabspace;
var lastvert = {
x: 0,
y: 0,
z: 0
}
var lastTabPos = -config.tabspace;
for (var j = 0; j < config.paths[i].length; j++) {
// console.log(j)
totalDist += distanceFormula(lastvert.x, config.paths[i][j].X, lastvert.y, config.paths[i][j].Y)
if (config.tabwidth) {
if (totalDist > (lastTabPos + config.tabspace) && config.z < config.tabdepth) {
if (j < config.paths[i].length) {
// console.log(i, j)
if (j < config.paths[i].length - 1) {
var d = distanceFormula(config.paths[i][j].X, config.paths[i][j + 1].X, config.paths[i][j].Y, config.paths[i][j + 1].Y)
} else {
var d = distanceFormula(config.paths[i][j].X, config.paths[i][0].X, config.paths[i][j].Y, config.paths[i][0].Y)
}
if (d >= (config.toolDia + config.tabwidth)) {
console.log('long enough')
var numTabs = Math.round(d / (config.tabspace + config.tabwidth));
// if we have a line distance of 100
// and 3 tabs (width 10) in that line per numTabs
// then we want to evenly space them
// so we divide the line distance by numTabs
var spacePerTab = d / numTabs;
// which in this example would be 33.33~
// then in each space per tab we need to center the tab
// which means dividing the difference of the spacePerTab and tabWidth by 2
var tabPaddingPerSpace = (spacePerTab - (config.tabwidth + config.toolDia)) / 2;
// console.log("Adding tab")
// next point
if (j < config.paths[i].length - 1) {
var deltaX = config.paths[i][j + 1].X - config.paths[i][j].X;
var deltaY = config.paths[i][j + 1].Y - config.paths[i][j].Y;
} else {
var deltaX = config.paths[i][0].X - config.paths[i][j].X;
var deltaY = config.paths[i][0].Y - config.paths[i][j].Y;
}
// get the line angle
var ang = Math.atan2(deltaY, deltaX);
// console.log(' ANGLE ' + (ang * 180 / Math.PI));
// convert it to degrees for later math with addDegree
ang = ang * 180 / Math.PI;
lastTabPos = totalDist;
var npt = [config.paths[i][j].X, config.paths[i][j].Y]
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.z));
clipperArr.push({
X: npt[0],
Y: npt[1]
});
for (var r = 0; r < numTabs; r++) {
var clipperTabsArr = [];
// then for each tab
// add another point at the current point +tabPaddingPerSpace
npt = newPointFromDistanceAndAngle(npt, ang, tabPaddingPerSpace);
// g += 'G1' + feedrate + ' X' + npt[0] + ' Y' + npt[1] + '\n';
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.z));
clipperArr.push({
X: npt[0],
Y: npt[1]
});
clipperTabsArr.push({
X: npt[0],
Y: npt[1]
});
// then we raise the z height by config.tabHeight
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.tabdepth));
clipperArr.push({
X: npt[0],
Y: npt[1]
});
clipperTabsArr.push({
X: npt[0],
Y: npt[1]
});
// g += 'G0 Z' + tabsBelowZ + '\n';
// then add another point at the current point +tabWidth
npt = newPointFromDistanceAndAngle(npt, ang, config.tabwidth + config.toolDia);
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.tabdepth));
clipperArr.push({
X: npt[0],
Y: npt[1]
});
clipperTabsArr.push({
X: npt[0],
Y: npt[1]
});
// g += 'G0' + feedrate + ' X' + npt[0] + ' Y' + npt[1] + '\n';
// then lower the z height back to zPos at plunge speed
// g += 'G0 F' + plungeSpeed + ' Z' + tabsBelowZ + '\n';
// g += 'G1 F' + plungeSpeed + ' Z' + zpos + '\n';
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.z));
clipperArr.push({
X: npt[0],
Y: npt[1]
});
clipperTabsArr.push({
X: npt[0],
Y: npt[1]
});
// then add another point at the current point +tabPaddingPerSpace
// with the cut speed
npt = newPointFromDistanceAndAngle(npt, ang, tabPaddingPerSpace);
lineUnionGeo.vertices.push(new THREE.Vector3(npt[0], npt[1], config.z));
clipperArr.push({
X: npt[0],
Y: npt[1]
});
clipperTabsPaths.push(clipperTabsArr);
// g += 'G1' + feedrate + ' X' + npt[0] + ' Y' + npt[1] + '\n';
}
} else { // line isnt long enough
lineUnionGeo.vertices.push(new THREE.Vector3(config.paths[i][j].X, config.paths[i][j].Y, config.z));
clipperArr.push({
X: config.paths[i][j].X,
Y: config.paths[i][j].Y
});
}
} else { // is last point
lineUnionGeo.vertices.push(new THREE.Vector3(config.paths[i][j].X, config.paths[i][j].Y, config.z));
clipperArr.push({
X: config.paths[i][j].X,
Y: config.paths[i][j].Y
});
}
} else { // havent moved far enough yet
lineUnionGeo.vertices.push(new THREE.Vector3(config.paths[i][j].X, config.paths[i][j].Y, config.z));
clipperArr.push({
X: config.paths[i][j].X,
Y: config.paths[i][j].Y
});
}
} else { // no valid config.tabwidth found
lineUnionGeo.vertices.push(new THREE.Vector3(config.paths[i][j].X, config.paths[i][j].Y, config.z));
clipperArr.push({
X: config.paths[i][j].X,
Y: config.paths[i][j].Y
});
}
// lineUnionGeo.vertices.push(new THREE.Vector3(paths[i][j].X, paths[i][j].Y, z));
lastvert = {
x: config.paths[i][j].X,
y: config.paths[i][j].Y,
z: config.z
}
} // end for loop j < paths[i].length
// close it by connecting last point to 1st point
// Handle open ended single line here by not adding point
if (config.paths[i].length > 2) {
lineUnionGeo.vertices.push(new THREE.Vector3(config.paths[i][0].X, config.paths[i][0].Y, config.z));
clipperArr.push({
X: config.paths[i][0].X,
Y: config.paths[i][0].Y
});
}
// if (config.leadInPaths) {
// if (config.leadInPaths.length == config.paths.length) {
// lineUnionGeo.vertices.push(new THREE.Vector3(config.leadInPaths[i][0].X, config.leadInPaths[i][0].Y, config.z));
// clipperArr.push({
// X: config.leadInPaths[i][0].X,
// Y: config.leadInPaths[i][0].Y
// });
// }
// }
var lineUnion = new THREE.Line(lineUnionGeo, lineUnionMat);
if (config.name) {
lineUnion.name = config.name;
}
//console.log(lineUnionGeo)
group.add(lineUnion);
clipperPaths.push(clipperArr);
clipperTabsPaths.push(clipperTabsArr);
} // end for loop i < paths.length
// If High performance is available, draw the 3D view
if (!config.performanceLimit) {
var prettyGrp = new THREE.Group();
var prettyGrpColor = config.prettyGrpColor;
if (config.z < config.tabdepth) { //draw with tabs
if (config.toolDia > minimumToolDiaForPreview || config.toolDia < -minimumToolDiaForPreview) { //Dont show for very small offsets, not worth the processing time
// generate once use again
// for each z
var lineMesh = this.getMeshLineFromClipperPath({
width: config.toolDia,
clipperPath: clipperPaths,
isSolid: true,
opacity: 0.2,
isShowOutline: true,
color: config.prettyGrpColor,
caps: "round"
});
lineMesh.position.z = config.z;
prettyGrp.add(lineMesh)
var lineMesh = this.getMeshLineFromClipperPath({
width: config.toolDia,
clipperPath: clipperTabsPaths,
isSolid: true,
opacity: 1,
isShowOutline: true,
color: 0x00ff00,
caps: "negative"
});
lineMesh.position.z = config.z;
lineMesh.name = "LineMesh2"
// for (r= 0; r < lineMesh.children.length; r++) {
// for (s=0; s> lineMesh.children[r].children.length; s++) {
// lineMesh.children[r].children[s].geometry.translate(lineMesh.position.x, lineMesh.position.y, lineMesh.position.z)
// }
// }
// lineMesh.position.x = 0;
// lineMesh.position.y = 0;
// lineMesh.position.z = 0;
prettyGrp.add(lineMesh)
// end if High Performance
}
} else { // without tabs
if (config.toolDia > minimumToolDiaForPreview || config.toolDia < -minimumToolDiaForPreview) { //Dont show for very small offsets, not worth the processing time
// generate once use again for each z
// if High Performance is available
var lineMesh = this.getMeshLineFromClipperPath({
width: config.toolDia,
clipperPath: config.paths,
isSolid: true,
opacity: 0.2,
isShowOutline: true,
color: config.prettyGrpColor,
caps: "round"
});
lineMesh.position.z = config.z;
lineMesh.name = "LineMesh3"
prettyGrp.add(lineMesh)
}
}
var grp = {
lines: group,
pretty: prettyGrp
}
// End if High Performance
} else {
var grp = {
lines: group,
pretty: false
}
}
return grp;
};
distanceFormula = function(x1, x2, y1, y2) {
// get the distance between p1 and p2
var a = (x2 - x1) * (x2 - x1);
var b = (y2 - y1) * (y2 - y1);
return Math.sqrt(a + b);
};
newPointFromDistanceAndAngle = function(pt, ang, distance) {
// use cos and sin to get a new point with an angle
// and distance from an existing point
// pt = [x,y]
// ang = in degrees
// distance = N
var r = [];
r.push(pt[0] + (distance * Math.cos(ang * Math.PI / 180)));
r.push(pt[1] + (distance * Math.sin(ang * Math.PI / 180)));
return r;
};
// borrowed code from https://github.com/chilipeppr/widget-eagle/blob/master/widget.js
function getMeshLineFromClipperPath(opts) {
// console.log(opts);
var width = opts.width ? opts.width : 1;
var paths = opts.clipperPath;
var isSolid = 'isSolid' in opts ? opts.isSolid : true;
var color = opts.color ? opts.color : 0x0000ff;
var opacity = opts.opacity ? opts.opacity : 0.3;
var isShowOutline = 'isShowOutline' in opts ? opts.isShowOutline : false;
var retGrp = new THREE.Group();
var cap = opts.caps;
var localInflateBy = width / 2;
// loop thru all paths and draw a mesh stroke
// around the path with opacity set, such that when
// multiples meshes are overlaid, their colors are darker
// to visualize the toolpath. that means creating normals
// for each pt and generating triangles to create mesh
var group = new THREE.Object3D();
var pathCtr = 0;
paths.forEach(function(path) {
// create a clipper stroke path for each line segment
// we won't create one for the last pt because there's no line
// after it
// var clipperStrokes = [];
var csThisPath = [];
//console.log("calculating stroke paths for each path");
for (var pi = 0; pi < path.length; pi++) {
// console.log(path[pi])
var pt = path[pi];
var pt2 = (pi + 1 < path.length) ? path[pi + 1] : path[0];
// console.log(pt, pt2)
if (pt2 != null) {
var clipperStroke = addStrokeCapsToLine(pt.X, pt.Y, pt2.X, pt2.Y, localInflateBy * 2, cap, color);
// console.log(clipperStroke)
// if (clipperStroke.length > 1) console.warn("got more than 1 path on clipperStroke");
// if (clipperStroke.length < 1) console.warn("got less than 1 path on clipperStroke");
csThisPath.push(clipperStroke[0] || [{
X: 0,
Y: 0
}]);
}
}
// console.log(csThisPath);
var csUnion = getUnionOfClipperPaths(csThisPath, false, false);
// var csUnion = csThisPath
if (isShowOutline) {
// console.log("isShowOutline")
var drawClipperPathsconfig = {
performanceLimit: config.performanceLimit,
paths: csUnion,
color: color,
opacity: opacity + 0.2,
z: 0,
name: false,
leadInPaths: false,
tabdepth: false,
tabspace: false,
tabwidth: false,
toolDia: false,
drawPretty: false
}
var threeObj = drawClipperPaths(drawClipperPathsconfig);
// var threeObj = drawClipperPaths(csUnion, color, opacity + 0.1, 0);
retGrp.add(threeObj);
}
// This is SUPER SLOW cuz of the triangle calculation
if (isSolid) {
//if (csUnion.length > 1) console.warn("got more than 1 path on union");
// investigate holes
var csUnionHoles = [];
var csUnionOuter = [];
var ctr = 0;
csUnion.forEach(function(path) {
if (ClipperLib.Clipper.Orientation(path)) {
// do nothing.
//console.log("outer path:", path);
csUnionOuter.push(path);
} else {
//console.warn("found a hole:", path);
csUnionHoles.push(path);
}
ctr++;
}, this);
if (csUnionOuter.length > 1) console.warn("got more than 1 outer path");
var mesh = this.createClipperPathsAsMesh(csUnionOuter, color, opacity, csUnionHoles);
// this.sceneAdd(mesh);
retGrp.add(mesh);
}
pathCtr++;
}, this);
retGrp.name = "retGrp"
return retGrp;
}
function addStrokeCapsToLine(x1, y1, x2, y2, width, capType, color) {
// console.log("addStrokeCapsToLine", capType)
if (width < 0) {
width = width * -1;
}
var cap = capType
// console.log(cap, capType)
// we are given a line with two points. to stroke and cap it
// we will draw the line in THREE.js and then shift x1/y1 to 0,0
// for the whole line
// then we'll rotate it to 3 o'clock
// then we'll shift it up on x to half width
// we'll create new vertexes on -x for half width
// we then have a drawn rectangle that's the stroke
// we'll add a circle at the start and end point for the cap
// then we'll unrotate it
// then we'll unshift it
var group = new THREE.Object3D();
group.name = "addStrokeCapsToLine"
var lineGeo = new THREE.Geometry();
lineGeo.vertices.push(new THREE.Vector3(x1, y1, 0));
lineGeo.vertices.push(new THREE.Vector3(x2, y2, 0));
var lineMat = new THREE.LineBasicMaterial({
color: color,
transparent: true,
opacity: 1
});
var line = new THREE.Line(lineGeo, lineMat);
line.name = "Line with cap"
// shift to make x1/y1 zero
line.position.set(x1 * -1, y1 * -1, 0);