-
Notifications
You must be signed in to change notification settings - Fork 676
/
Copy pathopenjscad.js
1465 lines (1368 loc) · 48.4 KB
/
openjscad.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: OpenJSCAD Development timeStamp
Modified to integrate into Laserweb UI by AUTHOR: Peter van der Walt
*/
OpenJsCad = function() {};
// Specific to your machine
var laserxmax = 600
var laserymax = 400
var lineincrement = 50
var axesgrp2 = '';
var axes2 = '';
var gridhelper = '';
var colorMeshes = '';
var scene2;
OpenJsCad.log = function(txt) {
var timeInMs = Date.now();
var prevtime = OpenJsCad.log.prevLogTime;
if (!prevtime) prevtime = timeInMs;
var deltatime = timeInMs - prevtime;
OpenJsCad.log.prevLogTime = timeInMs;
var timefmt = (deltatime * 0.001).toFixed(3);
txt = "[" + timefmt + "] " + txt;
if ((typeof(console) == "object") && (typeof(console.log) == "function")) {
//console.log(txt); // Turn on for Debug
} else if ((typeof(self) == "object") && (typeof(self.postMessage) == "function")) {
self.postMessage({
cmd: 'log',
txt: txt
});
} else throw new Error("Cannot log");
};
// A viewer is a WebGL canvas that lets the user view a mesh. The user can
// tumble it around by dragging the mouse.
OpenJsCad.Viewer = function(containerElm, size, options) {
// config stuff
// fg and bg colors
var defaultBgColor = [1, 1, 1];
var defaultMeshColor = [0.2, 0.2, 0.2];
var drawAxes = false;
var rotateZX = false;
var rotateXY = false;
this.renderer_ = renderer;
var axLength = 1000;
this.perspective = 45; // in degrees
//this.viewpointZ = initialdepth;
this.drawOptions = {
// Draw black triangle lines ("wireframe")
lines: options.drawLines,
// Draw surfaces
faces: options.drawFaces
};
// end config stuff
this.size = size;
this.defaultColor_ = options.color || defaultMeshColor;
// default is opaque if not defined otherwise
if (this.defaultColor_.length == 3) {
this.defaultColor_.push(1);
}
this.bgColor_ = new THREE.Color();
this.bgColor_.setRGB.apply(this.bgColor_, options.bgColor || defaultBgColor);
// the elm to contain the canvas
this.containerElm_ = containerElm;
this.createScene(drawAxes, axLength);
// this.createGrid();
this.createCamera();
this.parseSizeParams();
// createRenderer will also call render
//this.createRenderer(options.noWebGL);
//this.animate();
};
OpenJsCad.Viewer.prototype = {
// adds axes too
createScene: function(drawAxes, axLen) {
scene2 = new THREE.Scene();
this.scene_ = scene2;
if (drawAxes) {
this.drawAxes(axLen);
}
},
// createGrid: function() {
// if (gridhelper2) {
// scene2.remove(gridhelper);
// }
// var gridhelper2 = new THREE.GridHelperRect((laserxmax /2), 10, (laserymax / 2), 10);
// gridhelper2.setColors(0x0000ff, 0x707070);
// gridhelper2.position.y = 0;
// gridhelper2.position.x = 0;
// gridhelper2.position.z = 0;
// gridhelper2.rotation.x = 90 * Math.PI / 180;
// gridhelper2.material.opacity = 0.15;
// gridhelper2.material.transparent = true;
// gridhelper2.receiveShadow = false;
// //console.log("helper grid:", helper);
// this.grid2 = gridhelper2;
// //this.sceneAdd(this.grid);
// this.scene_.add(gridhelper2);
//
// if (axes2) {
// scene2.remove(axes2);
// }
//
// if (axesgrp2) {
// scene2.remove(axesgrp2);
// }
// var axesgrp2 = new THREE.Object3D();
// var axes2 = new THREE.AxisHelper(120);
//
// axes2.material.transparent = true;
// axes2.material.opacity = 0.8;
// axes2.material.depthWrite = false;
// axes2.position.set(0,0,-0.0001);
// axes2.translateX((laserxmax / 2) * -1);
// axes2.translateY((laserymax / 2) * -1);
//
// this.scene_.add(axes);
//
// var x = [];
// var y = [];
// for (var i = 0; i < laserxmax ; i+=lineincrement) {
//
// x[i] = makeSprite(this.scene_, "webgl", {
// x: i,
// y: -10,
// z: 0,
// text: i,
// color: "#ff0000"
// });
// axesgrp2.add(x[i]);
// }
//
// for (var i = 0; i < laserymax ; i+=lineincrement) {
//
// y[i] = makeSprite(this.scene_, "webgl", {
// x: -10,
// y: i,
// z: 0,
// text: i,
// color: "#006600"
// });
// axesgrp2.add(y[i]);
// }
// // add axes labels
// var xlbl = makeSprite(this.scene_, "webgl", {
// x: 125,
// y: 0,
// z: 0,
// text: "X",
// color: "#ff0000"
// });
// var ylbl = makeSprite(this.scene_, "webgl", {
// x: 0,
// y: 125,
// z: 0,
// text: "Y",
// color: "#006600"
// });
// var zlbl = makeSprite(this.scene_, "webgl", {
// x: 0,
// y: 0,
// z: 125,
// text: "Z",
// color: "#0000ff"
// });
//
//
// axesgrp2.add(xlbl);
// axesgrp2.add(ylbl);
// //axesgrp.add(zlbl);
//
// axesgrp2.translateX((laserxmax / 2) * -1);
// axesgrp2.translateY((laserymax / 2) * -1);
// this.scene_.add(axesgrp2);
// },
createCamera: function() {
//var light = new THREE.PointLight();
//light.position.set(0, 0, 0);
// aspect ration changes later - just a placeholder
var directionalLight2 = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight2.position.set(0, 1, 0);
this.scene_.add(directionalLight2);
camera2 = new THREE.PerspectiveCamera(this.perspective, 1 / 1, 0.01, 1000000);
this.camera_ = camera2;
//camera.add(light);
camera2.position.set(0, 0, 0);
camera2.up.set(0, 0, 1);
camera2.lookAt(0, 0, 0);
this.scene_.add(camera2);
//camera2.translateX(300);
},
createControls: function(canvas) {
// controls. just change this line (and script include) to other threejs controls if desired
var controls2 = new THREE.OrbitControls(this.camera_, canvas);
this.controls_ = controls2;
controls2.noKeys = true;
controls2.zoomSpeed = 0.5;
// controls.autoRotate = true;
controls2.autoRotateSpeed = 1;
controls2.addEventListener('change', this.render.bind(this));
},
webGLAvailable: function() {
try {
var canvas = document.createElement("canvas");
return !!
window.WebGLRenderingContext &&
(canvas.getContext("webgl") ||
canvas.getContext("experimental-webgl"));
} catch (e) {
return false;
}
},
createRenderer: function(bool_noWebGL) {
var Renderer = this.webGLAvailable() && !bool_noWebGL ?
THREE.WebGLRenderer : THREE.CanvasRenderer;
// we're creating new canvas on switching renderer, as same
// canvas doesn't tolerate moving from webgl to canvasrenderer
var renderer = new Renderer({
precision: 'highp'
});
this.renderer_ = renderer;
if (this.canvas) {
this.canvas.remove();
}
this.canvas = renderer.domElement;
this.containerElm_.appendChild(this.canvas);
// scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 )
renderer.setClearColor(this.bgColor_);
// renderer.setClearColor(scene.fog.color);
// and add controls
this.createControls(renderer.domElement);
// if coming in from contextrestore, enable rendering here
this.pauseRender_ = false;
this.handleResize();
// handling context lost
var this_ = this;
this.canvas.addEventListener("webglcontextlost", function(e) {
e.preventDefault();
this_.cancelAnimate();
}, false);
this.canvas.addEventListener("webglcontextrestored", function(e) {
this_.createRenderer(true);
this_.animate();
}, false);
},
render: function() {
this.renderer_ = renderer;
if (!this.pauseRender_) {
this.renderer_.render(this.scene_, camera2);
}
},
animate: function() {
// reduce fps? replace func with
// setTimeout( function() {
// requestAnimationFrame(this.animate.bind(this));
// }, 1000 / 40 ); // last num = fps
this.requestID_ = requestAnimationFrame(this.animate.bind(this));
this.controls_.update();
},
cancelAnimate: function() {
this.pauseRender_ = true;
cancelAnimationFrame(this.requestID_);
},
refreshRenderer: function(bool_noWebGL) {
this.cancelAnimate();
if (!bool_noWebGL) {
// need to refresh scene objects except camera
var objs = this.scene_.children.filter(function(ch) {
return !(ch instanceof THREE.Camera);
});
this.scene_.remove.apply(this.scene_, objs);
var newObjs = objs.map(function(obj) {
obj.geometry = obj.geometry.clone();
obj.material = obj.material.clone();
return obj.clone();
});
this.scene_.add.apply(this.scene_, newObjs);
this.applyDrawOptions();
}
this.createRenderer(bool_noWebGL);
this.animate();
},
// https://www.youtube.com/watch?v=c-O-tOYdAFY#t=858 (pause) for a basic grid
drawAxes: function(axLen) {
axLen = axLen || 1000;
function v(x, y, z) {
return new THREE.Vector3(x, y, z);
}
var origin = v(0, 0, 0);
[
[v(axLen, 0, 0), 0xFF0000],
[v(-axLen, 0, 0), 0xD3D3D3],
[v(0, axLen, 0), 0x00FF00],
[v(0, -axLen, 0), 0xD3D3D3],
[v(0, 0, axLen), 0x0000FF],
[v(0, 0, -axLen), 0xD3D3D3]
]
.forEach(function(axdef) {
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push(origin, axdef[0]);
this.scene_.add(new THREE.Line(lineGeometry,
new THREE.LineBasicMaterial({
color: axdef[1],
lineWidth: 1
})))
}, this);
},
setCsg: function(csg, resetZoom) {
this.clear();
res = THREE.CSG.fromCSG(csg, this.defaultColor_);
colorMeshes = [].concat(res.colorMesh)
.map(function(mesh) {
mesh.userData = {
faces: true
};
return mesh;
});
var wireMesh = res.wireframe;
wireMesh.userData = {
lines: true
};
this.scene_.add.apply(this.scene_, colorMeshes);
this.scene_.add(wireMesh);
resetZoom && this.resetZoom(res.boundLen);
this.applyDrawOptions();
wireMesh.translateX((laserxmax / 2) * -1);
wireMesh.translateY((laserymax / 2) * -1);
this.getUserMeshes('faces').forEach(function(faceMesh) {
faceMesh.visible = !!this.drawOptions.faces;
faceMesh.translateX((laserxmax / 2) * -1);
faceMesh.translateY((laserymax / 2) * -1);
}, this);
},
applyDrawOptions: function() {
this.getUserMeshes('faces').forEach(function(faceMesh) {
faceMesh.visible = !!this.drawOptions.faces;
}, this);
this.getUserMeshes('lines').forEach(function(lineMesh) {
lineMesh.visible = !!this.drawOptions.lines;
}, this);
this.render();
},
clear: function() {
this.scene_.remove.apply(this.scene_, this.getUserMeshes());
},
// gets the meshes created by setCsg
getUserMeshes: function(str) {
return this.scene_.children.filter(function(ch) {
if (str) {
return ch.userData[str];
} else {
return ch.userData.lines || ch.userData.faces;
}
});
},
resetZoom: function(r) {
if (!r) {
// empty object - any default zoom
r = 10;
}
var d = r / Math.tan(this.perspective * Math.PI / 180);
// play here for different start zoom
//this.camera_.position.set(d*2, d*2, d);
this.camera_.position.set(0, 0, d * 5);
this.camera_.zoom = 1;
//this.camera_.lookAt(this.scene_.position);
this.camera_.lookAt(0, 0, 0);
this.camera_.updateProjectionMatrix();
},
parseSizeParams: function() {
// essentially, allow all relative + px. Not cm and such.
var winResizeUnits = ['%', 'vh', 'vw', 'vmax', 'vmin'];
var width, height;
if (!this.size.width) {
this.size.width = this.size.widthDefault;
}
if (!this.size.height) {
this.size.height = this.size.heightDefault;
}
var wUnit = this.size.width.match(/^(\d+(?:\.\d+)?)(.*)$/)[2];
var hUnit = typeof this.size.height == 'string' ?
this.size.height.match(/^(\d+(?:\.\d+)?)(.*)$/)[2] :
'';
// whether unit scales on win resize
var isDynUnit = winResizeUnits.indexOf(wUnit) != -1 ||
winResizeUnits.indexOf(hUnit) != -1;
// e.g if units are %, need to keep resizing canvas with dom
if (isDynUnit) {
window.addEventListener('resize', this.handleResize.bind(this))
}
},
handleResize: function() {
var hIsRatio = typeof this.size.height != 'string';
// apply css, then check px size. This is in case css is not in px
this.canvas.style.width = this.size.width;
if (!hIsRatio) {
this.canvas.style.height = this.size.height;
}
var widthInPx = this.canvas.clientWidth;
var heightInPx = hIsRatio ?
widthInPx * this.size.height :
this.canvas.clientHeight; // size.height.match(/^(\d+(?:\.\d+)?)(.*)$/)[1];
this.camera_.aspect = widthInPx / heightInPx;
this.camera_.updateProjectionMatrix();
// set canvas attributes (false => don't set css)
this.renderer_.setSize(widthInPx, heightInPx, false);
this.render();
}
};
// make a full url path out of a base path and url component.
// url argument is interpreted as a folder name if it ends with a slash
OpenJsCad.makeAbsoluteUrl = function(url, baseurl) {
if (!url.match(/^[a-z]+\:/i)) {
var re = /^\/|\/$/g;
if (baseurl[baseurl.length - 1] != '/') {
// trailing part is a file, not part of base - remove
baseurl = baseurl.replace(/[^\/]*$/, "");
}
if (url[0] == '/') {
var basecomps = baseurl.split('/');
url = basecomps[0] + '//' + basecomps[2] + '/' + url.replace(re, "");
} else {
url = (baseurl.replace(re, "") + '/' + url.replace(re, ""))
.replace(/[^\/]+\/\.\.\//g, "");
}
}
return url;
};
OpenJsCad.isChrome = function() {
return (navigator.userAgent.search("Chrome") >= 0);
};
// This is called from within the web worker. Execute the main() function of the supplied script
// and post a message to the calling thread when finished
OpenJsCad.runMainInWorker = function(mainParameters) {
try {
if (typeof(main) != 'function') throw new Error('Your jscad file should contain a function main() which returns a CSG solid or a CAG area.');
OpenJsCad.log.prevLogTime = Date.now();
var result = main(mainParameters);
result = OpenJsCad.expandResultObjectArray(result);
OpenJsCad.checkResult(result);
var result_compact = OpenJsCad.resultToCompactBinary(result);
result = null; // not needed anymore
self.postMessage({
cmd: 'rendered',
result: result_compact
});
} catch (e) {
var errtxt = e.toString();
if (e.stack) {
errtxt += '\nStack trace:\n' + e.stack;
}
self.postMessage({
cmd: 'error',
err: errtxt
});
}
};
// expand an array of CSG or CAG objects into an array of objects [{data: <CAG or CSG object>}]
OpenJsCad.expandResultObjectArray = function(result) {
if (result instanceof Array) {
result = result.map(function(resultelement) {
if ((resultelement instanceof CSG) || (resultelement instanceof CAG)) {
resultelement = {
data: resultelement
};
}
return resultelement;
});
}
return result;
};
// check whether the supplied script returns valid object(s)
OpenJsCad.checkResult = function(result) {
var ok = true;
if (typeof(result) != "object") {
ok = false;
} else {
if (result instanceof Array) {
if (result.length < 1) {
ok = false;
} else {
result.forEach(function(resultelement) {
if (!("data" in resultelement)) {
ok = false;
} else {
if ((resultelement.data instanceof CSG) || (resultelement.data instanceof CAG)) {
// ok
} else {
ok = false;
}
}
});
}
} else if ((result instanceof CSG) || (result instanceof CAG)) {} else {
ok = false;
}
}
if (!ok) {
throw new Error("Your main() function does not return valid data. It should return one of the following: a CSG object, a CAG object, an array of CSG/CAG objects, or an array of objects: [{name:, caption:, data:}, ...] where data contains a CSG or CAG object.");
}
};
// convert the result to a compact binary representation, to be copied from the webworker to the main thread.
// it is assumed that checkResult() has been called already so the data is valid.
OpenJsCad.resultToCompactBinary = function(resultin) {
var resultout;
if (resultin instanceof Array) {
resultout = resultin.map(function(resultelement) {
var r = resultelement;
r.data = resultelement.data.toCompactBinary();
return r;
});
} else {
resultout = resultin.toCompactBinary();
}
return resultout;
};
OpenJsCad.resultFromCompactBinary = function(resultin) {
function fromCompactBinary(r) {
var result;
if (r.class == "CSG") {
result = CSG.fromCompactBinary(r);
} else if (r.class == "CAG") {
result = CAG.fromCompactBinary(r);
} else {
throw new Error("Cannot parse result");
}
return result;
}
var resultout;
if (resultin instanceof Array) {
resultout = resultin.map(function(resultelement) {
var r = resultelement;
r.data = fromCompactBinary(resultelement.data);
return r;
});
} else {
resultout = fromCompactBinary(resultin);
}
return resultout;
};
OpenJsCad.parseJsCadScriptSync = function(script, mainParameters, debugging) {
var workerscript = "";
workerscript += script;
if (debugging) {
workerscript += "\n\n\n\n\n\n\n/* -------------------------------------------------------------------------\n";
workerscript += "OpenJsCad debugging\n\nAssuming you are running Chrome:\nF10 steps over an instruction\nF11 steps into an instruction\n";
workerscript += "F8 continues running\nPress the (||) button at the bottom to enable pausing whenever an error occurs\n";
workerscript += "Click on a line number to set or clear a breakpoint\n";
workerscript += "For more information see: http://code.google.com/chrome/devtools/docs/overview.html\n\n";
workerscript += "------------------------------------------------------------------------- */\n";
workerscript += "\n\n// Now press F11 twice to enter your main() function:\n\n";
workerscript += "debugger;\n";
}
workerscript += "return main(" + JSON.stringify(mainParameters) + ");";
var f = new Function(workerscript);
OpenJsCad.log.prevLogTime = Date.now();
var result = f();
result = OpenJsCad.expandResultObjectArray(result);
OpenJsCad.checkResult(result);
return result;
};
// callback: should be function(error, csg)
OpenJsCad.parseJsCadScriptASync = function(script, mainParameters, options, callback) {
var baselibraries = [
"lib/openjscad/src/csg.js",
"lib/openjscad/src/openjscad.js"
];
var baseurl = document.location.href.replace(/\?.*$/, '');
var openjscadurl = baseurl;
console.log('URL ' + openjscadurl);
if (typeof options['openJsCadPath'] != 'undefined') {
// trailing '/' indicates it is a folder. This is necessary because makeAbsoluteUrl is called
// on openjscadurl
openjscadurl = OpenJsCad.makeAbsoluteUrl(options['openJsCadPath'], baseurl) + '/';
console.log('URL ' + openjscadurl);
}
var libraries = [];
if (typeof options['libraries'] != 'undefined') {
libraries = options['libraries'];
}
var workerscript = "";
workerscript += script;
workerscript += "\n\n\n\n//// The following code is added by OpenJsCad:\n";
workerscript += "var _csg_baselibraries=" + JSON.stringify(baselibraries) + ";\n";
workerscript += "var _csg_libraries=" + JSON.stringify(libraries) + ";\n";
workerscript += "var _csg_baseurl=" + JSON.stringify(baseurl) + ";\n";
workerscript += "var _csg_openjscadurl=" + JSON.stringify(openjscadurl) + ";\n";
workerscript += "var _csg_makeAbsoluteURL=" + OpenJsCad.makeAbsoluteUrl.toString() + ";\n";
workerscript += "_csg_baselibraries = _csg_baselibraries.map(function(l){return _csg_makeAbsoluteURL(l,_csg_openjscadurl);});\n";
workerscript += "_csg_libraries = _csg_libraries.map(function(l){return _csg_makeAbsoluteURL(l,_csg_baseurl);});\n";
workerscript += "_csg_baselibraries.map(function(l){importScripts(l)});\n";
workerscript += "_csg_libraries.map(function(l){importScripts(l)});\n";
workerscript += "self.addEventListener('message', function(e) {if(e.data && e.data.cmd == 'render'){";
workerscript += " OpenJsCad.runMainInWorker(" + JSON.stringify(mainParameters) + ");";
workerscript += "}},false);\n";
var blobURL = OpenJsCad.textToBlobUrl(workerscript);
if (!window.Worker) throw new Error("Your browser doesn't support Web Workers. Please try the Chrome browser instead.");
var worker = new Worker(blobURL);
worker.onmessage = function(e) {
if (e.data) {
if (e.data.cmd == 'rendered') {
var resulttype = e.data.result.class;
var result = OpenJsCad.resultFromCompactBinary(e.data.result);
callback(null, result);
} else if (e.data.cmd == "error") {
callback(e.data.err, null);
} else if (e.data.cmd == "log") {
console.log(e.data.txt);
}
}
};
worker.onerror = function(e) {
var errtxt = "Error in line " + e.lineno + ": " + e.message;
callback(errtxt, null);
};
worker.postMessage({
cmd: "render"
}); // Start the worker.
return worker;
};
OpenJsCad.getWindowURL = function() {
if (window.URL) return window.URL;
else if (window.webkitURL) return window.webkitURL;
else throw new Error("Your browser doesn't support window.URL");
};
OpenJsCad.textToBlobUrl = function(txt) {
var windowURL = OpenJsCad.getWindowURL();
var blob = new Blob([txt], {
type: 'application/javascript'
});
var blobURL = windowURL.createObjectURL(blob);
if (!blobURL) throw new Error("createObjectURL() failed");
return blobURL;
};
OpenJsCad.revokeBlobUrl = function(url) {
if (window.URL) window.URL.revokeObjectURL(url);
else if (window.webkitURL) window.webkitURL.revokeObjectURL(url);
else throw new Error("Your browser doesn't support window.URL");
};
OpenJsCad.FileSystemApiErrorHandler = function(fileError, operation) {
var errormap = {
1: 'NOT_FOUND_ERR',
2: 'SECURITY_ERR',
3: 'ABORT_ERR',
4: 'NOT_READABLE_ERR',
5: 'ENCODING_ERR',
6: 'NO_MODIFICATION_ALLOWED_ERR',
7: 'INVALID_STATE_ERR',
8: 'SYNTAX_ERR',
9: 'INVALID_MODIFICATION_ERR',
10: 'QUOTA_EXCEEDED_ERR',
11: 'TYPE_MISMATCH_ERR',
12: 'PATH_EXISTS_ERR',
};
var errname;
if (fileError.code in errormap) {
errname = errormap[fileError.code];
} else {
errname = "Error #" + fileError.code;
}
var errtxt = "FileSystem API error: " + operation + " returned error " + errname;
throw new Error(errtxt);
};
OpenJsCad.AlertUserOfUncaughtExceptions = function() {
window.onerror = function(message, url, line) {
message = message.replace(/^Uncaught /i, "");
//alert(message+"\n\n("+url+" line "+line+")");
console.log(message + "\n\n(" + url + " line " + line + ")");
};
};
// parse the jscad script to get the parameter definitions
OpenJsCad.getParamDefinitions = function(script) {
var scriptisvalid = true;
try {
// first try to execute the script itself
// this will catch any syntax errors
var f = new Function(script);
f();
} catch (e) {
scriptisvalid = false;
}
var params = [];
if (scriptisvalid) {
var script1 = "if(typeof(getParameterDefinitions) == 'function') {return getParameterDefinitions();} else {return [];} ";
script1 += script;
var f = new Function(script1);
params = f();
if ((typeof(params) != "object") || (typeof(params.length) != "number")) {
throw new Error("The getParameterDefinitions() function should return an array with the parameter definitions");
}
}
return params;
};
/**
* options parameter:
* - drawLines: display wireframe lines
* - drawFaces: display surfaces
* - bgColor: canvas background color
* - color: object color
* - viewerwidth, viewerheight: set rendering size. Works with any css unit.
* viewerheight can also be specified as a ratio to width, ie number e (0, 1]
* - noWebGL: force render without webGL
* - verbose: show additional info (currently only time used for rendering)
*/
OpenJsCad.Processor = function(containerdiv, options, onchange) {
this.containerdiv = containerdiv;
this.options = options = options || {};
this.onchange = onchange;
// Draw black triangle lines ("wireframe")
this.options.drawLines = !!this.cleanOption(options.drawLines, false);
// Draw surfaces
this.options.drawFaces = !!this.cleanOption(options.drawFaces, true);
// verbose output
this.options.verbose = !!this.cleanOption(options.verbose, true);
// default applies unless sizes specified in options
this.widthDefault = "565px";
this.heightDefault = "300px";
this.viewerdiv = null;
this.viewer = null;
this.viewerSize = {
widthDefault: this.widthDefault,
heightDefault: this.heightDefault,
width: this.options.viewerwidth,
height: this.options.viewerheight,
heightratio: this.options.viewerheightratio
};
// this.viewerwidth = this.options.viewerwidth || "800px";
// this.viewerheight = this.options.viewerheight || "600px";
this.processing = false;
this.currentObject = null;
this.hasValidCurrentObject = false;
this.hasOutputFile = false;
this.worker = null;
this.paramDefinitions = [];
this.paramControls = [];
this.script = null;
this.hasError = false;
this.debugging = false;
this.createElements();
};
OpenJsCad.Processor.convertToSolid = function(obj) {
if ((typeof(obj) == "object") && ((obj instanceof CAG))) {
// convert a 2D shape to a thin solid:
obj = obj.extrude({
offset: [0, 0, 0.1]
});
} else if ((typeof(obj) == "object") && ((obj instanceof CSG))) {
// obj already is a solid
} else {
throw new Error("Cannot convert to solid");
}
return obj;
};
OpenJsCad.Processor.prototype = {
cleanOption: function(option, deflt) {
return typeof option != "undefined" ? option : deflt;
},
// pass "faces" or "lines"
toggleDrawOption: function(str) {
if (str == 'faces' || str == 'lines') {
var newState = !this.viewer.drawOptions[str];
this.setDrawOption(str, newState);
return newState;
}
},
// e.g. setDrawOption('lines', false);
setDrawOption: function(str, bool) {
if (str == 'faces' || str == 'lines') {
this.viewer.drawOptions[str] = !!bool;
}
this.viewer.applyDrawOptions();
},
handleResize: function() {
this.viewer && (this.viewer.handleResize());
},
createElements: function() {
var that = this; //for event handlers
while (this.containerdiv.children.length > 0) {
this.containerdiv.removeChild(this.containerdiv.children[0]);
}
var viewerdiv = document.createElement("div");
viewerdiv.className = "viewer";
this.containerdiv.appendChild(viewerdiv);
this.viewerdiv = viewerdiv;
this.viewer = new OpenJsCad.Viewer(this.viewerdiv, this.viewerSize, this.options);
this.errordiv = document.createElement("div");
this.errordiv.className = "well";
this.errorpre = document.createElement("pre");
this.errordiv.appendChild(this.errorpre);
this.statusdiv = document.createElement("div");
//this.statusdiv.className = "statusdiv";
this.statusdiv.className = "well";
// surface/line draw
this.controldiv = document.createElement("div");
this.controldiv.style.cssText = 'display:none;';
var this_ = this;
[
['faces', 'surfaces', this.options.drawFaces],
['lines', 'lines', this.options.drawLines]
].forEach(function(tup) {
var cb = document.createElement('input');
cb.type = 'checkbox';
cb.id = 'cb_' + tup[0];
cb.checked = tup[2];
cb.addEventListener('click', function() {
this.checked = this_.toggleDrawOption(tup[0])
});
var lb = document.createElement('label');
lb.htmlFor = "cb_" + tup[0];
lb.appendChild(document.createTextNode(tup[1] + " "));
[cb, lb].forEach(function(ui) {
this.controldiv.appendChild(ui)
}, this);
}, this);
this.statusspan = document.createElement("span");
this.statusbuttons = document.createElement("div");
this.statusbuttons.style.float = "right";
this.statusdiv.appendChild(this.statusspan);
this.statusdiv.appendChild(this.statusbuttons);
this.statusdiv.appendChild(this.controldiv);
this.abortbutton = document.createElement("button");
this.abortbutton.innerHTML = "Abort";
this.abortbutton.onclick = function(e) {
that.abort();
};
this.statusbuttons.appendChild(this.abortbutton);
this.renderedElementDropdown = document.createElement("select");
this.renderedElementDropdown.onchange = function(e) {
that.setSelectedObjectIndex(that.renderedElementDropdown.selectedIndex);
};
this.renderedElementDropdown.style.display = "none";
this.statusbuttons.appendChild(this.renderedElementDropdown);
this.formatDropdown = document.createElement("select");
this.formatDropdown.onchange = function(e) {
that.currentFormat = that.formatDropdown.options[that.formatDropdown.selectedIndex].value;
that.updateDownloadLink();
};
this.statusbuttons.appendChild(this.formatDropdown);
this.generateOutputFileButton = document.createElement("button");
this.generateOutputFileButton.onclick = function(e) {
that.generateOutputFile();
};
this.statusbuttons.appendChild(this.generateOutputFileButton);
this.downloadOutputFileLink = document.createElement("a");
this.statusbuttons.appendChild(this.downloadOutputFileLink);
this.parametersdiv = document.createElement("div");
this.parametersdiv.className = "parametersdiv";
var headerdiv = document.createElement("div");
headerdiv.textContent = "Parameters:";
headerdiv.className = "header";
this.parametersdiv.appendChild(headerdiv);
this.parameterstable = document.createElement("table");
this.parameterstable.className = "parameterstable";
this.parametersdiv.appendChild(this.parameterstable);
var parseParametersButton = document.createElement("button");
parseParametersButton.style.cssText = 'margin: 10px;';
parseParametersButton.className = "button";
parseParametersButton.innerHTML = "<i></i>Update and Preview...";
parseParametersButton.onclick = function(e) {
//that.generateOutputFile();
that.rebuildSolid();
};
this.parametersdiv.appendChild(parseParametersButton);
this.parametersdiv.appendChild(parseParametersButton);
this.enableItems();
this.containerdiv.appendChild(this.statusdiv);
this.containerdiv.appendChild(this.errordiv);
this.containerdiv.appendChild(this.parametersdiv);
this.clearViewer();
},
getFilenameForRenderedObject: function() {
var filename = this.filename;
if (!filename) filename = "openjscad";
var index = this.renderedElementDropdown.selectedIndex;
if (index >= 0) {
var renderedelement = this.currentObjects[index];
if ('name' in renderedelement) {
filename = renderedelement.name;
} else {
filename += "_" + (index + 1);
}
}
return filename;
},
setRenderedObjects: function(obj) {
// if obj is a single CSG or CAG, convert to the array format:
if (obj === null) {
obj = [];
} else {
if (!(obj instanceof Array)) {
obj = [{
data: obj,
}, ];
}
}
this.currentObjects = obj;
while (this.renderedElementDropdown.options.length > 0) this.renderedElementDropdown.options.remove(0);
for (var i = 0; i < obj.length; ++i) {
var renderedelement = obj[i];
var caption;
if ('caption' in renderedelement) {
caption = renderedelement.caption;
} else if ('name' in renderedelement) {
caption = renderedelement.name;
} else {
caption = "Element #" + (i + 1);
}
var option = document.createElement("option");
option.appendChild(document.createTextNode(caption));
this.renderedElementDropdown.options.add(option);
}
this.renderedElementDropdown.style.display = (obj.length >= 2) ? "inline" : "none";
this.setSelectedObjectIndex((obj.length > 0) ? 0 : -1);
},
setSelectedObjectIndex: function(index) {
this.clearOutputFile();
this.renderedElementDropdown.selectedIndex = index;
var obj;
if (index < 0) {
obj = null;
} else {
obj = this.currentObjects[index].data;
}
this.currentObjectIndex = index;
this.currentObject = obj;
while (this.formatDropdown.options.length > 0)
this.formatDropdown.options.remove(0);
if (obj !== null) {
var csg = OpenJsCad.Processor.convertToSolid(obj);
// // reset zoom unless toggling between valid objects
// this.viewer.setCsg(csg, !this.hasValidCurrentObject);
this.isFirstRender_ = typeof this.isFirstRender_ == 'undefined' ? true : false;
// (re-)set zoom only on very first rendering action
this.viewer.setCsg(csg, this.isFirstRender_);
this.hasValidCurrentObject = true;
this.supportedFormatsForCurrentObject().forEach(function(format) {