/
GLViewer.ts
4897 lines (4344 loc) · 173 KB
/
GLViewer.ts
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
import { Geometry, Renderer, Camera, Raycaster, Projector, Light, Fog, Scene, Coloring, FrontSide, Material } from "./WebGL";
import { Vector3, Matrix4, Matrix3, Quaternion, XYZ } from "./WebGL/math";
import { MeshLambertMaterial, Object3D, Mesh, LineBasicMaterial, Line } from "./WebGL";
import { elementColors, CC, ColorSpec, ColorschemeSpec } from "./colors";
import { extend, getExtent, makeFunction, getPropertyRange, isEmptyObject, adjustVolumeStyle, mergeGeos, PausableTimer, getColorFromStyle, getElement } from "./utilities";
import { getGradient, Gradient } from "./Gradient";
import { AtomStyleSpec, GLModel, LineStyleSpec } from "./GLModel";
import { Label, LabelSpec } from "./Label";
import { ArrowSpec, BoxSpec, CurveSpec, CustomShapeSpec, CylinderSpec, GLShape, IsoSurfaceSpec, LineSpec, ShapeSpec, SphereSpec, splitMesh } from "./GLShape";
import { VolumeData } from "./VolumeData";
import { ProteinSurface, SurfaceType, syncSurface } from "./ProteinSurface4";
import { GLVolumetricRender, VolumetricRendererSpec } from "./VolumetricRender";
import { AtomSelectionSpec, AtomSpec } from "./specs";
import { decode, toRGBA8, encode } from 'upng-js'
/**
* WebGL-based 3Dmol.js viewer
* Note: The preferred method of instantiating a GLViewer is through {@link createViewer}
*
* @class
*/
export class GLViewer {
// private class variables
private static numWorkers = 4; // number of threads for surface generation
private static maxVolume = 64000; // how much to break up surface calculations
private callback: any;
private defaultcolors: any;
private config: any;
private nomouse = false;
private bgColor: any;
private camerax: number;
private _viewer: GLViewer;
private glDOM: HTMLCanvasElement | null = null;
private models: GLModel[] = []; // atomistic molecular models
private surfaces: any = {};
private shapes = []; // Generic shapes
private labels: Label[] = [];
private clickables = []; //things you can click on
private hoverables = []; //things you can hover over
private contextMenuEnabledAtoms = []; // atoms with context menu
private current_hover: any = null;
private hoverDuration = 500;
private viewer_frame = 0;
private WIDTH: number;
private HEIGHT: number;
private viewChangeCallback: any = null;
private stateChangeCallback: any = null;
private NEAR = 1;
private FAR = 800;
private CAMERA_Z = 150;
private fov = 20;
private linkedViewers = [];
private renderer: any = null;
private row: number;
private col: number;
private cols: number;
private rows: number;
private viewers: any;
private control_all = false;
private ASPECT: any;
private camera: Camera;
private lookingAt: Vector3;
private raycaster: Raycaster;
private projector: Projector;
private scene: any = null;
private rotationGroup: any = null; // which contains modelGroup
private modelGroup: any = null;
private fogStart = 0.4;
private slabNear = -50; // relative to the center of rotationGroup
private slabFar = 50;
public container: HTMLElement | null;
static readonly surfaceTypeMap = {
"VDW": SurfaceType.VDW,
"MS": SurfaceType.MS,
"SAS": SurfaceType.SAS,
"SES": SurfaceType.SES
};
private cq = new Quaternion(0, 0, 0, 1);
private dq = new Quaternion(0, 0, 0, 1);
private animated = 0;
private animationTimers = new Set<PausableTimer>();
private isDragging = false;
private mouseStartX = 0;
private mouseStartY = 0;
private touchDistanceStart = 0;
private touchHold = false;
private currentModelPos = 0;
private cz = 0;
private cslabNear = 0;
private cslabFar = 0;
private mouseButton: any;
private hoverTimeout: any;
private divwatcher: any;
private spinInterval: any;
//reimplement jquery getwidth/height
private getRect() {
let div = this.container;
let rect = div.getBoundingClientRect();
if (rect.width == 0 && rect.height == 0 && div.style.display === 'none') {
let oldpos = div.style.position;
let oldvis = div.style.visibility;
div.style.display = 'block';
div.style.visibility = 'hidden';
div.style.position = 'absolute';
rect = div.getBoundingClientRect();
div.style.display = 'none';
div.style.visibility = oldvis;
div.style.position = oldpos;
}
return rect;
};
private getWidth() {
return this.getRect().width;
};
private getHeight() {
return this.getRect().height;
};
private setupRenderer() {
this.renderer = new Renderer({
antialias: this.config.antialias,
preserveDrawingBuffer: true, //so we can export images
premultipliedAlpha: false,/* more traditional compositing with background */
id: this.config.id,
row: this.config.row,
col: this.config.col,
rows: this.config.rows,
cols: this.config.cols,
canvas: this.config.canvas,
//cannot initialize with zero size
containerWidth: this.WIDTH || 1,
containerHeight: this.HEIGHT || 1,
});
this.renderer.domElement.style.width = "100%";
this.renderer.domElement.style.height = "100%";
this.renderer.domElement.style.padding = "0";
this.renderer.domElement.style.position = "absolute"; //TODO: get rid of this
this.renderer.domElement.style.top = "0px";
this.renderer.domElement.style.left = "0px";
this.renderer.domElement.style.zIndex = "0";
}
private initializeScene() {
this.scene = new Scene();
this.scene.fog = new Fog(this.bgColor, 100, 200);
this.modelGroup = new Object3D();
this.rotationGroup = new Object3D();
this.rotationGroup.useQuaternion = true;
this.rotationGroup.quaternion = new Quaternion(0, 0, 0, 1);
this.rotationGroup.add(this.modelGroup);
this.scene.add(this.rotationGroup);
// setup lights
var directionalLight = new Light(0xFFFFFF);
directionalLight.position = new Vector3(0.2, 0.2, 1)
.normalize();
directionalLight.intensity = 1.0;
this.scene.add(directionalLight);
};
private initContainer(element) {
this.container = element;
this.WIDTH = this.getWidth();
this.HEIGHT = this.getHeight();
this.ASPECT = this.renderer.getAspect(this.WIDTH, this.HEIGHT);
this.renderer.setSize(this.WIDTH, this.HEIGHT);
this.container.append(this.renderer.domElement);
this.glDOM = this.renderer.domElement;
if (!this.nomouse) {
// user can request that the mouse handlers not be installed
this.glDOM.addEventListener('mousedown', this._handleMouseDown.bind(this), { passive: false });
this.glDOM.addEventListener('touchstart', this._handleMouseDown.bind(this), { passive: false });
this.glDOM.addEventListener('wheel', this._handleMouseScroll.bind(this), { passive: false });
this.glDOM.addEventListener('mousemove', this._handleMouseMove.bind(this), { passive: false });
this.glDOM.addEventListener('touchmove', this._handleMouseMove.bind(this), { passive: false });
this.glDOM.addEventListener("contextmenu", this._handleContextMenu.bind(this), { passive: false });
}
};
private decAnim() {
//decrement the number of animations currently
this.animated--;
if (this.animated < 0) this.animated = 0;
};
private incAnim() {
this.animated++;
};
private nextSurfID() {
//compute the next highest surface id directly from surfaces
//this is necessary to support linking of model data
var max = 0;
for (let i in this.surfaces) { // this is an object with possible holes
if (!this.surfaces.hasOwnProperty(i)) continue;
var val = parseInt(i);
if (!isNaN(val)) {
if (val > max)
max = val;
}
}
return max + 1;
};
private setSlabAndFog() {
let center = this.camera.position.z - this.rotationGroup.position.z;
if (center < 1)
center = 1;
this.camera.near = center + this.slabNear;
if (this.camera.near < 1)
this.camera.near = 1;
this.camera.far = center + this.slabFar;
if (this.camera.near + 1 > this.camera.far)
this.camera.far = this.camera.near + 1;
this.camera.fov = this.fov;
this.camera.right = center * Math.tan(Math.PI / 180 * this.fov);
this.camera.left = -this.camera.right;
this.camera.top = this.camera.right / this.ASPECT;
this.camera.bottom = -this.camera.top;
this.camera.updateProjectionMatrix();
this.scene.fog.near = this.camera.near + this.fogStart * (this.camera.far - this.camera.near);
// if (scene.fog.near > center) scene.fog.near = center;
this.scene.fog.far = this.camera.far;
if (this.config.disableFog) {
this.scene.fog.near = this.scene.fog.far;
}
};
// display scene
//if nolink is set/true, don't propagate changes to linked viewers
private show(nolink?) {
this.renderer.setViewport();
if (!this.scene)
return;
// var time = new Date();
this.setSlabAndFog();
this.renderer.render(this.scene, this.camera);
// console.log("rendered in " + (+new Date() - time) + "ms");
//have any scene change trigger a callback
if (this.viewChangeCallback) this.viewChangeCallback(this._viewer.getView());
if (!nolink && this.linkedViewers.length > 0) {
var view = this._viewer.getView();
for (var i = 0; i < this.linkedViewers.length; i++) {
var other = this.linkedViewers[i];
other.setView(view, true);
}
}
};
//regenerate the list of clickables
//also updates hoverables
private updateClickables() {
this.clickables.splice(0, this.clickables.length);
this.hoverables.splice(0, this.hoverables.length);
this.contextMenuEnabledAtoms.splice(0, this.contextMenuEnabledAtoms.length);
for (let i = 0, il = this.models.length; i < il; i++) {
let model = this.models[i];
if (model) {
let atoms = model.selectedAtoms({
clickable: true
});
let hoverable_atoms = model.selectedAtoms({
hoverable: true
});
let contextMenuEnabled_atom = model.selectedAtoms({ contextMenuEnabled: true });
// Array.prototype.push.apply(hoverables,hoverable_atoms);
for (let n = 0; n < hoverable_atoms.length; n++) {
this.hoverables.push(hoverable_atoms[n]);
}
// Array.prototype.push.apply(clickables, atoms); //add atoms into clickables
for (let m = 0; m < atoms.length; m++) {
this.clickables.push(atoms[m]);
}
// add atoms into contextMenuEnabledAtoms
for (let m = 0; m < contextMenuEnabled_atom.length; m++) {
this.contextMenuEnabledAtoms.push(contextMenuEnabled_atom[m]);
}
}
}
for (let i = 0, il = this.shapes.length; i < il; i++) {
let shape = this.shapes[i];
if (shape && shape.clickable) {
this.clickables.push(shape);
}
if (shape && shape.hoverable) {
this.hoverables.push(shape);
}
}
};
// Checks for selection intersects on mousedown
private handleClickSelection(mouseX: number, mouseY: number, event) {
let intersects = this.targetedObjects(mouseX, mouseY, this.clickables);
// console.log('handleClickSelection', mouseX, mouseY, intersects);
if (intersects.length) {
var selected = intersects[0].clickable;
if (selected.callback !== undefined) {
if (typeof (selected.callback) != "function") {
selected.callback = makeFunction(selected.callback);
}
if (typeof (selected.callback) === "function") {
selected.callback(selected, this._viewer, event, this.container);
}
}
}
};
//return offset of container
private canvasOffset() {
let canvas = this.glDOM;
let rect = canvas.getBoundingClientRect();
let doc = canvas.ownerDocument;
let docElem = doc.documentElement;
let win = doc.defaultView;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
};
//set current_hover to sel (which can be null), calling appropraite callbacks
private setHover(selected, event?) {
if (this.current_hover == selected) return;
if (this.current_hover) {
if (typeof (this.current_hover.unhover_callback) != "function") {
this.current_hover.unhover_callback = makeFunction(this.current_hover.unhover_callback);
}
this.current_hover.unhover_callback(this.current_hover, this._viewer, event, this.container);
}
this.current_hover = selected;
if (selected && selected.hover_callback !== undefined) {
if (typeof (selected.hover_callback) != "function") {
selected.hover_callback = makeFunction(selected.hover_callback);
}
if (typeof (selected.hover_callback) === "function") {
selected.hover_callback(selected, this._viewer, event, this.container);
}
}
};
//checks for selection intersects on hover
private handleHoverSelection(mouseX, mouseY) {
if (this.hoverables.length == 0) return;
let intersects = this.targetedObjects(mouseX, mouseY, this.hoverables);
if (intersects.length) {
var selected = intersects[0].clickable;
this.setHover(selected);
this.current_hover = selected;
}
else {
this.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
private handleHoverContinue(mouseX: number, mouseY: number) {
let intersects = this.targetedObjects(mouseX, mouseY, this.hoverables);
if (intersects.length == 0 || intersects[0] === undefined) {
this.setHover(null);
}
if (intersects[0] !== undefined && intersects[0].clickable !== this.current_hover) {
this.setHover(null);
}
};
private calcTouchDistance(ev) { // distance between first two
// fingers
var xdiff = ev.targetTouches[0].pageX -
ev.targetTouches[1].pageX;
var ydiff = ev.targetTouches[0].pageY -
ev.targetTouches[1].pageY;
return Math.sqrt(xdiff * xdiff + ydiff * ydiff);
};
//check targetTouches as well
private getX(ev) {
var x = ev.pageX;
if (x == undefined) x = ev.pageX; //firefox
if (ev.targetTouches &&
ev.targetTouches[0]) {
x = ev.targetTouches[0].pageX;
}
else if (ev.changedTouches &&
ev.changedTouches[0]) {
x = ev.changedTouches[0].pageX;
}
return x;
};
private getY(ev) {
var y = ev.pageY;
if (y == undefined) y = ev.pageY;
if (ev.targetTouches &&
ev.targetTouches[0]) {
y = ev.targetTouches[0].pageY;
}
else if (ev.changedTouches &&
ev.changedTouches[0]) {
y = ev.changedTouches[0].pageY;
}
return y;
};
//for grid viewers, return true if point is in this viewer
private isInViewer(x: number, y: number) {
if (this.viewers != undefined && !this.control_all) {
var width = this.WIDTH / this.cols;
var height = this.HEIGHT / this.rows;
var offset = this.canvasOffset();
var relx = (x - offset.left);
var rely = (y - offset.top);
var r = this.rows - Math.floor(rely / height) - 1;
var c = Math.floor(relx / width);
if (r != this.row || c != this.col)
return false;
}
return true;
};
//if the user has specify zoom limits, readjust to fit within them
//also, make sure we don't go past CAMERA_Z
private adjustZoomToLimits(z: number) {
//a lower limit of 0 is at CAMERA_Z
if (this.config.lowerZoomLimit && this.config.lowerZoomLimit > 0) {
let lower = this.CAMERA_Z - this.config.lowerZoomLimit;
if (z > lower) z = lower;
}
if (this.config.upperZoomLimit && this.config.upperZoomLimit > 0) {
let upper = this.CAMERA_Z - this.config.upperZoomLimit;
if (z < upper) z = upper;
}
if (z > this.CAMERA_Z) {
z = this.CAMERA_Z * 0.999; //avoid getting stuck
}
return z;
};
//interpolate between two normalized quaternions (t between 0 and 1)
//https://en.wikipedia.org/wiki/Slerp
private static slerp(v0: Quaternion, v1: Quaternion, t: number) {
// Compute the cosine of the angle between the two vectors.
//dot product
if (t == 1) return v1.clone();
else if (t == 0) return v0.clone();
let dot = v0.x * v1.x + v0.y * v1.y + v0.z * v1.z + v0.w * v1.w;
if (dot > 0.9995) {
// If the inputs are too close for comfort, linearly interpolate
// and normalize the result.
let result = new Quaternion(
v0.x + t * (v1.x - v0.x),
v0.y + t * (v1.y - v0.y),
v0.z + t * (v1.z - v0.z),
v0.w + t * (v1.w - v0.w));
result.normalize();
return result;
}
// If the dot product is negative, the quaternions
// have opposite handed-ness and slerp won't take
// the shorted path. Fix by reversing one quaternion.
if (dot < 0.0) {
v1 = v1.clone().multiplyScalar(-1);
dot = -dot;
}
if (dot > 1) dot = 1.0;
else if (dot < -1) dot = -1.0;
var theta_0 = Math.acos(dot); // theta_0 = angle between input vectors
var theta = theta_0 * t; // theta = angle between v0 and result
var v2 = v1.clone();
v2.sub(v0.clone().multiplyScalar(dot));
v2.normalize(); // { v0, v2 } is now an orthonormal basis
var c = Math.cos(theta);
var s = Math.sin(theta);
var ret = new Quaternion(
v0.x * c + v2.x * s,
v0.y * c + v2.y * s,
v0.z * c + v2.z * s,
v0.w * c + v2.w * s
);
ret.normalize();
return ret;
};
/* @param {Object} element HTML element within which to create viewer
* @param {ViewerSpec} config Object containing optional configuration for the viewer
*/
constructor(element, c: ViewerSpec = {}) {
// set variables
this.config = c;
this.callback = this.config.callback;
this.defaultcolors = this.config.defaultcolors;
if (!this.defaultcolors)
this.defaultcolors = elementColors.defaultColors;
this.nomouse = this.config.nomouse;
this.bgColor = 0;
this.config.backgroundColor = this.config.backgroundColor || "#ffffff";
if (typeof (this.config.backgroundColor) != 'undefined') {
this.bgColor = CC.color(this.config.backgroundColor).getHex();
}
this.config.backgroundAlpha = this.config.backgroundAlpha == undefined ? 1.0 : this.config.backgroundAlpha;
this.camerax = 0;
if (typeof (this.config.camerax) != 'undefined') {
this.camerax = parseFloat(this.config.camerax);
}
this._viewer = this;
this.container = element; //we expect container to be HTMLElement
if (this.config.hoverDuration != undefined) {
this.hoverDuration = this.config.hoverDuration;
}
if (this.config.antialias === undefined) this.config.antialias = true;
if (this.config.cartoonQuality === undefined) this.config.cartoonQuality = 10;
this.WIDTH = this.getWidth();
this.HEIGHT = this.getHeight();
this.setupRenderer();
this.row = this.config.row;
this.col = this.config.col;
this.cols = this.config.cols;
this.rows = this.config.rows;
this.viewers = this.config.viewers;
this.control_all = this.config.control_all;
this.ASPECT = this.renderer.getAspect(this.WIDTH, this.HEIGHT);
this.camera = new Camera(this.fov, this.ASPECT, this.NEAR, this.FAR, this.config.orthographic);
this.camera.position = new Vector3(this.camerax, 0, this.CAMERA_Z);
this.lookingAt = new Vector3();
this.camera.lookAt(this.lookingAt);
this.raycaster = new Raycaster(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
this.projector = new Projector();
this.initializeScene();
this.renderer.setClearColorHex(this.bgColor, this.config.backgroundAlpha);
this.scene.fog.color = CC.color(this.bgColor);
// this event is bound to the body element, not the container,
// so no need to put it inside initContainer()
document.body.addEventListener('mouseup', this._handleMouseUp.bind(this));
document.body.addEventListener('touchend', this._handleMouseUp.bind(this));
this.initContainer(this.container);
if (this.config.style) { //enable setting style in constructor
this.setViewStyle(this.config);
}
window.addEventListener("resize", this.resize.bind(this));
if (typeof (window.ResizeObserver) !== "undefined") {
this.divwatcher = new window.ResizeObserver(this.resize.bind(this));
this.divwatcher.observe(this.container);
}
try {
if (typeof (this.callback) === "function")
this.callback(this);
} catch (e) {
// errors in callback shouldn't invalidate the viewer
console.log("error with glviewer callback: " + e);
}
};
/**
* Return a list of objects that intersect that at the specified viewer position.
*
* @param x - x position in screen coordinates
* @param y - y position in screen coordinates
* @param {Object[]} - list of objects or selection object specifying what object to check for targeting
*/
public targetedObjects(x: number, y: number, objects) {
var mouse = {
x: x,
y: y,
z: -1.0
};
if (!Array.isArray(objects)) { //assume selection object
objects = this.selectedAtoms(objects);
}
if (objects.length == 0) return [];
this.raycaster.setFromCamera(mouse, this.camera);
return this.raycaster.intersectObjects(this.modelGroup, objects);
};
/** Convert model coordinates to screen coordinates.
* @param {object | list} - an object or list of objects with x,y,z attributes (e.g. an atom)
* @return {object | list} - and object or list of {x: screenX, y: screenY}
*/
public modelToScreen(coords) {
let returnsingle = false;
if (!Array.isArray(coords)) {
coords = [coords];
returnsingle = true;
}
let results = [];
let offset = this.canvasOffset();
coords.forEach(coord => {
let t = new Vector3(coord.x, coord.y, coord.z);
t.applyMatrix4(this.modelGroup.matrixWorld);
this.projector.projectVector(t, this.camera);
let screenX = this.WIDTH * (t.x + 1) / 2.0 + offset.left;
let screenY = -this.HEIGHT * (t.y - 1) / 2.0 + offset.top;
results.push({ x: screenX, y: screenY });
});
if (returnsingle) results = results[0];
return results;
};
/**
* For a given screen (x,y) displacement return model displacement
* @param{x} x displacement in screen coordinates
* @param{y} y displacement in screen corodinates
* @param{modelz} z coordinate in model coordinates to compute offset for, default is model axis
*/
public screenOffsetToModel(x: number, y: number, modelz?) {
var dx = x / this.WIDTH;
var dy = y / this.HEIGHT;
var zpos = (modelz === undefined ? this.rotationGroup.position.z : modelz);
var q = this.rotationGroup.quaternion;
var t = new Vector3(0, 0, zpos);
this.projector.projectVector(t, this.camera);
t.x += dx * 2;
t.y -= dy * 2;
this.projector.unprojectVector(t, this.camera);
t.z = 0;
t.applyQuaternion(q);
return t;
};
/**
* Distance from screen coordinate to model coordinate assuming screen point
* is projected to the same depth as model coordinate
* @param{screen} xy screen coordinate
* @param{model} xyz model coordinate
*/
public screenToModelDistance(screen: XYZ, model) {
let offset = this.canvasOffset();
//convert model to screen to get screen z
let mvec = new Vector3(model.x, model.y, model.z);
mvec.applyMatrix4(this.modelGroup.matrixWorld);
let m = mvec.clone();
this.projector.projectVector(mvec, this.camera);
let t = new Vector3((screen.x - offset.left) * 2 / this.WIDTH - 1, (screen.y - offset.top) * 2 / -this.HEIGHT + 1, mvec.z);
this.projector.unprojectVector(t, this.camera);
return t.distanceTo(m);
};
/**
* Set a callback to call when the view has potentially changed.
*
*/
public setViewChangeCallback(callback) {
if (typeof (callback) === 'function' || callback == null)
this.viewChangeCallback = callback;
};
/**
* Set a callback to call when the view has potentially changed.
*
*/
public setStateChangeCallback(callback) {
if (typeof (callback) === 'function' || callback == null)
this.stateChangeCallback = callback;
};
/**
* Return configuration of viewer
*/
public getConfig() {
return this.config;
};
/**
* Set the configuration object. Note that some setting may only
* have an effect at viewer creation time.
*/
public setConfig(c) {
this.config = c;
};
/**
* Return object representing internal state of
* the viewer appropriate for passing to setInternalState
*
*/
public getInternalState() {
var ret = { 'models': [], 'surfaces': [], 'shapes': [], 'labels': [] };
for (let i = 0; i < this.models.length; i++) {
if (this.models[i]) {
ret.models[i] = this.models[i].getInternalState();
}
}
//todo: labels, shapes, surfaces
return ret;
};
/**
* Overwrite internal state of the viewer with passed object
* which should come from getInternalState.
*
*/
public setInternalState(state) {
//clear out current viewer
this.clear();
//set model state
var newm = state.models;
for (let i = 0; i < newm.length; i++) {
if (newm[i]) {
this.models[i] = new GLModel(i);
this.models[i].setInternalState(newm[i]);
}
}
//todo: labels, shapes, surfaces
this.render();
};
/**
* Set lower and upper limit stops for zoom.
*
* @param {lower} - limit on zoom in (positive number). Default 0.
* @param {upper} - limit on zoom out (positive number). Default infinite.
* @example
$3Dmol.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();
});
*/
public setZoomLimits(lower, upper) {
if (typeof (lower) !== 'undefined') this.config.lowerZoomLimit = lower;
if (upper) this.config.upperZoomLimit = upper;
this.rotationGroup.position.z = this.adjustZoomToLimits(this.rotationGroup.position.z);
this.show();
};
/**
* Set camera parameters (distance to the origin and field of view)
*
* @param {parameters} - new camera parameters, with possible fields
* being fov for the field of view, z for the
* distance to the origin, and orthographic (boolean)
* for kind of projection (default false).
* @example
$3Dmol.get("data/set1_122_complex.mol2", function(data) {
var m = viewer.addModel(data);
viewer.setStyle({stick:{}});
viewer.zoomTo();
viewer.setCameraParameters({ fov: 10 , z: 300 });
viewer.render();
});
*/
public setCameraParameters(parameters) {
if (parameters.fov !== undefined) {
this.fov = parameters.fov;
this.camera.fov = this.fov;
}
if (parameters.z !== undefined) {
this.CAMERA_Z = parameters.z;
this.camera.z = this.CAMERA_Z;
}
if (parameters.orthographic !== undefined) {
this.camera.ortho = parameters.orthographic;
}
};
public _handleMouseDown(ev) {
ev.preventDefault();
if (!this.scene)
return;
var x = this.getX(ev);
var y = this.getY(ev);
if (x === undefined)
return;
this.isDragging = true;
this.mouseButton = ev.which;
this.mouseStartX = x;
this.mouseStartY = y;
this.touchHold = true;
this.touchDistanceStart = 0;
if (ev.targetTouches &&
ev.targetTouches.length == 2) {
this.touchDistanceStart = this.calcTouchDistance(ev);
}
this.cq = this.rotationGroup.quaternion.clone();
this.cz = this.rotationGroup.position.z;
this.currentModelPos = this.modelGroup.position.clone();
this.cslabNear = this.slabNear;
this.cslabFar = this.slabFar;
let self = this;
setTimeout(function () {
if (ev.targetTouches) {
if (self.touchHold == true) {
// console.log('Touch hold', x,y);
self.glDOM = self.renderer.domElement;
self.glDOM.dispatchEvent(new Event('contextmenu'));
}
else {
// console.log('Touch hold ended earlier');
}
}
}, 1000);
};
public _handleMouseUp(ev) {
// handle touch
this.touchHold = false;
// handle selection
if (this.isDragging && this.scene) { //saw mousedown, haven't moved
var x = this.getX(ev);
var y = this.getY(ev);
if (x == this.mouseStartX && y == this.mouseStartY) {
var offset = this.canvasOffset();
var mouseX = ((x - offset.left) / this.WIDTH) * 2 - 1;
var mouseY = -((y - offset.top) / this.HEIGHT) * 2 + 1;
this.handleClickSelection(mouseX, mouseY, ev);
}
}
this.isDragging = false;
}
public _handleMouseScroll(ev) { // Zoom
ev.preventDefault();
if (!this.scene)
return;
var x = this.getX(ev);
var y = this.getY(ev);
if (x === undefined)
return;
if (!this.isInViewer(x, y)) {
return;
}
var scaleFactor = (this.CAMERA_Z - this.rotationGroup.position.z) * 0.85;
var mult = 1.0;
if (ev.ctrlKey) {
mult = -1.0; //this is a pinch event turned into a wheel event (or they're just holding down the ctrl)
}
if (ev.detail) {
this.rotationGroup.position.z += mult * scaleFactor * ev.detail / 10;
} else if (ev.wheelDelta) {
this.rotationGroup.position.z -= mult * scaleFactor * ev.wheelDelta / 400;
}
this.rotationGroup.position.z = this.adjustZoomToLimits(this.rotationGroup.position.z);
this.show();
};
/**
* Return image URI of viewer contents (base64 encoded). *
*/
public pngURI() {
return this.getCanvas().toDataURL('image/png');
};
/**
* Return a promise that resolves to an animated PNG image URI of
viewer contents (base64 encoded) for nframes of viewer changes.
* @return {Promise}
*/
public apngURI(nframes: number) {
let viewer = this;
nframes = nframes ? nframes : 1;
return new Promise(function (resolve) {
let framecnt = 0;
let oldcb = viewer.viewChangeCallback;
let bufpromise = [];
let delays = [];
let lasttime = Date.now();
viewer.viewChangeCallback = function () {
delays.push(Date.now() - lasttime);
lasttime = Date.now();
bufpromise.push(new Promise(resolve => {
viewer.getCanvas().toBlob(function (blob) {
blob.arrayBuffer().then(resolve);
}, "image/png");
}));
framecnt += 1;
if (framecnt == nframes) {
viewer.viewChangeCallback = oldcb;
Promise.all(bufpromise).then((buffers) => {
//convert to apng
let rgbas = [];
//have to convert png to rgba, before creating the apng
for (let i = 0; i < buffers.length; i++) {
let img = decode(buffers[i]);
rgbas.push(toRGBA8(img)[0]);
}
let width = viewer.getCanvas().width;
let height = viewer.getCanvas().height;
let apng = encode(rgbas, width, height, 0, delays);
let blob = new Blob([apng], { type: 'image/png' });
let fr = new FileReader();
fr.onload = function (e) {
resolve(e.target.result);
};
fr.readAsDataURL(blob);
});
}
};
});
};
/**
* Return underlying canvas element.
*/
public getCanvas(): HTMLCanvasElement {
return this.glDOM;
};
/**
* Return renderer element.
*/
public getRenderer() {
return this.renderer;
};
/**
* Set the duration of the hover delay
*
* @param {number}
* [hoverDuration] - an optional parameter that denotes