/
sceneplotview3d.js
1025 lines (894 loc) · 33.5 KB
/
sceneplotview3d.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
define([
'three',
'orbitcontrols',
'draw',
'underscore'
], function(THREE, OrbitControls, draw, _) {
/** @private */
var makeLine = draw.makeLine;
/** @private */
var makeLabel = draw.makeLabel;
/**
*
* @class ScenePlotView3D
*
* Represents a three dimensional scene in THREE.js.
*
* @param {UIState} uiState shared UIState state object
* @param {THREE.renderer} renderer THREE renderer object.
* @param {Object} decViews dictionary of DecompositionViews shown in this
* scene
* @param {MultiModel} decModels MultiModel of DecompositionModels shown in
* this scene (with extra global data about them)
* @param {Node} container Div where the scene will be rendered.
* @param {Float} xView Horizontal position of the rendered scene in the
* container element.
* @param {Float} yView Vertical position of the rendered scene in the
* container element.
* @param {Float} width The width of the renderer
* @param {Float} height The height of the renderer
*
* @return {ScenePlotView3D} An instance of ScenePlotView3D.
* @constructs ScenePlotView3D
*/
function ScenePlotView3D(uiState, renderer, decViews, decModels, container,
xView, yView,
width, height) {
var scope = this;
this.UIState = uiState;
// convert to jquery object for consistency with the rest of the objects
var $container = $(container);
this.decViews = decViews;
this.decModels = decModels;
this.renderer = renderer;
/**
* Horizontal position of the scene.
* @type {Float}
*/
this.xView = xView;
/**
* Vertical position of the scene.
* @type {Float}
*/
this.yView = yView;
/**
* Width of the scene.
* @type {Float}
*/
this.width = width;
/**
* Height of the scene.
* @type {Float}
*/
this.height = height;
/**
* Axes color.
* @type {String}
* @default '#FFFFFF' (white)
*/
this.axesColor = '#FFFFFF';
/**
* Background color.
* @type {String}
* @default '#000000' (black)
*/
this.backgroundColor = '#000000';
/**
* True when changes have occured that require re-rendering of the canvas
* @type {Boolean}
*/
this.needsUpdate = true;
/**
* Array of integers indicating the index of the visible dimension at each
* axis ([x, y, z]).
* @type {Integer[]}
*/
this.visibleDimensions = _.clone(this.decViews.scatter.visibleDimensions);
// used to name the axis lines/labels in the scene
this._axisPrefix = 'emperor-axis-line-';
this._axisLabelPrefix = 'emperor-axis-label-';
//need to initialize the scene
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(this.backgroundColor);
/**
* Camera used to display the scatter scene.
* @type {THREE.OrthographicCamera}
*/
this.scatterCam = this.buildCamera('scatter');
/**
* Object used to light the scene in scatter mode,
* by default is set to a light and
* transparent color (0x99999999).
* @type {THREE.DirectionalLight}
*/
this.light = new THREE.DirectionalLight(0x999999, 2);
this.light.position.set(1, 1, 1).normalize();
this.scatterCam.add(this.light);
/**
* Camera used to display the parallel plot scene.
* @type {THREE.OrthographicCamera}
*/
this.parallelCam = this.buildCamera('parallel-plot');
// use $container.get(0) to retrieve the native DOM object
this.scatterController = this.buildCamController('scatter',
this.scatterCam,
$container.get(0));
this.parallelController = this.buildCamController('parallel-plot',
this.parallelCam,
$container.get(0));
//Swap the camera whenever the view type changes
this.UIState.registerProperty('view.viewType', function(evt) {
if (evt.newVal === 'parallel-plot') {
scope.camera = scope.parallelCam;
scope.control = scope.parallelController;
//Don't let the controller move around when its not the active camera
scope.scatterController.enabled = false;
scope.parallelController.enabled = true;
} else {
scope.camera = scope.scatterCam;
scope.control = scope.scatterController;
//Don't let the controller move around when its not the active camera
scope.scatterController.enabled = true;
scope.parallelController.enabled = false;
}
//Disable any active rotation
if (evt.newVal === 'parallel-plot')
scope.scatterController.autoRotate = false;
});
this.scene.add(this.scatterCam);
this.scene.add(this.parallelCam);
this._raycaster = new THREE.Raycaster();
this._mouse = new THREE.Vector2();
// add all the objects to the current scene
this.addDecompositionsToScene();
this.updateCameraTarget();
this.control.update();
this.scatterController.addEventListener('change', function() {
scope.needsUpdate = true;
});
this.parallelController.addEventListener('change', function() {
scope.needsUpdate = true;
});
/**
* Object with "min" and "max" attributes each of which is an array with
* the ranges that covers all of the decomposition views.
* @type {Object}
*/
this.drawAxesWithColor('#FFFFFF');
this.drawAxesLabelsWithColor('#FFFFFF');
// initialize subscribers for event callbacks
/**
* Events allowed for callbacks. DO NOT EDIT.
* @type {String[]}
*/
this.EVENTS = ['click', 'dblclick'];
/** @private */
this._subscribers = {};
for (var i = 0; i < this.EVENTS.length; i++) {
this._subscribers[this.EVENTS[i]] = [];
}
// Add callback call when sample is clicked
// Double and single click together from: http://stackoverflow.com/a/7845282
var DELAY = 200, clicks = 0, timer = null;
$container.on('click', function(event) {
clicks++;
if (clicks === 1) {
timer = setTimeout(function() {
scope._eventCallback('click', event);
clicks = 0;
}, DELAY);
}
else {
clearTimeout(timer);
scope._eventCallback('dblclick', event);
clicks = 0;
}
})
.on('dblclick', function(event) {
event.preventDefault(); //cancel system double-click event
});
// register callback for populating info with clicked sample name
// set the timeout for fading out the info div
var infoDuration = 4000;
var infoTimeout = setTimeout(function() {
scope.$info.fadeOut();
}, infoDuration);
/**
*
* The functions showText and copyToClipboard are used in the 'click' and
* 'dblclick' events.
*
* When a sample is clicked we show a legend at the bottom left of the
* view. If this legend is clicked, we copy the sample name to the
* clipboard. When a sample is double-clicked we directly copy the sample
* name to the clipboard and add the legend at the bottom left of the view.
*
*/
function showText(n, i) {
clearTimeout(infoTimeout);
scope.$info.text(n);
scope.$info.show();
// reset the timeout for fading out the info div
infoTimeout = setTimeout(function() {
scope.$info.fadeOut();
scope.$info.text('');
}, infoDuration);
}
function copyToClipboard(text) {
var $temp = $('<input>');
// we need an input element to be able to copy to clipboard, taken from
// https://codepen.io/shaikmaqsood/pen/XmydxJ/
$('body').append($temp);
$temp.val(text).select();
document.execCommand('copy');
$temp.remove();
}
//Add info div as bottom of canvas
this.$info = $('<div>').attr('title', 'Click to copy to clipboard');
this.$info.css({'position': 'absolute',
'bottom': 0,
'height': 16,
'width': '50%',
'padding-left': 10,
'padding-right': 10,
'font-size': 12,
'z-index': 10000,
'background-color': 'rgb(238, 238, 238)',
'border': '1px solid black',
'font-family': 'Verdana,Arial,sans-serif'}).hide();
this.$info.click(function() {
var text = scope.$info.text();
// handle the case where multiple clicks are received
text = text.replace(/\(copied to clipboard\) /g, '');
copyToClipboard(text);
scope.$info.effect('highlight', {}, 500);
scope.$info.text('(copied to clipboard) ' + text);
});
$(this.renderer.domElement).parent().append(this.$info);
this.on('click', showText);
this.on('dblclick', function(n, i) {
copyToClipboard(n);
showText('(copied to clipboard) ' + n, i);
});
// if a decomposition uses a point cloud, or
// if a decomposition uses a parallel plot,
// update the default raycasting tolerance as
// it is otherwise too large and error-prone
var updateRaycasterLinePrecision = function(evt) {
if (scope.UIState.getProperty('view.viewType') === 'parallel-plot')
scope._raycaster.linePrecision = 0.01;
else
scope._raycaster.linePrecision = 1;
};
var updateRaycasterPointPrecision = function(evt) {
if (scope.UIState.getProperty('view.usesPointCloud'))
scope._raycaster.params.Points.threshold = 0.01;
else
scope._raycaster.params.Points.threshold = 1;
};
this.UIState.registerProperty('view.usesPointCloud',
updateRaycasterPointPrecision);
this.UIState.registerProperty('view.viewType',
updateRaycasterLinePrecision);
};
/**
* Builds a camera (for scatter or parallel plot)
*/
ScenePlotView3D.prototype.buildCamera = function(viewType) {
var camera;
if (viewType === 'scatter')
{
// Set up the camera
var max = _.max(this.decViews.scatter.decomp.dimensionRanges.max);
var frontFrust = _.min([max * 0.001, 1]);
var backFrust = _.max([max * 100, 100]);
// these are placeholders that are
// later updated in updateCameraAspectRatio
camera = new THREE.OrthographicCamera(-50, 50, 50, -50);
camera.position.set(0, 0, max * 5);
camera.zoom = 0.7;
}
else if (viewType === 'parallel-plot')
{
var w = this.decModels.dimensionRanges.max.length;
// Set up the camera
camera = new THREE.OrthographicCamera(0, w, 1, 0);
camera.position.set(0, 0, 1); //Must set positive Z because near > 0
camera.zoom = 0.7;
}
return camera;
};
/**
* Builds a camera controller (for scatter or parallel plot)
*/
ScenePlotView3D.prototype.buildCamController = function(viewType, cam, view) {
/**
* Object used to interact with the scene. By default it uses the mouse.
* @type {THREE.OrbitControls}
*/
var control = new THREE.OrbitControls(cam,
view);
control.enableKeys = false;
control.rotateSpeed = 1.0;
control.zoomSpeed = 1.2;
control.panSpeed = 0.8;
control.enableZoom = true;
control.enablePan = true;
control.enableRotate = (viewType === 'scatter');
return control;
};
/**
*
* Adds all the decomposition views to the current scene.
*
*/
ScenePlotView3D.prototype.addDecompositionsToScene = function() {
var j, marker, scaling = this.getScalingConstant();
// Note that the internal logic of the THREE.Scene object prevents the
// objects from being re-added so we can simply iterate over all the
// decomposition views.
// Add all the meshes to the scene, iterate through all keys in
// decomposition view dictionary
for (var decViewName in this.decViews) {
var isArrowType = this.decViews[decViewName].decomp.isArrowType();
for (j = 0; j < this.decViews[decViewName].markers.length; j++) {
marker = this.decViews[decViewName].markers[j];
this.scene.add(marker);
// only arrows include text as part of their markers
if (isArrowType) {
marker.label.scale.set(marker.label.scale.x * scaling,
marker.label.scale.y * scaling, 1);
}
}
for (j = 0; j < this.decViews[decViewName].ellipsoids.length; j++) {
this.scene.add(this.decViews[decViewName].ellipsoids[j]);
}
// if the left lines exist so will the right lines
if (this.decViews[decViewName].lines.left) {
this.scene.add(this.decViews[decViewName].lines.left);
this.scene.add(this.decViews[decViewName].lines.right);
}
}
this.needsUpdate = true;
};
/**
* Calculate a scaling constant for the text in the scene.
*
* It is important that this factor is calculated based on all the elements
* in a scene, and that it is the same for all the text elements in the
* scene. Otherwise, some text will be bigger than other.
*
* @return {Number} The scaling factor to use for labels.
*/
ScenePlotView3D.prototype.getScalingConstant = function() {
return (this.decModels.dimensionRanges.max[0] -
this.decModels.dimensionRanges.min[0]) * 0.001;
};
/**
*
* Helper method used to iterate over the ranges of the visible dimensions.
*
* This function that centralizes the pattern followed by drawAxesWithColor
* and drawAxesLabelsWithColor.
*
* @param {Function} action a function that can take up to three arguments
* "start", "end" and "index". And for each visible dimension the function
* will get the "start" and "end" of the range, and the current "index" of the
* visible dimension.
* @private
*
*/
ScenePlotView3D.prototype._dimensionsIterator = function(action) {
this.decModels._unionRanges();
if (this.UIState['view.viewType'] === 'scatter')
{
// shortcut to the index of the visible dimension and the range object
var x = this.visibleDimensions[0], y = this.visibleDimensions[1],
z = this.visibleDimensions[2], range = this.decModels.dimensionRanges,
is2D = (z === null || z === undefined);
// Adds a padding to all dimensions such that samples don't overlap
// with the axes lines. Determined based on the default sphere radius
var axesPadding = 1.07;
/*
* We special case Z when it is a 2D plot, whenever that's the case we set
* the range to be zero so no lines are shown on screen.
*/
// this is the "origin" of our ordination
var start = [range.min[x] * axesPadding,
range.min[y] * axesPadding,
is2D ? 0 : range.min[z] * axesPadding];
var ends = [
[range.max[x] * axesPadding,
range.min[y] * axesPadding,
is2D ? 0 : range.min[z] * axesPadding],
[range.min[x] * axesPadding,
range.max[y] * axesPadding,
is2D ? 0 : range.min[z] * axesPadding],
[range.min[x] * axesPadding,
range.min[y] * axesPadding,
is2D ? 0 : range.max[z] * axesPadding]
];
action(start, ends[0], x);
action(start, ends[1], y);
// when transitioning to 2D disable rotation to avoid awkward angles
if (is2D) {
this.control.enableRotate = false;
}
else {
action(start, ends[2], z);
this.control.enableRotate = true;
}
}
else {
//Parallel Plots show all axes
for (var i = 0; i < this.decViews['scatter'].decomp.dimensions; i++)
{
action([i, 0, 0], [i, 1, 0], i);
}
}
};
/**
*
* Draw the axes lines in the plot
*
* @param {String} color A CSS-compatible value that specifies the color
* of each of the axes lines, the length of these lines is determined by the
* global dimensionRanges property computed in decModels.
* If the color value is null the lines will be removed.
*
*/
ScenePlotView3D.prototype.drawAxesWithColor = function(color) {
var scope = this, axisLine;
// axes lines are removed if the color is null
this.removeAxes();
if (color === null) {
return;
}
this._dimensionsIterator(function(start, end, index) {
axisLine = makeLine(start, end, color, 3, false);
axisLine.name = scope._axisPrefix + index;
scope.scene.add(axisLine);
});
};
/**
*
* Draw the axes labels for each visible dimension.
*
* The text in the labels is determined using the percentage explained by
* each dimension and the abbreviated name of a single decomposition object.
* Note that we arbitrarily use the first one, as all decomposition objects
* presented in the same scene should have the same percentages explained by
* each axis.
*
* @param {String} color A CSS-compatible value that specifies the color
* of the labels, these labels will be positioned at the end of the axes
* line. If the color value is null the labels will be removed.
*
*/
ScenePlotView3D.prototype.drawAxesLabelsWithColor = function(color) {
var scope = this, axisLabel, decomp, firstKey, text, scaling;
scaling = this.getScalingConstant();
// the labels are only removed if the color is null
this.removeAxesLabels();
if (color === null) {
return;
}
// get the first decomposition object, it doesn't really matter which one
// we look at though, as all of them should have the same percentage
// explained on each axis
firstKey = _.keys(this.decViews)[0];
decomp = this.decViews[firstKey].decomp;
this._dimensionsIterator(function(start, end, index) {
text = decomp.axesLabels[index];
axisLabel = makeLabel(end, text, color);
if (scope.UIState['view.viewType'] === 'scatter') {
//Scatter has a 1 to 1 aspect ratio and labels in world size
axisLabel.scale.set(axisLabel.scale.x * scaling,
axisLabel.scale.y * scaling,
1);
}
else if (scope.UIState['view.viewType'] === 'parallel-plot') {
//Parallel plot aspect ratio depends on number of dimensions
//We have to correct label size to account for this.
//But we also have to fix label width so that it fits between
//axes, which are exactly 1 apart in world space
var cam = scope.camera;
var labelWPix = axisLabel.scale.x;
var labelHPix = axisLabel.scale.y;
var viewWPix = scope.width;
var viewHPix = scope.height;
//Assuming a camera zoom of 1:
var viewWUnits = cam.right - cam.left;
var viewHUnits = cam.top - cam.bottom;
//These are world sizes of label for a camera zoom of 1
var labelWUnits = labelWPix * viewWUnits / viewWPix;
var labelHUnits = labelHPix * viewHUnits / viewHPix;
//TODO FIXME HACK: Note that our options here are to scale each
//label to fit in its area, or to scale all labels by the same amount
//We choose to scale all labels by the same amount based on an
//empirical 'nice' label length of ~300
//We could replace this with a max of all label widths, but must note
//that label widths are always powers of 2 in the current version
//Resize to fit labels of width 300 between axes
var scalingFudge = .9 / (300 * viewWUnits / viewWPix);
axisLabel.scale.set(labelWUnits * scalingFudge,
labelHUnits * scalingFudge,
1);
}
axisLabel.name = scope._axisLabelPrefix + index;
scope.scene.add(axisLabel);
});
};
/**
*
* Helper method to remove objects that match a prefix from the view's scene
* this method is used by removeAxes and removeAxesLabels. This function
* iterates "num" times, and for each iteration it finds and removes objects
* with the name of the form "prefix" + "iteration".
*
* @param {String} prefix The label that will prepended to the iterating
* index.
*
*/
ScenePlotView3D.prototype._removeObjectsWithPrefix = function(prefix) {
var scope = this;
_.each(_.range(this.decViews.scatter.decomp.dimensions), function(i) {
var axisLine = scope.scene.getObjectByName(prefix + i);
scope.scene.remove(axisLine);
});
};
/**
*
* Helper method to remove the axis lines from the scene
*
*/
ScenePlotView3D.prototype.removeAxes = function() {
this._removeObjectsWithPrefix(this._axisPrefix);
};
/**
*
* Helper method to remove the axis labels from the scene
*
*/
ScenePlotView3D.prototype.removeAxesLabels = function() {
this._removeObjectsWithPrefix(this._axisLabelPrefix);
};
/**
*
* Resizes and relocates the scene.
*
* @param {Float} xView New horizontal location.
* @param {Float} yView New vertical location.
* @param {Float} width New scene width.
* @param {Float} height New scene height.
*
*/
ScenePlotView3D.prototype.resize = function(xView, yView, width, height) {
this.xView = xView;
this.yView = yView;
this.width = width;
this.height = height;
this.updateCameraAspectRatio();
this.control.update();
//Since parallel plot labels have to correct for aspect ratio, we need
//to redraw when width/height of view is modified.
this.drawAxesLabelsWithColor(this.axesColor);
this.needsUpdate = true;
};
/**
*
* Resets the aspect ratio of the camera according to the current size of the
* plot space.
*
*/
ScenePlotView3D.prototype.updateCameraAspectRatio = function() {
if (this.UIState['view.viewType'] === 'scatter')
{
var x = this.visibleDimensions[0], y = this.visibleDimensions[1];
// orthographic cameras operate in space units not in pixel units i.e.
// the width and height of the view is based on the objects not the window
var owidth = this.decModels.dimensionRanges.max[x] -
this.decModels.dimensionRanges.min[x];
var oheight = this.decModels.dimensionRanges.max[y] -
this.decModels.dimensionRanges.min[y];
var aspect = this.width / this.height;
// ensure that the camera's aspect ratio is equal to the window's
owidth = oheight * aspect;
this.camera.left = -owidth / 2;
this.camera.right = owidth / 2;
this.camera.top = oheight / 2;
this.camera.bottom = -oheight / 2;
this.camera.aspect = aspect;
this.camera.updateProjectionMatrix();
}
else if (this.UIState['view.viewType'] === 'parallel-plot')
{
var w = this.decModels.dimensionRanges.max.length;
this.camera.left = 0;
this.camera.right = w;
this.camera.top = 1;
this.camera.bottom = 0;
this.camera.updateProjectionMatrix();
}
};
/**
* Updates the target and dimensions of the camera and control
*
* The target of the scene depends on the coordinate space of the data, by
* default it is set to zero, but we need to make sure that the target is
* reasonable for the data.
*/
ScenePlotView3D.prototype.updateCameraTarget = function() {
if (this.UIState['view.viewType'] === 'scatter')
{
var x = this.visibleDimensions[0], y = this.visibleDimensions[1];
var owidth = this.decModels.dimensionRanges.max[x] -
this.decModels.dimensionRanges.min[x];
var oheight = this.decModels.dimensionRanges.max[y] -
this.decModels.dimensionRanges.min[y];
var xcenter = this.decModels.dimensionRanges.max[x] - (owidth / 2);
var ycenter = this.decModels.dimensionRanges.max[y] - (oheight / 2);
var max = _.max(this.decViews.scatter.decomp.dimensionRanges.max);
this.control.target.set(xcenter, ycenter, 0);
this.camera.position.set(xcenter, ycenter, max * 5);
this.camera.updateProjectionMatrix();
this.light.position.set(xcenter, ycenter, max * 5);
this.updateCameraAspectRatio();
this.control.saveState();
this.needsUpdate = true;
}
else if (this.UIState['view.viewType'] === 'parallel-plot') {
this.control.target.set(0, 0, 1); //Must set positive Z because near > 0
this.camera.position.set(0, 0, 1); //Must set positive Z because near > 0
this.camera.updateProjectionMatrix();
this.updateCameraAspectRatio();
this.control.saveState();
this.needsUpdate = true;
}
};
ScenePlotView3D.prototype.NEEDS_RENDER = 1;
ScenePlotView3D.prototype.NEEDS_CONTROLLER_REFRESH = 2;
/**
*
* Convenience method to check if this or any of the decViews under this need
* rendering
*
*/
ScenePlotView3D.prototype.checkUpdate = function() {
var updateDimensions = false, updateColors = false,
currentDimensions, backgroundColor, axesColor, scope = this;
//Check if the view type changed and swap the markers in/out of the scene
//tree.
var anyMarkersSwapped = false;
_.each(this.decViews, function(view) {
if (view.needsSwapMarkers) {
anyMarkersSwapped = true;
var oldMarkers = view.getAndClearOldMarkers();
for (var i = 0; i < oldMarkers.length; i++) {
scope.scene.remove(oldMarkers[i]);
oldMarkers[i].material.dispose(); //FIXME: What is our plan for this?
oldMarkers[i].geometry.dispose(); //FIXME: What is our plan for this?
}
var newMarkers = view.markers;
for (i = 0; i < newMarkers.length; i++) {
scope.scene.add(newMarkers[i]);
}
var lines = view.lines;
var ellipsoids = view.ellipsoids;
if (scope.UIState['view.viewType'] == 'parallel-plot') {
for (i = 0; i < lines.length; i++)
scope.scene.remove(lines[i]);
for (i = 0; i < ellipsoids.length; i++)
scope.scene.remove(ellipsoids[i]);
}
if (scope.UIState['view.viewType'] == 'scatter') {
for (i = 0; i < lines.length; i++)
scope.scene.add(lines[i]);
for (i = 0; i < ellipsoids.length; i++)
scope.scene.add(ellipsoids[i]);
}
}});
if (anyMarkersSwapped) {
this.updateCameraTarget();
this.control.update();
}
// check if any of the decomposition views have changed
var updateData = _.any(this.decViews, function(dv) {
// note that we may be overwriting these variables, but we have a
// guarantee that if one of them changes for one of decomposition views,
// all of them will have changed, so grabbing one should be sufficient to
// perform the comparisons below
currentDimensions = dv.visibleDimensions;
backgroundColor = dv.backgroundColor;
axesColor = dv.axesColor;
return dv.needsUpdate;
});
_.each(this.decViews, function(view) {
view.getTubes().forEach(function(tube) {
if (tube !== null)
scope.scene.add(tube);
});
});
// check if the visible dimensions have changed
if (!_.isEqual(currentDimensions, this.visibleDimensions)) {
// remove the current axes
this.removeAxes();
this.removeAxesLabels();
// get the new dimensions and re-display the data
this.visibleDimensions = _.clone(currentDimensions);
this.drawAxesWithColor(this.axesColor);
this.drawAxesLabelsWithColor(this.axesColor);
this.updateCameraTarget();
this.control.update();
updateDimensions = true;
}
// check if we should change the axes color
if (axesColor !== this.axesColor) {
this.drawAxesWithColor(axesColor);
this.drawAxesLabelsWithColor(axesColor);
this.axesColor = _.clone(axesColor);
updateColors = true;
}
// check if we should change the background color
if (backgroundColor !== this.backgroundColor) {
this.backgroundColor = _.clone(backgroundColor);
this.scene.background = new THREE.Color(this.backgroundColor);
updateColors = true;
}
if (updateData) {
this.drawAxesWithColor(this.axesColor);
this.drawAxesLabelsWithColor(this.axesColor);
}
var retVal = 0;
if (anyMarkersSwapped)
retVal |= ScenePlotView3D.prototype.NEEDS_CONTROLLER_REFRESH;
if (anyMarkersSwapped || this.needsUpdate || updateData ||
updateDimensions || updateColors || this.control.autoRotate)
retVal |= ScenePlotView3D.prototype.NEEDS_RENDER;
// if anything has changed, then trigger an update
return retVal;
};
/**
*
* Convenience method to re-render the contents of the scene.
*
*/
ScenePlotView3D.prototype.render = function() {
this.renderer.setViewport(this.xView, this.yView, this.width, this.height);
this.renderer.render(this.scene, this.camera);
var camera = this.camera;
// if autorotation is enabled, then update the controls
if (this.control.autoRotate) {
this.control.update();
}
// Only scatter plots that are not using a point cloud should be pointed
// towards the camera. For arrow types and point clouds doing this will
// results in odd visual effects
if (!this.UIState.getProperty('view.usesPointCloud') &&
this.decViews.scatter.decomp.isScatterType()) {
_.each(this.decViews.scatter.markers, function(element) {
element.quaternion.copy(camera.quaternion);
});
}
this.needsUpdate = false;
$.each(this.decViews, function(key, val) {
val.needsUpdate = false;
});
};
/**
*
* Helper method that runs functions subscribed to the container's callbacks.
* @param {String} eventType Event type being called
* @param {event} event The event from jQuery, with x and y click coords
* @private
*
*/
ScenePlotView3D.prototype._eventCallback = function(eventType, event) {
event.preventDefault();
// don't do anything if no subscribers
if (this._subscribers[eventType].length === 0) {
return;
}
var element = this.renderer.domElement, scope = this;
var offset = $(element).offset();
this._mouse.x = ((event.clientX - offset.left) / element.width) * 2 - 1;
this._mouse.y = -((event.clientY - offset.top) / element.height) * 2 + 1;
this._raycaster.setFromCamera(this._mouse, this.camera);
// get a flattened array of markers
var objects = _.map(this.decViews, function(decomp) {
return decomp.markers;
});
objects = _.reduce(objects, function(memo, value) {
return memo.concat(value);
}, []);
var intersects = this._raycaster.intersectObjects(objects);
// Get first intersected item and call callback with it.
if (intersects && intersects.length > 0) {
var firstObj = intersects[0].object, intersect;
/*
* When the intersect object is a Points object, the raycasting method
* won't intersect individual mesh objects. Instead it intersects a point
* and we get the index of the point. This index can then be used to
* trace the original Plottable object.
*/
if (firstObj.isPoints || firstObj.isLineSegments) {
// don't search over invisible things
intersects = _.filter(intersects, function(marker) {
return firstObj.geometry.attributes.visible.getX(marker.index) &&
firstObj.geometry.attributes.opacity.getX(marker.index);
});
var meshIndex = intersects[0].index;
var modelIndex = this.decViews.scatter.getModelPointIndex(meshIndex,
this.UIState['view.viewType']);
intersect = this.decViews.scatter.decomp.plottable[modelIndex];
}
else {
intersects = _.filter(intersects, function(marker) {
return marker.object.visible && marker.object.material.opacity;
});
intersect = intersects[0].object;
}
for (var i = 0; i < this._subscribers[eventType].length; i++) {
// keep going if one of the callbacks fails
try {
this._subscribers[eventType][i](intersect.name, intersect);
} catch (e) {
console.error(e);
}
this.needsUpdate = true;
}
}
};
/**
*
* Interface to subscribe to event types in the canvas, see the EVENTS
* property.
*
* @param {String} eventType The type of event to subscribe to.
* @param {Function} handler Function to call when `eventType` is triggered,
* receives two parameters, a string with the name of the object, and the
* object itself i.e. f(objectName, object).
*
* @throws {Error} If the given eventType is unknown.
*
*/
ScenePlotView3D.prototype.on = function(eventType, handler) {
if (this.EVENTS.indexOf(eventType) === -1) {
throw new Error('Unknown event ' + eventType + '. Known events are: ' +
this.EVENTS.join(', '));
}
this._subscribers[eventType].push(handler);
};
/**
*
* Interface to unsubscribe a function from an event type, see the EVENTS
* property.
*
* @param {String} eventType The type of event to unsubscribe from.
* @param {Function} handler Function to remove from the subscribers list.
*
* @throws {Error} If the given eventType is unknown.
*
*/
ScenePlotView3D.prototype.off = function(eventType, handler) {