-
Notifications
You must be signed in to change notification settings - Fork 191
/
glviewer.js
3867 lines (3432 loc) · 145 KB
/
glviewer.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
//a molecular viewer based on GLMol
/**
* WebGL-based 3Dmol.js viewer
* Note: The preferred method of instantiating a GLViewer is through {@link $3Dmol.createViewer}
*
* @constructor
* @param {Object} element HTML element within which to create viewer
* @param {Object} config Object containing optional configuration for the viewer including:
* @param {function} config.callback - Callback function to be immediately executed on this viewer
* @param {Object} config.defaultcolors - Object defining default atom colors as atom => color property value pairs for all models within this viewer
* @param {boolean} config.nomouse - Whether to disable mouse handlers
* @param {string} config.backgroundColor - Color of the canvas' background
* @param {number} config.camerax
* @param {number} config.hoverDuration
* @param {string} config.id - id of the canvas
* @param config.row
* @param config.col
* @param config.rows
* @param config.cols
* @param config.canvases
* @param config.viewers
* @param {boolean} config.control_all
* @param {boolean} config.orthographic
*/
$3Dmol.GLViewer = (function() {
// private class variables
var numWorkers = 4; // number of threads for surface generation
var maxVolume = 64000; // how much to break up surface calculations
// private class helper functions
function GLViewer(element, config) {
// set variables
config = config || {};
var callback = config.callback;
var defaultcolors = config.defaultcolors;
if(!defaultcolors)
defaultcolors = $3Dmol.elementColors.defaultColors;
var nomouse = config.nomouse;
var bgColor = 0;
config.backgroundColor = config.backgroundColor || "#ffffff";
//config.disableFog= config.disableFog || false;
if(typeof(config.backgroundColor) != undefined) {
bgColor = $3Dmol.CC.color(config.backgroundColor).getHex();
}
var camerax = 0;
if(typeof(config.camerax) != undefined) {
camerax = parseFloat(config.camerax);
}
var _viewer = this;
var container = element;
var id = container.id;
var glDOM = null;
var models = []; // atomistic molecular models
var surfaces = {};
var shapes = []; // Generic shapes
var labels = [];
var fixed_labels = [];
var clickables = []; //things you can click on
var hoverables = []; //things you can hover over
var popups = [];
var current_hover = null;
var hoverDuration = 500;
if(typeof(config.hoverDuration) != undefined) {
hoverDuration = config.hoverDuration;
}
var WIDTH = container.width();
var HEIGHT = container.height();
// set dimensions
// $(container).width(WIDTH);
// $(container).height(HEIGHT);
var NEAR = 1, FAR = 800;
var CAMERA_Z = 150;
var fov = 20;
var linkedViewers = [];
var renderer = new $3Dmol.Renderer({
antialias : true,
preserveDrawingBuffer: true, //so we can export images
premultipliedAlpha : false,/* more traditional compositing with background */
id:config.id,
row:config.row,
col:config.col,
rows:config.rows,
cols:config.cols,
canvas:config.canvas
});
renderer.domElement.style.width = "100%";
renderer.domElement.style.height = "100%";
renderer.domElement.style.padding = "0";
renderer.domElement.style.position = "absolute"; //TODO: get rid of this
renderer.domElement.style.top = "0px";
renderer.domElement.style.left = "0px";
renderer.domElement.style.zIndex = "0";
var row = config.row;
var col = config.col;
var cols = config.cols;
var rows = config.rows;
var viewers = config.viewers;
var control_all = config.control_all;
var ASPECT =renderer.getAspect(WIDTH,HEIGHT);
var camera = new $3Dmol.Camera(fov, ASPECT, NEAR, FAR, config.orthographic);
camera.position = new $3Dmol.Vector3(camerax, 0, CAMERA_Z);
var lookingAt = new $3Dmol.Vector3();
camera.lookAt(lookingAt);
var raycaster = new $3Dmol.Raycaster(new $3Dmol.Vector3(0, 0, 0),
new $3Dmol.Vector3(0, 0, 0));
var projector = new $3Dmol.Projector();
var mouseVector = new $3Dmol.Vector3(0, 0, 0);
var scene = null;
var rotationGroup = null; // which contains modelGroup
var modelGroup = null;
var fogStart = 0.4;
var slabNear = -50; // relative to the center of rotationGroup
var slabFar = 50;
// UI variables
var cq = new $3Dmol.Quaternion(0, 0, 0, 1);
var dq = new $3Dmol.Quaternion(0, 0, 0, 1);
var animated = 0;
var isDragging = false;
var mouseStartX = 0;
var mouseStartY = 0;
var touchDistanceStart = 0;
var currentModelPos = 0;
var cz = 0;
var cslabNear = 0;
var cslabFar = 0;
var decAnim = function() {
//decrement the number of animations currently
animated--;
if(animated < 0) animated = 0;
}
var incAnim = function() {
animated++;
}
var nextSurfID = function() {
//compute the next highest surface id directly from surfaces
//this is necessary to support linking of model data
var max = 0;
for (var i in surfaces) { // this is an object with possible holes
if(!surfaces.hasOwnProperty(i)) continue;
var val = parseInt(i);
if(!isNaN(val)) i = val;
if(i > max) max = i;
}
return max+1;
};
//updates font size of labels based on camera zoom
var setLabelStyles = function(scaleFactor){
for(var label in labels){
var label = labels[label];
if(label.stylespec.scale){
modelGroup.remove(label.sprite);
label.dispose();
//change font size here
label.stylespec.fontSize*=(1+scaleFactor);
label.setContext();
modelGroup.add(label.sprite);
}
}
}
var setSlabAndFog = function() {
var center = camera.position.z - rotationGroup.position.z;
if (center < 1)
center = 1;
camera.near = center + slabNear;
if (camera.near < 1)
camera.near = 1;
camera.far = center + slabFar;
if (camera.near + 1 > camera.far)
camera.far = camera.near + 1;
camera.fov = fov;
camera.right = center * Math.tan(Math.PI / 180 * fov);
camera.left = -camera.right;
camera.top = camera.right / ASPECT;
camera.bottom = -camera.top;
camera.updateProjectionMatrix();
scene.fog.near = camera.near + fogStart
* (camera.far - camera.near);
// if (scene.fog.near > center) scene.fog.near = center;
scene.fog.far = camera.far;
if(config.disableFog){
scene.fog.near=scene.fog.far;
}
};
// display scene
//if nolink is set/true, don't propagate changes to linked viewers
var show = function(nolink) {
renderer.setViewport();
if (!scene)
return;
// var time = new Date();
setSlabAndFog();
renderer.render(scene, camera);
// console.log("rendered in " + (+new Date() - time) + "ms");
if(!nolink && linkedViewers.length > 0) {
var view = _viewer.getView();
for(var i = 0; i < linkedViewers.length; i++) {
var other = linkedViewers[i];
other.setView(view, true);
}
}
};
var initializeScene = function() {
scene = new $3Dmol.Scene();
scene.fog = new $3Dmol.Fog(bgColor, 100, 200);
modelGroup = new $3Dmol.Object3D();
rotationGroup = new $3Dmol.Object3D();
rotationGroup.useQuaternion = true;
rotationGroup.quaternion = new $3Dmol.Quaternion(0, 0, 0, 1);
rotationGroup.add(modelGroup);
scene.add(rotationGroup);
// setup lights
var directionalLight = new $3Dmol.Light(0xFFFFFF);
directionalLight.position = new $3Dmol.Vector3(0.2, 0.2, 1)
.normalize();
directionalLight.intensity = 1.0;
scene.add(directionalLight);
};
initializeScene();
renderer.setClearColorHex(bgColor, 1.0);
scene.fog.color = $3Dmol.CC.color(bgColor);
var clickedAtom = null;
// enable mouse support
//regenerate the list of clickables
//also updates hoverables
var updateClickables = function() {
clickables.splice(0,clickables.length);
hoverables.splice(0,hoverables.length);
var i, il;
for (i = 0, il = models.length; i < il; i++) {
var model = models[i];
if(model) {
var atoms = model.selectedAtoms({
clickable : true
});
var hoverable_atoms = model.selectedAtoms({
hoverable : true
});
Array.prototype.push.apply(hoverables,hoverable_atoms);
Array.prototype.push.apply(clickables, atoms); //add atoms into clickables
}
}
for (i = 0, il = shapes.length; i < il; i++) {
var shape = shapes[i];
if (shape && shape.clickable) {
clickables.push(shape);
}
if( shape && shape.hoverable){
hoverables.push(shape);
}
}
};
// Checks for selection intersects on mousedown
var handleClickSelection = function(mouseX, mouseY, event) {
if(clickables.length == 0) return;
var mouse = {
x : mouseX,
y : mouseY,
z : -1.0
};
raycaster.setFromCamera(mouse,camera);
var intersects = [];
intersects = raycaster.intersectObjects(modelGroup, clickables);
if (intersects.length) {
var selected = intersects[0].clickable;
if (selected.callback !== undefined
&& typeof (selected.callback) === "function") {
selected.callback(selected, _viewer, event, container);
}
}
};
//set current_hover to sel (which can be null), calling appropraite callbacks
var setHover = function(selected, event) {
if(current_hover == selected) return;
if(current_hover) current_hover.unhover_callback(current_hover, _viewer, event, container);
current_hover=selected;
if (selected && selected.hover_callback !== undefined
&& typeof (selected.hover_callback) === "function") {
selected.hover_callback(selected, _viewer, event, container);
}
};
//checks for selection intersects on hover
var handleHoverSelection = function(mouseX, mouseY, event){
if(hoverables.length == 0) return;
var mouse = {
x : mouseX,
y : mouseY,
z : -1.0
};
raycaster.setFromCamera(mouse,camera);
var intersects = [];
intersects = raycaster.intersectObjects(modelGroup, hoverables);
if (intersects.length) {
var selected = intersects[0].clickable;
setHover(selected);
current_hover=selected;
}
else{
setHover(null);
}
}
//sees if the mouse is still on the object that invoked a hover event and if not then the unhover callback is called
var handleHoverContinue = function(mouseX,mouseY,event){
var mouse = {
x : mouseX,
y : mouseY,
z : -1.0
};
raycaster.setFromCamera(mouse,camera);
var intersects = [];
intersects = raycaster.intersectObjects(modelGroup, hoverables);
if(intersects.length == 0 || intersects[0] === undefined){
setHover(null);
}
if(intersects[0]!== undefined && intersects[0].clickable !== current_hover){
setHover(null);
}
}
var calcTouchDistance = function(ev) { // distance between first two
// fingers
var xdiff = ev.originalEvent.targetTouches[0].pageX
- ev.originalEvent.targetTouches[1].pageX;
var ydiff = ev.originalEvent.targetTouches[0].pageY
- ev.originalEvent.targetTouches[1].pageY;
return Math.sqrt(xdiff * xdiff + ydiff * ydiff);
}
//check targetTouches as well
var getXY = function(ev) {
var x = ev.pageX, y = ev.pageY;
if(x == undefined) x = ev.originalEvent.pageX; //firefox
if(y == undefined) y = ev.originalEvent.pageY;
if (ev.originalEvent.targetTouches
&& ev.originalEvent.targetTouches[0]) {
x = ev.originalEvent.targetTouches[0].pageX;
y = ev.originalEvent.targetTouches[0].pageY;
}
else if (ev.originalEvent.changedTouches
&& ev.originalEvent.changedTouches[0]) {
x = ev.originalEvent.changedTouches[0].pageX;
y = ev.originalEvent.changedTouches[0].pageY;
}
return [x,y];
};
//for a given screen (x,y) displacement return model displacement
var screenXY2model = function(x,y) {
var dx = x/WIDTH;
var dy = y/HEIGHT;
var zpos = rotationGroup.position.z;
var q = rotationGroup.quaternion;
var t = new $3Dmol.Vector3(0,0,zpos);
projector.projectVector(t, camera);
t.x += dx*2;
t.y -= dy*2;
projector.unprojectVector(t, camera);
t.z = 0;
t.applyQuaternion(q);
return t;
}
//for grid viewers, return true if point is in this viewer
var isInViewer = function(x,y) {
var WIDTH = container.width();
var HEIGHT = container.height();
if(viewers != undefined && !control_all){
var width = WIDTH/cols;
var height = HEIGHT/rows;
var offset = $('canvas',container).offset();
var relx = (x - offset.left)
var rely = (y - offset.top)
var r = rows-Math.floor(rely/height)-1;
var c= Math.floor(relx/width);
if(r != row || c != col)
return false;
}
return true;
}
// this event is bound to the body element, not the container,
// so no need to put it inside initContainer()
$('body').bind('mouseup touchend', function(ev) {
// handle selection
if(isDragging && scene) { //saw mousedown, haven't moved
var xy = getXY(ev);
var x = xy[0];
var y = xy[1];
if(x == mouseStartX && y == mouseStartY) {
var offset = $('canvas',container).offset();
var mouseX = ((x - offset.left) / WIDTH) * 2 - 1;
var mouseY = -((y - offset.top) / HEIGHT) * 2 + 1;
handleClickSelection(mouseX, mouseY, ev, container);
}
}
isDragging = false;
});
//if the user has specify zoom limits, readjust to fit within them
//also, make sure we don't go past CAMERA_Z
var adjustZoomToLimits = function(z) {
//a lower limit of 0 is at CAMERA_Z
if(config.lowerZoomLimit && config.lowerZoomLimit > 0) {
var lower = CAMERA_Z-config.lowerZoomLimit;
if(z > lower) z = lower;
}
if(config.upperZoomLimit && config.upperZoomLimit > 0) {
var upper = CAMERA_Z-config.upperZoomLimit;
if(z < upper) z = upper;
}
if(z > CAMERA_Z) {
z = CAMERA_Z*0.999; //avoid getting stuck
}
return z;
};
/**
* Set lower and upper limit stops for zoom.
*
* @function $3Dmol.GLViewer#setZoomLimits
* @param {lower} - limit on zoom in (positive number). Default 0.
* @param {upper} - limit on zoom out (positive number). Default infinite.
* @example
$.get("data/set1_122_complex.mol2", function(moldata) {
var m = viewer.addModel(moldata);
viewer.setStyle({stick:{colorscheme:"Jmol"}});
viewer.setZoomLimits(100,200);
viewer.zoomTo();
viewer.zoom(10); //will not zoom all the way
viewer.render();
});
*/
this.setZoomLimits = function(lower, upper) {
if(typeof(lower) !== 'undefined') config.lowerZoomLimit = lower;
if(upper) config.upperZoomLimit = upper;
rotationGroup.position.z = adjustZoomToLimits(rotationGroup.position.z);
show();
};
var mouseButton;
var _handleMouseDown = this._handleMouseDown = function(ev) {
ev.preventDefault();
if (!scene)
return;
var xy = getXY(ev);
var x = xy[0];
var y = xy[1];
if (x === undefined)
return;
isDragging = true;
clickedAtom = null;
mouseButton = ev.which;
mouseStartX = x;
mouseStartY = y;
touchDistanceStart = 0;
if (ev.originalEvent.targetTouches
&& ev.originalEvent.targetTouches.length == 2) {
touchDistanceStart = calcTouchDistance(ev);
}
cq = rotationGroup.quaternion;
cz = rotationGroup.position.z;
currentModelPos = modelGroup.position.clone();
cslabNear = slabNear;
cslabFar = slabFar;
};
var _handleMouseScroll = this._handleMouseScroll = function(ev) { // Zoom
ev.preventDefault();
if (!scene)
return;
var xy = getXY(ev);
var x = xy[0];
var y = xy[1];
if (x === undefined)
return;
if(!isInViewer(x,y)) {
return;
}
var scaleFactor = (CAMERA_Z - rotationGroup.position.z) * 0.85;
var mult = 1.0;
if(ev.originalEvent.ctrlKey) {
mult = -1.0; //this is a pinch event turned into a wheel event (or they're just holding down the ctrl)
}
if (ev.originalEvent.detail) {
rotationGroup.position.z += mult * scaleFactor
* ev.originalEvent.detail / 10;
} else if (ev.originalEvent.wheelDelta) {
rotationGroup.position.z -= mult * scaleFactor
* ev.originalEvent.wheelDelta / 400;
}
rotationGroup.position.z = adjustZoomToLimits(rotationGroup.position.z);
show();
};
/**
* Return image URI of viewer contents (base64 encoded).
* @function $3Dmol.GLViewer#pngURI
*
*/
this.pngURI = function() {
return this.getCanvas().toDataURL('image/png');
}
/**
* Return underlying canvas element.
*/
this.getCanvas = function() {
return glDOM.get(0);
}
/**
* Set the duration of the hover delay
*
* @function $3Dmol.GLViewer#setHoverDuration
* @param {number}
* [hoverDuration] - an optional parameter that denotes
* the duration of the hover delay (in milliseconds) before the hover action is called
*
*/
this.setHoverDuration = function(duration) {
hoverDuration = duration;
}
var hoverTimeout;
var _handleMouseMove = this._handleMouseMove = function(ev) { // touchmove
WIDTH = container.width();
HEIGHT = container.height();
clearTimeout(hoverTimeout);
var offset = $('canvas',container).offset();
var mouseX = ((getXY(ev)[0] - offset.left) / WIDTH) * 2 - 1;
var mouseY = -((getXY(ev)[1] - offset.top) / HEIGHT) * 2 + 1;
//hover timeout
if(current_hover !== null)
handleHoverContinue(mouseX,mouseY,ev);
hoverTimeout=setTimeout(
function(){
handleHoverSelection(mouseX,mouseY,ev);
}
,hoverDuration);
ev.preventDefault();
if (!scene)
return;
if (!isDragging)
return;
var mode = 0;
var xy = getXY(ev);
var x = xy[0];
var y = xy[1];
if (x === undefined)
return;
if(!isInViewer(x,y)) {
return;
}
var dx = (x - mouseStartX) / WIDTH;
var dy = (y - mouseStartY) / HEIGHT;
// check for pinch
if (touchDistanceStart != 0
&& ev.originalEvent.targetTouches
&& ev.originalEvent.targetTouches.length == 2) {
var newdist = calcTouchDistance(ev);
// change to zoom
mode = 2;
dy = (newdist - touchDistanceStart) * 2
/ (WIDTH + HEIGHT);
console.log("pinch "+touchDistanceStart+" dy "+dy);
} else if (ev.originalEvent.targetTouches
&& ev.originalEvent.targetTouches.length == 3) {
// translate
mode = 1;
}
var xyRatio = renderer.getXYRatio();
var ratioX = xyRatio[0];
var ratioY = xyRatio[1];
dx*=ratioX;
dy*=ratioY;
var r = Math.sqrt(dx * dx + dy * dy);
var scaleFactor;
if (mode == 3
|| (mouseButton == 3 && ev.ctrlKey)) { // Slab
slabNear = cslabNear + dx * 100;
slabFar = cslabFar - dy * 100;
} else if (mode == 2 || mouseButton == 3
|| ev.shiftKey) { // Zoom
scaleFactor = (CAMERA_Z - rotationGroup.position.z) * 0.85;
if (scaleFactor < 80)
scaleFactor = 80;
rotationGroup.position.z = cz + dy * scaleFactor;
rotationGroup.position.z = adjustZoomToLimits(rotationGroup.position.z);
} else if (mode == 1 || mouseButton == 2
|| ev.ctrlKey) { // Translate
var t = screenXY2model(ratioX*(x-mouseStartX), ratioY*(y-mouseStartY));
modelGroup.position.addVectors(currentModelPos,t);
} else if ((mode === 0 || mouseButton == 1)
&& r !== 0) { // Rotate
var rs = Math.sin(r * Math.PI) / r;
dq.x = Math.cos(r * Math.PI);
dq.y = 0;
dq.z = rs * dx;
dq.w = -rs * dy;
rotationGroup.quaternion = new $3Dmol.Quaternion(
1, 0, 0, 0);
rotationGroup.quaternion.multiply(dq);
rotationGroup.quaternion.multiply(cq);
}
show();
};
var initContainer = function(element) {
container = element;
WIDTH = container.width();
HEIGHT = container.height();
ASPECT = renderer.getAspect(WIDTH,HEIGHT);
renderer.setSize(WIDTH, HEIGHT);
container.append(renderer.domElement);
glDOM = $(renderer.domElement);
if (!nomouse) {
// user can request that the mouse handlers not be installed
glDOM.bind('mousedown touchstart', _handleMouseDown);
glDOM.bind('DOMMouseScroll mousewheel', _handleMouseScroll);
glDOM.bind('mousemove touchmove', _handleMouseMove);
glDOM.bind("contextmenu", function(ev) {
ev.preventDefault();
});
}
};
initContainer(container);
// public methods
/**
* Change the viewer's container element
* Also useful if the original container element was removed from the DOM.
*
* @function $3Dmol.GLViewer#setContainer
*
* @param {Object | string} element
* Either HTML element or string identifier. Defaults to the element used to initialize the viewer.
*/
this.setContainer = function(element) {
if($.type(element) === "string")
element = $("#"+element);
if(!element) {
element = container
};
initContainer(element);
return this;
};
/**
* Set the background color (default white)
*
* @function $3Dmol.GLViewer#setBackgroundColor
* @param {number}
* hex Hexcode specified background color, or standard color spec
* @param {number}
* a Alpha level (default 1.0)
*
* @example
*
* viewer.setBackgroundColor(0x000000);
*
*/
this.setBackgroundColor = function(hex, a) {
if(typeof(a) == "undefined") {
a = 1.0;
}
else if(a < 0 || a > 1.0) {
a = 1.0;
}
var c = $3Dmol.CC.color(hex);
scene.fog.color = c;
bgColor = c.getHex();
renderer.setClearColorHex(c.getHex(), a);
show();
return this;
};
/**
* Set view projection scheme. Either orthographic or perspective.
* Default is perspective. Orthographic can also be enabled on viewer creation
* by setting orthographic to true in the config object.
*
* @function $3Dmol.GLViewer#setProjection
*
* @example
viewer.setViewStyle({style:"outline"});
$.get('data/1fas.pqr', function(data){
viewer.addModel(data, "pqr");
$.get("data/1fas.cube",function(volumedata){
viewer.addSurface($3Dmol.SurfaceType.VDW, {opacity:0.85,voldata: new $3Dmol.VolumeData(volumedata, "cube"), volscheme: new $3Dmol.Gradient.RWB(-10,10)},{});
});
viewer.zoomTo();
viewer.setProjection("orthographic");
viewer.render(callback);
});
*
*/
this.setProjection = function(proj) {
camera.ortho = (proj === "orthographic");
setSlabAndFog();
};
/**
* Set global view styles.
* @function $3Dmol.GLViewer#setViewStyle
*
* @example
* viewer.setViewStyle({style:"outline"});
$.get('data/1fas.pqr', function(data){
viewer.addModel(data, "pqr");
$.get("data/1fas.cube",function(volumedata){
viewer.addSurface($3Dmol.SurfaceType.VDW, {opacity:0.85,voldata: new $3Dmol.VolumeData(volumedata, "cube"), volscheme: new $3Dmol.Gradient.RWB(-10,10)},{});
});
viewer.zoomTo();
viewer.render(callback);
});
*
*/
this.setViewStyle = function(parameters) {
if (parameters["style"] === "outline") {
var params = {};
if(parameters.color) params.color = $3Dmol.CC.color(parameters.color);
if(parameters.width) params.width = parameters.width;
renderer.enableOutline(params);
} else {
renderer.disableOutline();
}
return this;
}
if(config.style) { //enable setting style in constructor
this.setViewStyle(config);
}
/**
* Set viewer width
*
* @function $3Dmol.GLViewer#setWidth
* @param {number}
* w Width in pixels
*/
this.setWidth = function(w) {
WIDTH = w || WIDTH;
renderer.setSize(WIDTH, HEIGHT);
return this;
};
/**
* Set viewer height
*
* @function $3Dmol.GLViewer#setHeight
* @param {number}
* h Height in pixels
*/
this.setHeight = function(h) {
HEIGHT = h || HEIGHT;
renderer.setSize(WIDTH, HEIGHT);
return this;
};
/**
* Resize viewer according to containing HTML element's dimensions
*
* @function $3Dmol.GLViewer#resize
*/
this.resize = function() {
WIDTH = container.width();
HEIGHT = container.height();
ASPECT = renderer.getAspect(WIDTH,HEIGHT);
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = ASPECT;
camera.updateProjectionMatrix();
show();
return this;
};
$(window).resize(this.resize);
/**
* Return specified model
*
* @function $3Dmol.GLViewer#getModel
* @param {number}
* [id=last model id] - Retrieve model with specified id
* @default Returns last model added to viewer or null if there are no models
* @return {GLModel}
*
* @example // Retrieve reference to first GLModel added var m =
* $3Dmol.download("pdb:1UBQ",viewer,{},function(m1){
$3Dmol.download("pdb:1UBI", viewer,{}, function(m2) {
viewer.zoomTo();
m1.setStyle({cartoon: {color:'green'}});
//could use m2 here as well
viewer.getModel().setStyle({cartoon: {color:'blue'}});
viewer.render();
})
});
*/
this.getModel = function(id) {
if(!(id in models)) {
if(models.length == 0)
return null;
else
return models[models.length-1]; //get last model if no (or invalid) id specified
}
return models[id];
};
/**
* Rotate scene by angle degrees around axis
*
* @function $3Dmol.GLViewer#rotate
* @param {number}
* [angle] - Angle, in degrees, to rotate by.
* @param {string}
* [axis] - Axis ("x", "y", or "z") to rotate around.
* Default "y"
* @param {number}
* [animationDuration] - an optional parameter that denotes
* the duration of the rotation animation. Default 0 (no animation)
* @param {boolean} [fixedPath] - if true animation is constrained to
* requested motion, overriding updates that happen during the animation *
* @example $3Dmol.download('cid:4000', viewer, {}, function() {
viewer.setStyle({stick:{}});
viewer.zoomTo();
viewer.rotate(90,'y',1);
viewer.render(callback);
});
*
*/
this.rotate = function(angle, axis, animationDuration, fixedPath) {
animationDuration = animationDuration!==undefined ? animationDuration : 0;
if (typeof (axis) === "undefined") {
axis = "y";
}
if(axis == "x"){
axis = {x:1,y:0,z:0}
}if(axis =="y"){
axis = {x:0,y:1,z:0}
}if(axis =="z"){
axis = {x:0,y:0,z:1}
}
var qFromAngle = function(rangle) {
var s = Math.sin(rangle / 2.0);
var c = Math.cos(rangle / 2.0);
var i = 0, j = 0, k = 0;
i = axis.x * s
j = axis.y * s
k = axis.z * s
return new $3Dmol.Quaternion(i, j, k, c).normalize();
}
var wait_time = 20;
var rangle = Math.PI * angle / 180.0;
var q = qFromAngle(rangle);
if(animationDuration ){
var final = new $3Dmol.Quaternion().copy(rotationGroup.quaternion).multiply(q);//final
animateMotion(animationDuration,fixedPath,
modelGroup.position,
rotationGroup.position.z,
final,
lookingAt);
} else { //not animated
rotationGroup.quaternion.multiply(q);
show();
}
return this;
};
this.surfacesFinished= function() {
for(var key in surfaces){
if(!surfaces[key][0].done){
return false;
}
}
return true;
};
/** Returns an array representing the current viewpoint.
* Translation, zoom, and rotation quaternion.
* @function $3Dmol.GLViewer#getView
* @returns {Array.<number>} [ pos.x, pos.y, pos.z, rotationGroup.position.z, q.x, q.y, q.z, q.w ]
* */
this.getView = function() {
if (!modelGroup)
return [ 0, 0, 0, 0, 0, 0, 0, 1 ];
var pos = modelGroup.position;
var q = rotationGroup.quaternion;
return [ pos.x, pos.y, pos.z, rotationGroup.position.z, q.x, q.y,
q.z, q.w ];
};
/** Sets the view to the specified translation, zoom, and rotation.
*
* @function $3Dmol.GLViewer#setView
* @param {Array.<number>} arg Array formatted identically to the return value of getView */
this.setView = function(arg, nolink) {
if (arg === undefined
|| !(arg instanceof Array || arg.length !== 8))
return this;
if (!modelGroup || !rotationGroup)
return this;
modelGroup.position.x = arg[0];
modelGroup.position.y = arg[1];
modelGroup.position.z = arg[2];
rotationGroup.position.z = arg[3];
rotationGroup.quaternion.x = arg[4];
rotationGroup.quaternion.y = arg[5];
rotationGroup.quaternion.z = arg[6];
rotationGroup.quaternion.w = arg[7];
if(typeof(arg[8]) != "undefined") {
rotationGroup.position.x = arg[8];
rotationGroup.position.y = arg[9];
}
show(nolink);