forked from jpadie/widget-grbl-autolevel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwidget.js
2378 lines (2077 loc) · 101 KB
/
widget.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
/* global $ chilipeppr requirejs cprequire cprequire_test cpdefine localStorage THREE */
requirejs.config({
paths: {
// Three: '//i2dcui.appspot.com/geturl?url=http://threejs.org/build/three.js',
Three: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r76/three',
ThreeTextGeometry: '//i2dcui.appspot.com/js/three/TextGeometry',
ThreeFontUtils: '//i2dcui.appspot.com/js/three/FontUtils',
ThreeHelvetiker: '//i2dcui.appspot.com/js/three/threehelvetiker'
},
shim: {
ThreeTextGeometry: ['Three'],
ThreeFontUtils: ['Three', 'ThreeTextGeometry'],
ThreeHelvetiker: ['Three', 'ThreeTextGeometry', 'ThreeFontUtils'],
}
});
//make change
// make sure Helvetiker loads
/*
var ThreeHelvetiker;
console.log("Making sure font load code run first.");
window["_typeface_js"] = {loadFace: function(data) {
console.log("apparently we're supposed to load Helvetiker here???");
ThreeHelvetiker = data;
}};
console.log(window["_typeface_js"]);
*/
// Test this element. This code is auto-removed by the chilipeppr.load()
cprequire_test(["inline:com-chilipeppr-widget-autolevel"], function(autolevel) {
console.log("test running of " + autolevel.id);
autolevel.init();
$('#com-chilipeppr-widget-autolevel').css('position', 'relative');
$('#com-chilipeppr-widget-autolevel').css('background', 'none');
$('body').prepend('<div id="3dviewer"></div>');
chilipeppr.load("#3dviewer", "http://fiddle.jshell.net/chilipeppr/y3HRF/show/light/", function() {
cprequire(['inline:com-chilipeppr-widget-3dviewer'], function(threed) {
threed.init({ doMyOwnDragDrop: true });
$('#com-chilipeppr-widget-3dviewer .panel-heading').addClass('hidden');
//autolevel.addRegionTo3d();
//autolevel.loadFileFromLocalStorageKey('com-chilipeppr-widget-autolevel-recent8');
//autolevel.toggleShowMatrix();
});
});
//mimic probe request, respond with generic x,y,z coordinates for testing
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/send", this, function(data) {
if (data.search(/G38/g) >= 0)
chilipeppr.publish("/com-chilipeppr-interface-cnccontroller/proberesponse", { "x": 0, "y": 0, "z": -1.232 });
});
/*
// we mimic the /send and /recvline serial port methods here for testing
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/send", this, function(data) {
// when we get a send of {"z":""} reply back as if the tinyg is sending it
if (data == '{"z":""}\n') {
setTimeout(function() {
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {dataline:'{"r":{"z":{"am":1,"vm":400,"fr":200,"tm":70,"jm":3000000,"jh":20000000,"jd":0.0500,"sn":1,"sx":0,"sv":20,"lv":10,"lb":10.000,"zb":0.000},"f":[1,0,9,7178]}}'});
}, 1000);
}
if (data == "G28.2 Z0\n") {
var sr = '{"sr":{"mpoz":0.118}}\n' +
'{"sr":{"mpoz":0.084}}\n' +
'{"sr":{"mpoz":0.051}}\n' +
'{"sr":{"vel":26.58,"mpoz":0.038,"coor":0,"dist":1,"stat":9}}\n' +
'{"sr":{"mpoz":0.018}}\n' +
'{"sr":{"mpoz":-0.014}}\n' +
'{"sr":{"vel":19.94,"mpoz":-0.047}}\n' +
'{"sr":{"vel":0.95,"mpoz":-0.065}}\n' +
'{"sr":{"vel":0.00,"mpoz":-0.065,"stat":3}}\n' +
'{"qr":27}\n' +
'{"sr":{"vel":9.94,"mpoz":-0.058,"stat":9}}\n' +
'{"sr":{"vel":10.00,"mpoz":-0.042}}\n' +
'{"sr":{"mpoz":-0.025}}\n' +
'{"sr":{"mpoz":-0.009}}\n' +
'{"sr":{"vel":0.25,"mpoz":0.002}}\n' +
'{"qr":28}\n' +
//'{"sr"{"sr":{"vel":0.00,"stat":3}}\n';
'{"sr"{"sr":{"mpoz":0.000,"coor":1,"dist":0}}\n';
var srs = sr.split(/\n/);
var delay = 0;
srs.forEach(function(item) {
delay += 100;
setTimeout(function() {
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {dataline:item + "\n"});
}, delay);
});
}
});
*/
//var testFinalData = [];
//autolevel.loadTestData(testFinalData);
//autolevel.loadFileFromLocalStorageKey('com-chilipeppr-widget-autolevel-recent6');
} /*end_test*/ );
cpdefine("inline:com-chilipeppr-widget-autolevel", ["chilipeppr_ready", "ThreeHelvetiker", "Three"], function() {
return {
id: "com-chilipeppr-widget-autolevel",
url: "(auto fill by runme.js)", // The final URL of the working widget as a single HTML file with CSS and Javascript inlined. You can let runme.js auto fill this if you are using Cloud9.
fiddleurl: "(auto fill by runme.js)", // The edit URL. This can be auto-filled by runme.js in Cloud9 if you'd like, or just define it on your own to help people know where they can edit/fork your widget
githuburl: "(auto fill by runme.js)", // The backing github repo
testurl: "(auto fill by runme.js)", // The standalone working widget so can view it working by itself
name: "Widget / Auto-Level",
desc: "Allows you to auto-level your PCB before milling. Most raw PCB boards have a slight warpage. This widget lets you probe the warpage and then it auto-scales your Gcode to match the warpage so you get very clean/predictable z-positions in your milling job.",
publish: {},
subscribe: {},
foreignPublish: {
"/com-chilipeppr-widget-3dviewer/sceneadd": "We ask the 3D viewer to add THREE.js objects to the scene.",
"/com-chilipeppr-widget-3dviewer/sceneremove": "We ask the 3D viewer to remove THREE.js objects from the scene.",
"/com-chilipeppr-widget-3dviewer/request3dObject": "We ask the 3D viewer to send us the user object being shown in 3D viewer so we can analyze it. In particular, we want to know its bounding box for calculating the probe area."
},
foreignSubscribe: {
"/com-chilipeppr-widget-3dviewer/recv3dObject": "When we request a /com-chilipeppr-widget-3dviewer/request3dObject we get back this signal and the payload is the actual user object so we can analyze it.",
"/com-chilipeppr-interface-cnccontroller/proberesponse": "we receive the parsed probe trigger coordinates back from the cnc interface."
},
init: function() {
this.forkSetup();
$('#com-chilipeppr-widget-autolevel-showregion').click(this.addRegionTo3d.bind(this));
$('#com-chilipeppr-widget-autolevel-hideregion').click(this.removeRegionFrom3d.bind(this));
$('#com-chilipeppr-widget-autolevel-body .autolevel-elem').blur(this.formUpdate.bind(this));
$('.com-chilipeppr-widget-autolevel-autofill').click(this.autoFillData.bind(this));
$('.com-chilipeppr-widget-autolevel-run').click(this.startAutoLevel.bind(this));
$('.com-chilipeppr-widget-autolevel-stop').click(this.stopAutoLevel.bind(this));
$('.com-chilipeppr-widget-autolevel-pause').click(this.pause.bind(this));
$('.com-chilipeppr-widget-autolevel-toggleInterpolate').on('click', function() {
$(this).toggleClass('btn-success');
}).hide();
// toggleprobearea
$('.com-chilipeppr-widget-autolevel-toggleprobearea').click(this.toggleProbeArea.bind(this));
// runTestProbe
$('.com-chilipeppr-widget-autolevel-runtestprobe').click(this.runTestProbe.bind(this));
// gcodesendtows
$('.com-chilipeppr-widget-autolevel-gcodesendtows').click(this.sendGcodeToWorkspace.bind(this));
// run this method after modal is dismissed
//$('#com-chilipeppr-widget-modal-autolevel-start').on('hidden.bs.modal', this.modalComplete.bind(this));
$('#com-chilipeppr-widget-modal-autolevel-start .btn-autolevel-go').click(this.modalComplete.bind(this));
$('.com-chilipeppr-widget-autolevel-togglematrix').click(this.toggleShowMatrix.bind(this));
$('.com-chilipeppr-widget-autolevel-viewdata').click(this.showData.bind(this));
// setup del files
$('#com-chilipeppr-widget-autolevel .recent-file-delete').click(this.deleteRecentFiles.bind(this));
this.buildRecentFileMenu();
// paste loader
$('#com-chilipeppr-widget-autolevel .dropdown-menu .paste-load').click(function(e) {
e.stopPropagation();
});
var that = this;
$('#com-chilipeppr-widget-autolevel .dropdown-menu .paste-load-go').click(function(e) {
that.loadText();
});
// exaggerate detail menu
$('.com-chilipeppr-widget-autolevel-exaggerate1x').click(1, this.setExaggerate.bind(this));
$('.com-chilipeppr-widget-autolevel-exaggerate10x').click(10, this.setExaggerate.bind(this));
$('.com-chilipeppr-widget-autolevel-exaggerate50x').click(50, this.setExaggerate.bind(this));
$('.com-chilipeppr-widget-autolevel-exaggerate100x').click(100, this.setExaggerate.bind(this));
//$('#autolevel-run .dropdown-toggle').dropdown()
// raycast
$('.com-chilipeppr-widget-autolevel-raycast').click(this.rayCast.bind(this));
// envelope
$('.com-chilipeppr-widget-autolevel-envelope').click(this.envelope.bind(this));
$('.com-chilipeppr-widget-autolevel-gcodeview').click(this.envelopeView.bind(this));
console.log(this.name + " done loading.");
},
showData: function() {
$('#com-chilipeppr-widget-modal-autolevel-view .modal-body textarea').val(JSON.stringify(this.probes, null, " "));
$('#com-chilipeppr-widget-modal-autolevel-view .modal-title').text("View Probe Data");
$('#com-chilipeppr-widget-modal-autolevel-view').modal('show');
},
loadText: function() {
console.log("loading probe data from paste");
var data = $('#com-chilipeppr-widget-autolevel .dropdown-menu .paste-load').val();
var name = "Paste: ";
if (data.length > 20) name += data.substring(0, 20);
else name += data;
name = name.replace(/[\r\n]/g, " ");
var info = {
name: name,
lastModified: new Date()
};
console.log("info:", info);
// send event off as if the file was drag/dropped
this.createRecentFileEntry(data, info);
// load the data
var pd = data;
//console.log("new probe data to load", pd);
this.probes = $.parseJSON(pd);
//console.log("new probe data:", this.probes);
//this.removeRegionFrom3d();
//this.refreshProbeMatrix();
if (!this.isMatrixShowing)
this.toggleShowMatrix();
else
this.refreshProbeMatrix();
},
deleteRecentFiles: function() {
console.log("deleting files");
// loop thru file storage and delete entries that match this widget
for (var i = 0; i < localStorage.length; i++) {
console.log("localStorage.item.key:", localStorage.key(i));
var key = localStorage.key(i);
if (key.match(/com-chilipeppr-widget-autolevel/))
localStorage.removeItem(key);
}
//localStorage.clear();
this.buildRecentFileMenu();
},
createRecentFileEntry: function(fileStr, info) {
console.log("createRecentFileEntry. fileStr.length:", fileStr.length, "info:", info);
// get the next avail slot
var lastSlot = -1;
for (var ctr = 0; ctr < 100; ctr++) {
if ('com-chilipeppr-widget-autolevel-recent' + ctr in localStorage) {
console.log("found recent file entry. ctr:", ctr);
lastSlot = ctr;
}
}
console.log("lastSlot we found:", lastSlot);
var nextSlot = lastSlot + 1;
var recent = localStorage.getItem("com-chilipeppr-widget-autolevel-recent" + nextSlot);
if (recent === null) {
console.log("empty slot. filling.");
localStorage.setItem("com-chilipeppr-widget-autolevel-recent" + nextSlot, fileStr);
localStorage.setItem("com-chilipeppr-widget-autolevel-recent" + nextSlot + "-name", info.name);
localStorage.setItem("com-chilipeppr-widget-autolevel-recent" + nextSlot + "-lastMod", info.lastModified);
this.buildRecentFileMenu();
}
},
buildRecentFileMenu: function() {
// cleanup prev recent files
$('#com-chilipeppr-widget-autolevel .dropdown-menu2 > li.recent-file-item').remove();
var li = $('#com-chilipeppr-widget-autolevel .dropdown-menu2 > li.recent-files');
console.log("listItems:", li);
var ctr = 0;
var recentName = localStorage.getItem("com-chilipeppr-widget-autolevel-recent" + ctr + "-name");
while (recentName !== null) {
console.log("recentFile ctr:", ctr, "recentName:", recentName);
var recentLastModified = localStorage.getItem("com-chilipeppr-widget-autolevel-recent" + ctr + "-lastMod");
var rlm = new Date(recentLastModified);
var recentSize = localStorage.getItem("com-chilipeppr-widget-autolevel-recent" + ctr).length;
var rsize = parseInt(recentSize / 1024, 10);
if (rsize === 0) rsize = 1;
var newLi = $(
'<li class="recent-file-item"><a href="javascript:">' + recentName +
' <span class="lastModifyDate">' + rlm.toLocaleString() + '</span>' +
' ' + rsize + 'KB' +
'</a></li>');
//' <button type="button" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-trash"></span></button></a></li>');
newLi.insertAfter(li);
var that = this;
newLi.click("com-chilipeppr-widget-autolevel-recent" + ctr, function(data) {
console.log("got recent file click. data:", data);
var key = data.data;
that.loadFileFromLocalStorageKey(key);
});
ctr++;
recentName = localStorage.getItem("com-chilipeppr-widget-autolevel-recent" + ctr + "-name");
}
},
loadFileFromLocalStorageKey: function(key) {
// load file into probes
var info = {
name: localStorage.getItem(key + '-name'),
lastModified: localStorage.getItem(key + '-lastMod')
};
console.log("loading probe data. localStorage.key:", key, "info:", info);
// load the data
var pd = localStorage.getItem(key);
//console.log("new probe data to load", pd);
this.probes = $.parseJSON(pd);
//console.log("new probe data:", that.probes);
this.status("Loaded probe data \"" + info.name + "\"");
// if we call this, we'll get the user3dObject
//this.getBbox();
//this.removeRegionFrom3d();
//this.refreshProbeMatrix();
if (!this.isMatrixShowing)
this.toggleShowMatrix();
else
this.refreshProbeMatrix();
},
loadTestData: function(data) {
this.probes = data;
console.log("loaded test data");
},
matrix: null, // stores our matrix 3d obj
previousLayerOpacities: [], // store previous opacities that we're overriding
toggleShowMatrix: function() {
if ($('.com-chilipeppr-widget-autolevel-togglematrix').hasClass('active')) {
// that means we're showing the matrix, so hide it
this.hideProbeMatrix();
$('.com-chilipeppr-widget-autolevel-togglematrix').removeClass('active');
}
else {
// show it
if (this.probes.length > 0) {
this.showProbeMatrix();
$('.com-chilipeppr-widget-autolevel-togglematrix').addClass('active');
}
else {
this.status("No data to show matrix. Run the probe first.");
}
}
},
isMatrixShowing: false, //
showProbeMatrix: function() {
if (!this.isMatrixShowing) {
// if we call this, we'll get the user3dObject
this.getBbox();
//this.user3dObject.visible = false;
if (this.user3dObject) {
this.removeRegionFrom3d();
this.fadeOutUserObject();
// now draw our matrix
this.drawMatrix();
}
console.log("user3dObject:", this.user3dObject);
this.isMatrixShowing = true;
}
},
hideProbeMatrix: function() {
if (this.isMatrixShowing) {
this.removeMatrix();
this.unfadeOutUserObject();
this.isMatrixShowing = false;
}
},
refreshProbeMatrix: function() {
// refreshes matrix without unfading and fading user object
// which is slow
this.fadeOutUserObject();
if (this.isMatrixShowing) {
this.removeMatrix();
}
this.drawMatrix();
this.isMatrixShowing = true;
},
isFadeOutUserObject: false,
fadeOutUserObject: function() {
if (!this.isFadeOutUserObject && this.user3dObject !== null) {
// fade out the user object so our matrix is visible
chilipeppr.publish('/com-chilipeppr-widget-3dviewer/wakeanimate', "");
var o = this.user3dObject;
var that = this;
that.previousLayerOpacities = [];
o.children.forEach(function iterLayers(lyr) {
//added by jpadie to cater for unhandled bugs when material and/or opacity
//is not defined for the material property
if (lyr.material == undefined || lyr.material.opacity == undefined) {}
else {
that.previousLayerOpacities.push(lyr.material.opacity);
lyr.material.opacity = 0.035;
}
});
this.isFadeOutUserObject = true;
}
},
unfadeOutUserObject: function() {
if (this.isFadeOutUserObject) {
// reset previous opacities
if (this.user3dObject && this.previousLayerOpacities.length > 0) {
var o = this.user3dObject;
var ctr = 0;
var that = this;
o.children.forEach(function(lyr) {
lyr.material.opacity = that.previousLayerOpacities[ctr];
ctr++;
});
}
this.isFadeOutUserObject = false;
}
},
sendGcodeToWorkspace: function() {
console.log("sendGcodeToWorkspace");
var gcodeline = this.envelope({
addZToAllGCmds: true,
breakLongGCmdsIntoMoreZ: false
});
var gcodetxt = gcodeline.join("\n");
var info = {
name: "Auto-Levelled " + gcodetxt.substring(0, 20),
lastModified: new Date()
};
console.log("info:", info);
// send event off as if the file was drag/dropped
chilipeppr.publish("/com-chilipeppr-elem-dragdrop/ondropped", gcodetxt, info);
},
envelopeView: function(evt, opts) {
// options are
/* {
onlyLinesWithZ: true, // (default)
addZToAllGCmds: true,
breakLongGCmdsIntoMoreZ: true
*/
var options = {
addZToAllGCmds: true,
breakLongGCmdsIntoMoreZ: false
};
if (opts !== null && typeof opts != "undefined") {
options = opts;
}
// show the gcode
var gcodeline = this.envelope(options);
//var gcode = this.user3dObject;
/*
if (gcode == null) {
console.log("had to run envelope()");
this.envelope();
gcode = this.user3dObject;
}
*/
//console.log("gcode:", gcode);
/*
var gcodeline = [];
gcode.userData.lines.forEach(function(item) {
if ('origtext' in item.args)
gcodeline.push(item.args.origtext);
else if ('text' in item.args)
gcodeline.push(item.args.text);
else
gcodeline.push("huh? no gcode text???");
});
*/
var gcodetext = gcodeline.join("\n");
$('#com-chilipeppr-widget-modal-autolevel-view .modal-body textarea').val(gcodetext);
$('#com-chilipeppr-widget-modal-autolevel-view .modal-title').text("Gcode with Auto-Level Applied");
$('#com-chilipeppr-widget-modal-autolevel-view').modal('show');
},
autolevelledGcode: null,
envelope: function(options) {
// options are
/* {
onlyLinesWithZ: true, // (default)
addZToAllGCmds: true,
breakLongGCmdsIntoMoreZ: true
}
*/
if (typeof options == "undefined") {
options = {};
}
if ($('.com-chilipeppr-widget-autolevel-toggleInterpolate').hasClass('btn-success')) {
options.breakLongGCmdsIntoMoreZ = true;
}
console.log("envelope called. options:", options);
// the 3dviewer contains the orig gcode inside the
// userData of the 3dobject.
// we are going to loop thru and find all z's in the gcode
// and raycast to adjust the z.
// then we can update all widgets with the new gcode to
// apply the envelope
var newgcode = [];
var gcode = this.user3dObject;
if (gcode === null) {
console.log("getting 3d obj from 3d viewer");
this.get3dObjectFrom3dViewer();
gcode = this.user3dObject;
}
console.log("gcode:", gcode);
if (gcode.length == 0) {
this.autolevelledGcode = [];
return this.autolevelledGcode;
}
// unfade so we can see results
//this.unfadeOutUserObject();
// we take the mesh and raycast all pts to get their adjusted z
// probeMesh is set by the drawMatrix() method
var meshGrp = this.getUnitMesh();
if (meshGrp === null) {
console.log("uh oh. mesh is null.");
}
else {
console.log("meshGrp good:", meshGrp);
}
// to create ray, we need start point and direction vector
// already have startpoint vector from gcode, so create direction
var direction = new THREE.Vector3(0, 0, -1);
direction.normalize();
//this.scene.updateMatrixWorld();
meshGrp.updateMatrix();
var ctr = 0;
var ctrtext = 0;
var ctrtextwithz = 0;
var ctrtextwithzmatch = 0;
var ctrIntersected = 0;
var ctrGCmd = 0;
var ctrGCmdRayIntersected = 0;
var ctrGCmdNotValid = 0;
if (options.breakLongGCmdsIntoMoreZ) {
var steps = parseFloat($('.grid-steps').val());
if (isNaN(steps) || steps == 0) steps = 5;
var _gcode = this.interPolator.interpolate(gcode, steps, true); //interpolate gcode into smaller steps.
//need to raycast interpolated code here.
var gcodetxt = _gcode.join("\n");
var info = {
name: "Interpolated gCode for auto-levelling" + gcodetxt.substring(0, 20),
lastModified: new Date()
};
console.log("info:", info);
// send event off as if the file was drag/dropped
chilipeppr.publish("/com-chilipeppr-elem-dragdrop/ondropped", gcodetxt, info);
gcodetxt = _gcode = null;
}
/* it would be more memory efficient to do this on the fly, line by line. */
var gcode = this.user3dObject;
if (gcode === null) {
console.log("getting 3d obj from 3d viewer");
this.get3dObjectFrom3dViewer();
gcode = this.user3dObject;
}
gcode.userData.lines.forEach(function(item) {
// see if gcode line has z val
var newgcodeline = "";
if ('origtext' in item.args) {
// this is gcode
ctrtext++;
// set new line to current line just as a starting point
// it will get overriden if we modify
newgcodeline = item.args.origtext;
// see if has z value
var txt = item.args.text;
//console.log("working on item:", item);
if (txt.match(/z/i)) {
// yes, there's a z value
ctrtextwithz++;
// now do raycast
var startPoint = new THREE.Vector3(item.p2.x, item.p2.y, item.p2.z + 100);
var ray = new THREE.Raycaster(startPoint, direction);
var rayIntersects = ray.intersectObject(meshGrp, true);
if (rayIntersects[0]) {
//item.p2.origz = item.p2.z;
item.p2.autolevelz = rayIntersects[0].point.z + item.p2.z;
item.p2.autolevelz = item.p2.autolevelz.toFixed(4);
// adjust gcode
var origtext = item.args.origtext;
if (origtext.match(/z {0,}(-{0,1}\d+\.{0,1}\d*)/i)) {
var z = RegExp.$1;
ctrtextwithzmatch++;
var newtxt = origtext.replace(/z {0,}(-{0,1}\d+\.{0,1}\d*)/i, "Z" + item.p2.autolevelz);
//item.args.oldtext = item.args.origtext;
//item.args.origtext = newtxt + " (al z mod " + item.p2.origz + ")";
newgcodeline = newtxt + " (al z mod " + item.p2.z + ")";
//console.log("got z:", z, item.args);
}
ctrIntersected++;
//console.log(ctr, txt, item.p2);
}
}
else if (options.addZToAllGCmds && item.args.cmd.match(/^G/i)) {
// this is a G command without a z, so let's test it's a valid G cmd
// for adding a Z value
if (item.args.cmd.match(/G0|G1/i)) {
//console.log("got a G0 or G1 cmd. so good to go to add Z");
ctrGCmd++;
// now do raycast
var startPoint = new THREE.Vector3(item.p2.x, item.p2.y, item.p2.z + 100);
var ray = new THREE.Raycaster(startPoint, direction);
var rayIntersects = ray.intersectObject(meshGrp, true);
if (rayIntersects[0]) {
ctrGCmdRayIntersected++;
//item.p2.origz = item.p2.z;
item.p2.autolevelz = rayIntersects[0].point.z + item.p2.z;
item.p2.autolevelz = item.p2.autolevelz.toFixed(4);
//item.args.oldtext = item.args.origtext;
newgcodeline = item.args.origtext + "Z" + item.p2.autolevelz + " (al new z)";
//console.log("adding z. new item:", item);
}
}
else {
//console.log("this is g cmd without G0 or G1");
ctrGCmdNotValid++;
}
}
}
else if ('text' in item.args) {
newgcodeline = item.args.text;
}
else {
newgcodeline = "huh? no gcode text???";
}
// push onto final array of gcode
newgcode.push(newgcodeline);
ctr++;
});
console.log("lines of gcode analyzed:", ctr, "with gcode text:", ctrtext, "txt with z val:", ctrtextwithz, "ctrtextwithzmatch:", ctrtextwithzmatch, "intersected (should be same as with z val):", ctrIntersected);
console.log("did user want z added to all G cmds", options.addZToAllGCmds, "ctrGCmd:", ctrGCmd, "ctrGCmdNotValid:", ctrGCmdNotValid, "ctrGCmdRayIntersected:", ctrGCmdRayIntersected);
console.log("ctr:", ctr, "len of newgcode arr (should be same as ctr):", newgcode.length);
this.autolevelledGcode = newgcode;
return this.autolevelledGcode;
},
getUnitMesh: function() {
// create new mesh that is not amplified so we can calc off of it
var p = this.probes;
var maxx = null;
var maxy = null;
// we stored the orig indx of x/y to make converting to 2d array easier
// this makes our matrix drawing easier
var pd2 = [];
p.forEach(function loopThruProbes(item) {
if (pd2[item.xindx] === undefined) pd2[item.xindx] = [];
pd2[item.xindx][item.yindx] = item;
});
// ok, we've got our 2d array. make triangles
// try a mesh to show the difference in points and to represent
// the adjustments we'll do to the z
var material = new THREE.MeshBasicMaterial();
//var material = new THREE.MeshNormalMaterial({
// side: THREE.DoubleSide
//});
//var material = new THREE.MeshLambertMaterial({
// color: '#999999',
//side: THREE.DoubleSide
//});
var meshGrp = new THREE.Object3D();
var holes = [];
var xctrlen = pd2.length - 1;
var yctrlen = pd2[0].length - 1;
//xctrlen = 10;
//yctrlen = 1;
for (var ctrx = 0; ctrx < xctrlen; ctrx++) {
for (var ctry = 0; ctry < yctrlen; ctry++) {
// what are the x,y,z vals of start point
/* pt2 pt3
pt1 pt4
*/
var x1 = pd2[ctrx][ctry].x;
var y1 = pd2[ctrx][ctry].y;
var z1 = pd2[ctrx][ctry].z;
z1 = (z1 === null) ? 0 : z1;
// pt2 is 1 up in y direction
var x2 = pd2[ctrx][ctry + 1].x;
var y2 = pd2[ctrx][ctry + 1].y;
var z2 = pd2[ctrx][ctry + 1].z;
z2 = (z2 === null) ? 0 : z2;
// pt3 is 1 right in x direction, 1 up in y dir
var x3 = pd2[ctrx + 1][ctry + 1].x;
var y3 = pd2[ctrx + 1][ctry + 1].y;
var z3 = pd2[ctrx + 1][ctry + 1].z;
z3 = (z3 === null) ? 0 : z3;
// pt4 is 1 right in x direction
var x4 = pd2[ctrx + 1][ctry].x;
var y4 = pd2[ctrx + 1][ctry].y;
var z4 = pd2[ctrx + 1][ctry].z;
z4 = (z4 === null) ? 0 : z4;
// add to mesh
//geom.vertices.push(new THREE.Vector3(cx,cy,cz));
var vertices = [];
var triangles, mesh;
var geometry = new THREE.Geometry();
var v = new THREE.Vector3(x1, y1, z1);
//console.log("adding pt1:", v);
if (z1 !== null) vertices.push(v);
var v = new THREE.Vector3(x2, y2, z2);
//console.log("adding pt2:", v);
if (z2 !== null) vertices.push(v);
var v = new THREE.Vector3(x3, y3, z3);
//console.log("adding pt3:", v);
if (z3 !== null) vertices.push(v);
var v = new THREE.Vector3(x4, y4, z4);
//console.log("adding pt3:", v);
if (z4 !== null) vertices.push(v);
geometry.vertices = vertices;
//console.log("about to triangulate shape. vertices:", vertices, "holes:", holes);
triangles = THREE.ShapeUtils.triangulateShape(vertices, holes);
for (var i = 0; i < triangles.length; i++) {
geometry.faces.push(new THREE.Face3(triangles[i][0], triangles[i][1], triangles[i][2]));
}
//geometry.computeCentroids();
geometry.computeFaceNormals();
mesh = new THREE.Mesh(geometry, material);
meshGrp.add(mesh);
}
}
return meshGrp;
},
rayCast: function() {
// RayCast
// To do this we need to take all points in the Gcode
// so we'll have to ask the 3D viewer for them
// then we cast those points onto the mesh from the probe
// data. This will give us the intersection points.
// Then we can adjust the z positions of the gcode
// to their new positions that would match the probe warpage
var gcode = this.user3dObject;
if (gcode === null) {
console.log("getting 3d obj from 3d viewer");
this.get3dObjectFrom3dViewer();
gcode = this.user3dObject;
}
console.log("gcode:", gcode);
var ctr = 0;
var ctrIntersected = 0;
console.log("[0]:", gcode.children[0].geometry);
// unfade so we can see results
this.unfadeOutUserObject();
// we take the mesh and raycast all pts to get their adjusted z
// probeMesh is set by the drawMatrix() method
var meshGrp = this.probeMesh;
if (meshGrp === null) {
console.log("uh oh. mesh is null.");
}
else {
console.log("meshGrp good:", meshGrp);
}
// to create ray, we need start point and direction vector
// already have startpoint vector from gcode, so create direction
var direction = new THREE.Vector3(0, 0, -1);
direction.normalize();
//this.scene.updateMatrixWorld();
meshGrp.updateMatrix();
// loop thru each point in gcode and adjust z height
// essentially we're applying the probe data envelope to gcode
gcode.children[0].geometry.vertices.forEach(function(item) {
//if (item.x < 50 && item.y < 5) {
//console.log("found point inside test area. item:", item);
// move z way up so it's above mesh
//item.z = item.z + 100;
var startPoint = new THREE.Vector3(item.x, item.y, item.z + 100);
var ray = new THREE.Raycaster(startPoint, direction);
var rayIntersects = ray.intersectObject(meshGrp, true);
//if (ctr < 10) {
if (rayIntersects[0]) {
//console.log("we do have an intersection:", rayIntersects);
item.z = rayIntersects[0].point.z;
ctrIntersected++;
}
else {
//console.log("no intersecting of ray to mesh");
}
//}
item.z = item.z + 10;
ctr++;
//}
});
gcode.children[0].geometry.verticesNeedUpdate = true;
console.log("adjusted z on #pts", ctr, "ctrIntersected:", ctrIntersected);
},
exaggerateMult: 50, // exaggerate the detail by multiplying z value
setExaggerate: function(evt) {
console.log("setting exaggerate level:", evt.data);
this.exaggerateMult = evt.data;
if (this.isMatrixShowing)
this.refreshProbeMatrix();
},
probeMesh: null, // stores the mesh of probe data for later raycasting
drawMatrix: function() {
var color = '#660000';
// Create dashed line material
var material = new THREE.LineDashedMaterial({
vertexColors: false,
color: color,
dashSize: 1,
gapSize: 1,
linewidth: 2,
transparent: true,
opacity: 0.8
});
var p = this.probes;
var maxx = null;
var maxy = null;
//var lastz = null;
// we stored the orig indx of x/y to make converting to 2d array easier
// this makes our matrix drawing easier
var pd2 = [];
p.forEach(function loopThruProbes(item) {
if (maxx === null) maxx = item.x;
else if (item.x > maxx) maxx = item.x;
if (maxy === null) maxy = item.x;
else if (item.y > maxy) maxy = item.y;
// calc zabs
//if (lastz == null) item.zabs = 0; // makes 1st probe be 0 pos on Z
//else if (item.z == null) item.zabs = 0; // if no data yet for z, just use 0
//else item.zabs = lastz + item.z; // adds last z to this z to convert relative to abs
//else item.zabs = lastz + item.zmaxlowest; // adds last z to this z to convert relative to abs
// since we're probing with g38.2 now, we have an abs val already, no relative. thank god!
//item.zabs = item.zprobe;
// inject into 2d array
//console.log("inject 2d array. item.xindx:", item.xindx);
if (pd2[item.xindx] === undefined) pd2[item.xindx] = [];
pd2[item.xindx][item.yindx] = item;
//lastz = item.zabs;
});
this.maxx = maxx;
this.maxy = maxy;
console.log("maxx:", maxx, "maxy:", maxy);
console.log("pd2:", pd2);
/*
// now that our zabs is calculated
// let's take our probe data and put in 2d array so we can manipulate better
// we need to generate triangles so need pts in a square to make 2 triangles
// out of. since we know we did a grid we should do 2 triangles per square
var pd = [];
p.forEach(function(item) {
if (pd[item.x] === undefined) pd[item.x] = [];
pd[item.x][item.y] = item;
});
console.log("don generating 2d arra. pd:", pd);
console.log("x length:", pd.length);
console.log("one of the y lengths:", pd[p[0].x].length);
// ok, now collapse pd[][] to new array with new indexes
var pd2 = [];
var ix = 0;
for(var ctrx = 0; ctrx < pd.length; ctrx++) {
if (pd[ctrx] !== undefined) {
if (pd2[ix] === undefined) pd2[ix] = [];
var iy = 0;
for(var ctry = 0; ctry < pd[p[0].x].length; ctry++) {
if (pd[ctrx][ctry] !== undefined) {
pd2[ix][iy] = pd[ctrx][ctry];
iy++;
}
}
ix++;
}
}
console.log("new pd2:", pd2);
*/
// ok, we've got our 2d array. make triangles
// try a mesh to show the difference in points and to represent
// the adjustments we'll do to the z
//var material = new THREE.MeshBasicMaterial();
//var material = new THREE.MeshNormalMaterial({
// side: THREE.DoubleSide
//});
var material = new THREE.MeshLambertMaterial({
color: '#999999',
side: THREE.DoubleSide
});
var meshGrp = new THREE.Object3D();
var holes = [];
var xctrlen = pd2.length - 1;
var yctrlen = pd2[0].length - 1;
//xctrlen = 10;
//yctrlen = 1;
for (var ctrx = 0; ctrx < xctrlen; ctrx++) {
for (var ctry = 0; ctry < yctrlen; ctry++) {
// what are the x,y,z vals of start point
/* pt2 pt3
pt1 pt4
*/
var x1 = pd2[ctrx][ctry].x;
var y1 = pd2[ctrx][ctry].y;
var z1 = pd2[ctrx][ctry].z;
z1 = (z1 === null) ? 0 : z1;
// pt2 is 1 up in y direction
var x2 = pd2[ctrx][ctry + 1].x;
var y2 = pd2[ctrx][ctry + 1].y;
var z2 = pd2[ctrx][ctry + 1].z;
z2 = (z2 === null) ? 0 : z2;
// pt3 is 1 right in x direction, 1 up in y dir
var x3 = pd2[ctrx + 1][ctry + 1].x;
var y3 = pd2[ctrx + 1][ctry + 1].y;
var z3 = pd2[ctrx + 1][ctry + 1].z;
z3 = (z3 === null) ? 0 : z3;
// pt4 is 1 right in x direction
var x4 = pd2[ctrx + 1][ctry].x;
var y4 = pd2[ctrx + 1][ctry].y;
var z4 = pd2[ctrx + 1][ctry].z;
z4 = (z4 === null) ? 0 : z4;
// add to mesh
//geom.vertices.push(new THREE.Vector3(cx,cy,cz));
var vertices = [];
var triangles, mesh;
var geometry = new THREE.Geometry();
var v = new THREE.Vector3(x1, y1, z1 * this.exaggerateMult);
//console.log("adding pt1:", v);
if (z1 !== null) vertices.push(v);
var v = new THREE.Vector3(x2, y2, z2 * this.exaggerateMult);
//console.log("adding pt2:", v);
if (z2 !== null) vertices.push(v);
var v = new THREE.Vector3(x3, y3, z3 * this.exaggerateMult);
//console.log("adding pt3:", v);
if (z3 !== null) vertices.push(v);
var v = new THREE.Vector3(x4, y4, z4 * this.exaggerateMult);
//console.log("adding pt3:", v);
if (z4 !== null) vertices.push(v);
geometry.vertices = vertices;
//console.log("about to triangulate shape. vertices:", vertices, "holes:", holes);
triangles = THREE.ShapeUtils.triangulateShape(vertices, holes);
for (var i = 0; i < triangles.length; i++) {
geometry.faces.push(new THREE.Face3(triangles[i][0], triangles[i][1], triangles[i][2]));
}
//geometry.computeCentroids();
geometry.computeFaceNormals();
mesh = new THREE.Mesh(geometry, material);
meshGrp.add(mesh);
}