forked from jscad/OpenJSCAD.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openjscad.js
1726 lines (1593 loc) · 54.2 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
// == openjscad.js, originally written by Joost Nieuwenhuijse (MIT License)
// few adjustments by Rene K. Mueller <[email protected]> for OpenJSCAD.org
//
// History:
// 2016/06/27: 0.5.1: incrementing version number for release
// 2016/05/01: 0.5.0: added SVG import and export, added options to Processor and View classes, allow more flexibility in HTML by Z3 Dev
// 2016/02/25: 0.4.0: GUI refactored, functionality split up into more files, mostly done by Z3 Dev
// 2013/03/12: reenable webgui parameters to fit in current design
// 2013/03/11: few changes to fit design of http://openjscad.org
(function(module) {
var OpenJsCad = function() { };
OpenJsCad.version = '0.5.1 (2016/06/27)';
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);
} else if( (typeof(self) == "object") && (typeof(self.postMessage) == "function") ) {
self.postMessage({cmd: 'log', txt: txt});
}
else throw new Error("Cannot log");
};
// See Processor.setStatus()
// Note: leave for compatibility
OpenJsCad.status = function(s) {
OpenJsCad.log(s);
}
OpenJsCad.env = function() {
var env = "OpenJSCAD "+OpenJsCad.version;
if(typeof document !== 'undefined') {
var w = document.defaultView;
env = env+" ["+w.navigator.userAgent+"]";
} else {
if (typeof require == 'function') {
var os = require("os");
env = env+" ["+os.type()+":"+os.release()+","+os.platform()+":"+os.arch()+"]";
}
}
console.log(env);
}
// 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(containerelement) {
// see the various methods below on how to change these
this.camera = {
fov: 45, // field of view
angle: {x: -60,y: 0,z: -45}, // view angle about XYZ axis
position: {x: 0,y: 0,z: 100}, // initial position at XYZ
clip: {min: 0.5, max: 1000}, // rendering outside this range is clipped
};
this.plate = {
draw: true, // draw or not
size: 200, // plate size (X and Y)
// minor grid settings
m: {
i: 1, // number of units between minor grid lines
r: .8, g: .8, b: .8, a: .5, // color
},
// major grid settings
M: {
i: 10, // number of units between major grid lines
r: .5, g: .5, b: .5, a: .5, // color
},
};
this.axis = {
draw: false, // draw or not
x: {
neg: {r: 1, g: .5, b: .5, a: .5}, // color in negative direction
pos: {r: 1, g: 0, b: 0, a: .8}, // color in positive direction
},
y: {
neg: {r: .5, g: 1, b: .5, a: .5}, // color in negative direction
pos: {r: 0, g: 1, b: 0, a: .8}, // color in positive direction
},
z: {
neg: {r: .5, g: .5, b: 1, a: .5}, // color in negative direction
pos: {r: 0, g: 0, b: 1, a: .8}, // color in positive direction
},
};
this.solid = {
draw: true, // draw or not
lines: false, // draw outlines or not
overlay: false, // use overlay when drawing lines or not
smooth: false, // use smoothing or not
color: [1,.4,1,1], // default color
};
// Set up WebGL state
var gl = GL.create();
this.gl = gl;
this.gl.lineWidth(1); // don't let the library choose
// Set up the viewport
this.gl.canvas.width = $(containerelement).width();
this.gl.canvas.height = $(containerelement).height();
this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height); // pixels
this.gl.matrixMode(this.gl.PROJECTION);
this.gl.loadIdentity();
this.gl.perspective(this.camera.fov, this.gl.canvas.width / this.gl.canvas.height, this.camera.clip.min, this.camera.clip.max);
this.gl.matrixMode(this.gl.MODELVIEW);
this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA);
this.gl.clearColor(0.93, 0.93, 0.93, 1);
this.gl.enable(this.gl.DEPTH_TEST);
this.gl.enable(this.gl.CULL_FACE);
// Black shader for wireframe
this.blackShader = new GL.Shader('\
void main() {\
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\
}', '\
void main() {\
gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);\
}'
);
// Shader with diffuse and specular lighting
this.lightingShader = new GL.Shader('\
varying vec3 color;\
varying float alpha;\
varying vec3 normal;\
varying vec3 light;\
void main() {\
const vec3 lightDir = vec3(1.0, 2.0, 3.0) / 3.741657386773941;\
light = lightDir;\
color = gl_Color.rgb;\
alpha = gl_Color.a;\
normal = gl_NormalMatrix * gl_Normal;\
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\
}',
'\
varying vec3 color;\
varying float alpha;\
varying vec3 normal;\
varying vec3 light;\
void main() {\
vec3 n = normalize(normal);\
float diffuse = max(0.0, dot(light, n));\
float specular = pow(max(0.0, -reflect(light, n).z), 10.0) * sqrt(diffuse);\
gl_FragColor = vec4(mix(color * (0.3 + 0.7 * diffuse), vec3(1.0), specular), alpha);\
}'
);
var _this=this;
var shiftControl = $('<div class="shift-scene"><div class="arrow arrow-left" />\
<div class="arrow arrow-right" />\
<div class="arrow arrow-top" />\
<div class="arrow arrow-bottom" /></div>');
$(containerelement).append(this.gl.canvas)
.append(shiftControl)
.hammer({//touch screen control
drag_lock_to_axis: true
}).on("transform", function(e){
if (e.gesture.touches.length >= 2) {
_this.clearShift();
_this.onTransform(e);
e.preventDefault();
}
}).on("touch", function(e) {
if (e.gesture.pointerType != 'touch'){
e.preventDefault();
return;
}
if (e.gesture.touches.length == 1) {
var point = e.gesture.center;
_this.touch.shiftTimer = setTimeout(function(){
shiftControl.addClass('active').css({
left: point.pageX + 'px',
top: point.pageY + 'px'
});
_this.touch.shiftTimer = null;
_this.touch.cur = 'shifting';
}, 500);
} else {
_this.clearShift();
}
}).on("drag", function(e) {
if (e.gesture.pointerType != 'touch') {
e.preventDefault();
return;
}
if (!_this.touch.cur || _this.touch.cur == 'dragging') {
_this.clearShift();
_this.onPanTilt(e);
} else if (_this.touch.cur == 'shifting') {
_this.onShift(e);
}
}).on("touchend", function(e) {
_this.clearShift();
if (_this.touch.cur) {
shiftControl.removeClass('active shift-horizontal shift-vertical');
}
}).on("transformend dragstart dragend", function(e) {
if ((e.type == 'transformend' && _this.touch.cur == 'transforming') ||
(e.type == 'dragend' && _this.touch.cur == 'shifting') ||
(e.type == 'dragend' && _this.touch.cur == 'dragging'))
_this.touch.cur = null;
_this.touch.lastX = 0;
_this.touch.lastY = 0;
_this.touch.scale = 0;
});
this.gl.onmousemove = function(e) {
_this.onMouseMove(e);
};
this.gl.ondraw = function() {
_this.onDraw();
};
this.gl.resizeCanvas = function() {
var canvasWidth = _this.gl.canvas.clientWidth;
var canvasHeight = _this.gl.canvas.clientHeight;
if (_this.gl.canvas.width != canvasWidth ||
_this.gl.canvas.height != canvasHeight) {
_this.gl.canvas.width = canvasWidth;
_this.gl.canvas.height = canvasHeight;
_this.gl.viewport(0, 0, _this.gl.canvas.width, _this.gl.canvas.height);
_this.gl.matrixMode( _this.gl.PROJECTION );
_this.gl.loadIdentity();
_this.gl.perspective(_this.camera.fov, _this.gl.canvas.width / _this.gl.canvas.height, _this.camera.clip.min, _this.camera.clip.max );
_this.gl.matrixMode( _this.gl.MODELVIEW );
_this.onDraw();
}
};
// only window resize is available, so add an event callback for the canvas
window.addEventListener( 'resize', this.gl.resizeCanvas );
this.gl.onmousewheel = function(e) {
var wheelDelta = 0;
if (e.wheelDelta) {
wheelDelta = e.wheelDelta;
} else if (e.detail) {
// for firefox, see http://stackoverflow.com/questions/8886281/event-wheeldelta-returns-undefined
wheelDelta = e.detail * -40;
}
if(wheelDelta) {
var factor = Math.pow(1.003, -wheelDelta);
var coeff = _this.getZoom();
coeff *= factor;
_this.setZoom(coeff);
}
};
// state variables, i.e. used for storing values, etc
// state of viewer
// 0 - initialized, no object
// 1 - cleared, no object
// 2 - showing, object
this.state = 0;
// state of perpective (camera)
this.angleX = this.camera.angle.x;
this.angleY = this.camera.angle.y;
this.angleZ = this.camera.angle.z;
this.viewpointX = this.camera.position.x;
this.viewpointY = this.camera.position.y;
this.viewpointZ = this.camera.position.z;
this.onZoomChanged = null;
this.touch = {
lastX: 0,
lastY: 0,
scale: 0,
ctrl: 0,
shiftTimer: null,
shiftControl: shiftControl,
cur: null //current state
};
this.meshes = [];
this.clear(); // and draw the inital viewer
};
OpenJsCad.Viewer.prototype = {
setCsg: function(csg) {
if(0&&csg.length) { // preparing multiple CSG's (not union-ed), not yet working
for(var i=0; i<csg.length; i++)
this.meshes.concat(this.csgToMeshes(csg[i]));
} else {
this.meshes = this.csgToMeshes(csg);
}
this.state = 2; // showing, object
this.onDraw();
},
clear: function() {
// empty mesh list:
this.meshes = [];
this.state = 1; // cleared, no object
this.onDraw();
},
reset: function() {
// reset camera to initial settings
this.angleX = this.camera.angle.x;
this.angleY = this.camera.angle.y;
this.angleZ = this.camera.angle.z;
this.viewpointX = this.camera.position.x;
this.viewpointY = this.camera.position.y;
this.viewpointZ = this.camera.position.z;
this.onDraw();
},
supported: function() {
return !!this.gl;
},
setCameraOptions: function(options) {
options = options || {};
// apply all options found
for (var x in this.camera) {
if (x in options) this.camera[x] = options[x];
}
},
setPlateOptions: function(options) {
options = options || {};
// apply all options found
for (var x in this.plate) {
if (x in options) this.plate[x] = options[x];
}
},
setAxisOptions: function(options) {
options = options || {};
// apply all options found
for (var x in this.axis) {
if (x in options) this.axis[x] = options[x];
}
},
setSolidOptions: function(options) {
options = options || {};
// apply all options found
for (var x in this.solid) {
if (x in options) this.solid[x] = options[x];
}
},
setZoom: function(coeff) { //0...1
coeff=Math.max(coeff, 0);
coeff=Math.min(coeff, 1);
this.viewpointZ = this.camera.clip.min + coeff * (this.camera.clip.max - this.camera.clip.min);
if(this.onZoomChanged) {
this.onZoomChanged();
}
this.onDraw();
},
getZoom: function() {
var coeff = (this.viewpointZ-this.camera.clip.min) / (this.camera.clip.max - this.camera.clip.min);
return coeff;
},
onMouseMove: function(e) {
if (e.dragging) {
//console.log(e.which,e.button);
var b = e.button;
if(e.which) { // RANT: not even the mouse buttons are coherent among the brand (chrome,firefox,etc)
b = e.which;
}
e.preventDefault();
if(e.altKey||b==3) { // ROTATE X,Y (ALT or right mouse button)
this.angleY += e.deltaX;
this.angleX += e.deltaY;
//this.angleX = Math.max(-180, Math.min(180, this.angleX));
} else if(e.shiftKey||b==2) { // PAN (SHIFT or middle mouse button)
var factor = 5e-3;
this.viewpointX += factor * e.deltaX * this.viewpointZ;
this.viewpointY -= factor * e.deltaY * this.viewpointZ;
} else if(e.ctrlKey||e.metaKey) { // ZOOM IN/OU
var factor = Math.pow(1.006, e.deltaX+e.deltaY);
var coeff = this.getZoom();
coeff *= factor;
this.setZoom(coeff);
} else { // ROTATE X,Z left mouse button
this.angleZ += e.deltaX;
this.angleX += e.deltaY;
}
this.onDraw();
}
},
clearShift: function() {
if(this.touch.shiftTimer) {
clearTimeout(this.touch.shiftTimer);
this.touch.shiftTimer = null;
}
return this;
},
//pan & tilt with one finger
onPanTilt: function(e) {
this.touch.cur = 'dragging';
var delta = 0;
if (this.touch.lastY && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) {
//tilt
delta = e.gesture.deltaY - this.touch.lastY;
this.angleX += delta;
} else if (this.touch.lastX && (e.gesture.direction == 'left' || e.gesture.direction == 'right')) {
//pan
delta = e.gesture.deltaX - this.touch.lastX;
this.angleZ += delta;
}
if (delta)
this.onDraw();
this.touch.lastX = e.gesture.deltaX;
this.touch.lastY = e.gesture.deltaY;
},
//shift after 0.5s touch&hold
onShift: function(e) {
this.touch.cur = 'shifting';
var factor = 5e-3;
var delta = 0;
if (this.touch.lastY && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) {
this.touch.shiftControl
.removeClass('shift-horizontal')
.addClass('shift-vertical')
.css('top', e.gesture.center.pageY + 'px');
delta = e.gesture.deltaY - this.touch.lastY;
this.viewpointY -= factor * delta * this.viewpointZ;
this.angleX += delta;
}
if (this.touch.lastX && (e.gesture.direction == 'left' || e.gesture.direction == 'right')) {
this.touch.shiftControl
.removeClass('shift-vertical')
.addClass('shift-horizontal')
.css('left', e.gesture.center.pageX + 'px');
delta = e.gesture.deltaX - this.touch.lastX;
this.viewpointX += factor * delta * this.viewpointZ;
this.angleZ += delta;
}
if (delta)
this.onDraw();
this.touch.lastX = e.gesture.deltaX;
this.touch.lastY = e.gesture.deltaY;
},
//zooming
onTransform: function(e) {
this.touch.cur = 'transforming';
if (this.touch.scale) {
var factor = 1 / (1 + e.gesture.scale - this.touch.scale);
var coeff = this.getZoom();
coeff *= factor;
this.setZoom( coeff);
}
this.touch.scale = e.gesture.scale;
return this;
},
onDraw: function(e) {
var gl = this.gl;
gl.makeCurrent();
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.loadIdentity();
// set the perspective based on the camera postion
gl.translate(this.viewpointX, this.viewpointY, -this.viewpointZ);
gl.rotate(this.angleX, 1, 0, 0);
gl.rotate(this.angleY, 0, 1, 0);
gl.rotate(this.angleZ, 0, 0, 1);
// draw the solid (meshes)
if(this.solid.draw) {
gl.enable(gl.BLEND);
if (!this.solid.overlay) gl.enable(gl.POLYGON_OFFSET_FILL);
for (var i = 0; i < this.meshes.length; i++) {
var mesh = this.meshes[i];
this.lightingShader.draw(mesh, gl.TRIANGLES);
}
if (!this.solid.overlay) gl.disable(gl.POLYGON_OFFSET_FILL);
gl.disable(gl.BLEND);
if(this.solid.lines) {
if (this.solid.overlay) gl.disable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
for (var i = 0; i < this.meshes.length; i++) {
var mesh = this.meshes[i];
this.blackShader.draw(mesh, gl.LINES);
}
gl.disable(gl.BLEND);
if (this.solid.overlay) gl.enable(gl.DEPTH_TEST);
}
}
// draw the plate and the axis
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.begin(gl.LINES);
if(this.plate.draw) {
var m = this.plate.m; // short cut
var M = this.plate.M; // short cut
var size = this.plate.size/2;
// -- minor grid
gl.color(m.r,m.g,m.b,m.a);
var mg = m.i;
var MG = M.i;
for(var x=-size; x<=size; x+=mg) {
if(x%MG) { // draw only minor grid line
gl.vertex(-size, x, 0);
gl.vertex(size, x, 0);
gl.vertex(x, -size, 0);
gl.vertex(x, size, 0);
}
}
// -- major grid
gl.color(M.r,M.g,M.b,M.a);
for(var x=-size; x<=size; x+=MG) {
gl.vertex(-size, x, 0);
gl.vertex(size, x, 0);
gl.vertex(x, -size, 0);
gl.vertex(x, size, 0);
}
}
if (this.axis.draw) {
var size = this.plate.size/2;
// X axis
var c = this.axis.x.neg;
gl.color(c.r, c.g, c.b, c.a); //negative direction is lighter
gl.vertex(-size, 0, 0);
gl.vertex(0, 0, 0);
c = this.axis.x.pos;
gl.color(c.r, c.g, c.b, c.a); //positive direction is lighter
gl.vertex(0, 0, 0);
gl.vertex(size, 0, 0);
// Y axis
c = this.axis.y.neg;
gl.color(c.r, c.g, c.b, c.a); //negative direction is lighter
gl.vertex(0, -size, 0);
gl.vertex(0, 0, 0);
c = this.axis.y.pos;
gl.color(c.r, c.g, c.b, c.a); //positive direction is lighter
gl.vertex(0, 0, 0);
gl.vertex(0, size, 0);
// Z axis
c = this.axis.z.neg;
gl.color(c.r, c.g, c.b, c.a); //negative direction is lighter
gl.vertex(0, 0, -size);
gl.vertex(0, 0, 0);
c = this.axis.z.pos;
gl.color(c.r, c.g, c.b, c.a); //positive direction is lighter
gl.vertex(0, 0, 0);
gl.vertex(0, 0, size);
}
if(0) { // WHAT IS THIS FOR?
gl.triangle();
gl.color(0.6, 0.2, 0.6, 0.2); //positive direction
gl.vertex(-plate,-plate,0);
gl.vertex(plate,-plate,0);
gl.vertex(plate,plate,0);
gl.end();
gl.triangle();
gl.color(0.6, 0.2, 0.6, 0.2); //positive direction
gl.vertex(plate,plate,0);
gl.vertex(-plate,plate,0);
gl.vertex(-plate,-plate,0);
gl.end();
}
gl.end();
gl.disable(gl.BLEND);
},
// Convert from CSG solid to an array of GL.Mesh objects
// limiting the number of vertices per mesh to less than 2^16
csgToMeshes: function(initial_csg) {
var csg = initial_csg.canonicalized();
var mesh = new GL.Mesh({ normals: true, colors: true });
var meshes = [ mesh ];
var vertexTag2Index = {};
var vertices = [];
var colors = [];
var triangles = [];
// set to true if we want to use interpolated vertex normals
// this creates nice round spheres but does not represent the shape of
// the actual model
var smoothlighting = this.solid.smooth;
var polygons = csg.toPolygons();
var numpolygons = polygons.length;
for(var j = 0; j < numpolygons; j++) {
var polygon = polygons[j];
var color = this.solid.color; // default color
if(polygon.shared && polygon.shared.color) {
color = polygon.shared.color;
} else if(polygon.color) {
color = polygon.color;
}
if (color.length < 4)
color.push(1.); //opaque
var indices = polygon.vertices.map(function(vertex) {
var vertextag = vertex.getTag();
var vertexindex = vertexTag2Index[vertextag];
var prevcolor = colors[vertexindex];
if(smoothlighting && (vertextag in vertexTag2Index) &&
(prevcolor[0] == color[0]) &&
(prevcolor[1] == color[1]) &&
(prevcolor[2] == color[2])
) {
vertexindex = vertexTag2Index[vertextag];
} else {
vertexindex = vertices.length;
vertexTag2Index[vertextag] = vertexindex;
vertices.push([vertex.pos.x, vertex.pos.y, vertex.pos.z]);
colors.push(color);
}
return vertexindex;
});
for (var i = 2; i < indices.length; i++) {
triangles.push([indices[0], indices[i - 1], indices[i]]);
}
// if too many vertices, start a new mesh;
if (vertices.length > 65000) {
// finalize the old mesh
mesh.triangles = triangles;
mesh.vertices = vertices;
mesh.colors = colors;
mesh.computeWireframe();
mesh.computeNormals();
if ( mesh.vertices.length ) {
meshes.push(mesh);
}
// start a new mesh
mesh = new GL.Mesh({ normals: true, colors: true });
triangles = [];
colors = [];
vertices = [];
}
}
// finalize last mesh
mesh.triangles = triangles;
mesh.vertices = vertices;
mesh.colors = colors;
mesh.computeWireframe();
mesh.computeNormals();
if ( mesh.vertices.length ) {
meshes.push(mesh);
}
return meshes;
},
};
// this is a bit of a hack; doesn't properly supports urls that start with '/'
// but does handle relative urls containing ../
OpenJsCad.makeAbsoluteUrl = function(url, baseurl) {
if(!url.match(/^[a-z]+\:/i)) {
var basecomps = baseurl.split("/");
if(basecomps.length > 0) {
basecomps.splice(basecomps.length - 1, 1);
}
var urlcomps = url.split("/");
var comps = basecomps.concat(urlcomps);
var comps2 = [];
comps.map(function(c) {
if(c == "..") {
if(comps2.length > 0) {
comps2.splice(comps2.length - 1, 1);
}
} else {
comps2.push(c);
}
});
url = "";
for(var i = 0; i < comps2.length; i++) {
if(i > 0) url += "/";
url += comps2[i];
}
}
return url;
};
OpenJsCad.isChrome = function() {
return (window.navigator.userAgent.search("Chrome") >= 0);
};
OpenJsCad.isSafari = function() {
return /Version\/[\d\.]+.*Safari/.test(window.navigator.userAgent); // FIXME WWW says don't use this
}
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);
};
// Call this routine to install a handler for uncaught exceptions
OpenJsCad.AlertUserOfUncaughtExceptions = function() {
window.onerror = function(message, url, line) {
var msg = "uncaught exception";
switch (arguments.length) {
case 1: // message
msg = arguments[0];
break;
case 2: // message and url
msg = arguments[0]+'\n('+arguments[1]+')';
break;
case 3: // message and url and line#
msg = arguments[0]+'\nLine: '+arguments[2]+'\n('+arguments[1]+')';
break;
case 4: // message and url and line# and column#
case 5: // message and url and line# and column# and Error
msg = arguments[0]+'\nLine: '+arguments[2]+',col: '+arguments[3]+'\n('+arguments[1]+')';
break;
default:
break;
}
if(typeof document == 'object') {
var e = document.getElementById("errordiv");
if (e !== null) {
e.firstChild.textContent = msg;
e.style.display = "block";
}
} else {
console.log(msg);
}
return false;
};
};
// parse the jscad script to get the parameter definitions
OpenJsCad.getParamDefinitions = function(script) {
var scriptisvalid = true;
script += "\nfunction include() {}"; // at least make it not throw an error so early
try
{
// first try to execute the script itself
// this will catch any syntax errors
// BUT we can't introduce any new function!!!
(new Function(script))();
}
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;
};
OpenJsCad.Processor = function(containerdiv, options) {
if (options === undefined) options = {};
// the default options
this.opts = {
debug: false,
libraries: ['csg.js','formats.js','openjscad.js','openscad.js'],
openJsCadPath: '',
useAsync: true,
useSync: true,
};
// apply all options found
for (var x in this.opts) {
if (x in options) this.opts[x] = options[x];
}
this.containerdiv = containerdiv;
this.viewer = null;
this.worker = null;
this.zoomControl = null;
// callbacks
this.onchange = null; // function(Processor) for callback
this.ondownload = null; // function(Processor) for callback
this.currentObject = null;
this.hasOutputFile = false;
this.hasError = false;
this.paramDefinitions = [];
this.paramControls = [];
this.script = null;
this.baseurl = document.location.href;
this.baseurl = this.baseurl.replace(/#.*$/,''); // remove remote URL
this.baseurl = this.baseurl.replace(/\?.*$/,''); // remove parameters
if (this.baseurl.lastIndexOf('/') != (this.baseurl.length-1)) {
this.baseurl = this.baseurl.substring(0,this.baseurl.lastIndexOf('/')+1);
}
// state of the processor
// 0 - initialized - no viewer, no parameters, etc
// 1 - processing - processing JSCAD script
// 2 - complete - completed processing
// 3 - incomplete - incompleted due to errors in processing
this.state = 0; // initialized
this.createElements();
};
OpenJsCad.Processor.convertToSolid = function(objs) {
if (objs.length === undefined) {
if ((objs instanceof CAG) || (objs instanceof CSG)) {
var obj = objs;
objs = [obj];
} else {
throw new Error("Cannot convert object ("+typeof(objs)+") to solid");
}
}
var solid = null;
for(var i=0; i<objs.length; i++) {
var obj = objs[i];
if (obj instanceof CAG) {
obj = obj.extrude({offset: [0,0,0.1]}); // convert CAG to a thin solid CSG
}
if (solid !== null) {
solid = solid.unionForNonIntersecting(obj);
} else {
solid = obj;
}
}
return solid;
};
OpenJsCad.Processor.prototype = {
createElements: function() {
var that = this; // for event handlers
while(this.containerdiv.children.length > 0)
{
this.containerdiv.removeChild(0);
}
var viewerdiv = document.createElement("div");
viewerdiv.className = "viewer";
viewerdiv.style.width = '100%';
viewerdiv.style.height = '100%';
this.containerdiv.appendChild(viewerdiv);
try {
this.viewer = new OpenJsCad.Viewer(viewerdiv);
} catch(e) {
viewerdiv.innerHTML = "<b><br><br>Error: " + e.toString() + "</b><br><br>A browser with support for WebGL is required";
}
//Zoom control
if(0) {
var div = document.createElement("div");
this.zoomControl = div.cloneNode(false);
this.zoomControl.style.width = this.viewerwidth + 'px';
this.zoomControl.style.height = '20px';
this.zoomControl.style.backgroundColor = 'transparent';
this.zoomControl.style.overflowX = 'scroll';
div.style.width = this.viewerwidth * 11 + 'px';
div.style.height = '1px';
this.zoomControl.appendChild(div);
this.zoomChangedBySlider = false;
this.zoomControl.onscroll = function(event) {
var zoom = that.zoomControl;
var newzoom=zoom.scrollLeft / (10 * zoom.offsetWidth);
that.zoomChangedBySlider=true; // prevent recursion via onZoomChanged
that.viewer.setZoom(newzoom);
that.zoomChangedBySlider=false;
};
this.viewer.onZoomChanged = function() {
if(!that.zoomChangedBySlider)
{
var newzoom = that.viewer.getZoom();
that.zoomControl.scrollLeft = newzoom * (10 * that.zoomControl.offsetWidth);
}
};
this.containerdiv.appendChild(this.zoomControl);
this.zoomControl.scrollLeft = this.viewer.viewpointZ / this.viewer.camera.clip.max *
(this.zoomControl.scrollWidth - this.zoomControl.offsetWidth);
//end of zoom control
}
this.errordiv = this.containerdiv.parentElement.querySelector("div#errordiv");
if (!this.errordiv) {
this.errordiv = document.createElement("div");
this.errordiv.id = 'errordiv';
this.containerdiv.parentElement.appendChild(this.errordiv);
}
this.errorpre = document.createElement("pre");
this.errordiv.appendChild(this.errorpre);
this.statusdiv = this.containerdiv.parentElement.querySelector("div#statusdiv");
if (!this.statusdiv) {
this.statusdiv = document.createElement("div");
this.statusdiv.id = "statusdiv";
this.containerdiv.parentElement.appendChild(this.statusdiv);
}
this.statusspan = document.createElement("span");
this.statusspan.id = 'statusspan';
this.statusbuttons = document.createElement("span");
this.statusbuttons.id = 'statusbuttons';
this.statusdiv.appendChild(this.statusspan);
this.statusdiv.appendChild(this.statusbuttons);
this.abortbutton = document.createElement("button");
this.abortbutton.innerHTML = "Abort";
this.abortbutton.onclick = function(e) {
that.abort();
};
this.statusbuttons.appendChild(this.abortbutton);
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.downloadOutputFileLink.className = "downloadOutputFileLink"; // so we can css it
this.statusbuttons.appendChild(this.downloadOutputFileLink);
this.parametersdiv = this.containerdiv.parentElement.querySelector("div#parametersdiv");
if (!this.parametersdiv) {
this.parametersdiv = document.createElement("div");
this.parametersdiv.id = "parametersdiv";
this.containerdiv.parentElement.appendChild(this.parametersdiv);
}
this.parameterstable = document.createElement("table");
this.parameterstable.className = "parameterstable";
this.parametersdiv.appendChild(this.parameterstable);
var element = this.parametersdiv.querySelector("button#updateButton");
if (element === null) {
element = document.createElement("button");
element.innerHTML = "Update";