-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsplatterplot.js
1375 lines (1154 loc) · 41.7 KB
/
splatterplot.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
window.onload = main;
// create the gl context using lightgl.js
var gl;
if (location.search == "?lofi") {
gl = GL.create({width: 640, height: 480});
} else {
gl = GL.create({width: 800, height: 600});
}
// hold compiled shaders
var shaders = [];
// `timer` holds a timer variable to handle the re-calling of gl.ondraw while waiting
// for asynchronous loads of resources.
var timer = null;
// `timings` holds a boolean value whether we should capture timing information of
// various operations of splatterplots for instrumentation/analysis purposes.
var timings = false;
// variables that determine the current viewport of the datapoints
var screenOffset = [0,0];
var scale = 1;
var offset = [0,0];
// calculated global bounds of all data series
var dataReady = false;
var bounds = [];
// holds a KD-tree for user querying ('what is here?')
var pointTree = {};
// the dataset object that represents all data series
var ds = {
data: [],
groups: [], // should contain objects that have 'textures', 'data', and 'buffer' fields
colors: [[0.0, 0.580, 0.686], [0.996, 0.325, 0.290]],
textures: [],
colNames: [],
numCols: 0,
numRows: 0,
ready: false
};
// holds a full quad (e.g. -1,-1 to 1,1) for texture writing
var plane;
// holds the 'max' texture name that has the maximum value in its (0,0) coordinate
// (can change based on the size of the canvas when ping-ponging)
var maxTexName = 'max1';
var maxComputed = false;
// `maxTexture` and `maxTexture2` holds the global maximum texture
var maxTexture = [];
var maxTextureNum = -1;
// holds any sort of background texture, and the corresponding plane
var bgTexture;
var bgPlane;
// rendering variables (should be user-controlled eventually)
var sigma = 15.0;
var threshold = 0.5;
var clutterRadius = 25;
var outlierSize = 2.5;
// Helper methods for getting performance information
var timeStart = function(name) {
if (timings) {
console.time(name);
}
}
var timeStop = function(name) {
if (timings) {
console.timeEnd(name);
}
}
// ### setZoomPan();
//
// Sets up the transformation matrix for the incoming datapoints
var setZoomPan = function() {
gl.loadIdentity();
gl.translate(screenOffset[0], screenOffset[1], 0);
gl.scale(scale, scale, 1);
gl.translate(offset[0], offset[1], 0);
};
// ### initTextures();
//
// Instantiates the textures for first draw for each data series (group).
var textureExists = false;
var initTextures = function() {
// globally supported by WebGL browsers, but at a loss of precision
var options = {
filter: gl.NEAREST,
format: gl.RGBA,
type: gl.UNSIGNED_BYTE
};
// Higher precision, but requires support from the OES_texture_float extension.
var floatOpts = {
filter: gl.NEAREST,
format: gl.RGBA,
type: gl.FLOAT
};
// initialize textures given width + height
ds.groups.forEach(function(grp,i) {
// Textures for drawing density graphs and KDE
grp.textures['freq0'] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
grp.textures['freq1'] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
// Textures for computing the maximum value in the blurred textures
grp.textures['max0'] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
grp.textures['max1'] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
// Textures for computing the distance to the threshold boundary using the
// jump-flooding algorithm.
grp.textures['dist0'] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
grp.textures['dist1'] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
// The final colored texture to be blended with other data series.
grp.textures['rgb'] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
// The texture that holds the selected outlier points
grp.textures['outliers'] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
grp.textures['outlierpts'] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
});
// Initialize the global maximum textures
maxTexture[0] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
maxTexture[1] = new GL.Texture(gl.canvas.width, gl.canvas.height, floatOpts);
// Assuming the texture is a power-of-two texture.
// Set correction factor to crop off excess texture in
bgTexture = GL.Texture.fromURL("img/usa-map.png", {
minFilter: gl.NEAREST_MIPMAP_LINEAR,
magFilter: gl.LINEAR,
format: gl.RGBA
});
// Initialize a utility framebuffer
ds.fbo = gl.createFramebuffer();
// Clean up and unbind any bound textures/framebuffers
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.bindTexture(gl.TEXTURE_2D, null);
// Unset variable set by lightgl.js in TEXTURE.js;
// see <http://code.google.com/p/chromium/issues/detail?id=125481>
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
textureExists = true;
};
// ### clearTextures(datasetGroup);
//
// On redraw, clear all values from all textures from the given dataset group (e.g. one of the
// elements from `ds.groups`).
var clearTextures = function(grp) {
gl.bindFramebuffer(gl.FRAMEBUFFER, ds.fbo);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
for (var texture in grp.textures) {
// Skip processing max textures so that they always contain the maximum blurred value of each dataset.
// Set `maxComputed` to false to force rebuilding the texture.
if (maxComputed && texture.indexOf("max") != -1) continue;
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, grp.textures[texture].id, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}
// clear the max texture if the max has not been computed
if (!maxComputed) {
for (var i = 0; i < 2; i++) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, maxTexture[i].id, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}
}
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
};
// ### deleteTextures();
//
// Forcibly deletes all textures.
var deleteTextures = function() {
ds.groups.forEach(function(grp, g) {
for (var texture in grp.textures) {
gl.deleteTexture(grp.textures[texture].id);
delete grp.textures[texture];
}
});
for (var i = 0; i < 2; i++) {
gl.deleteTexture(maxTexture[i].id);
delete maxTexture[i];
}
textureExists = false;
}
// ### drawPoints();
//
// Draws the points as a conventional scatterplot. Useful to see overdraw.
var order = [];
var drawPoints = function(doShuffle) {
if (!shaders['testlgl']) {
if (!timer)
timer = setTimeout("gl.ondraw()", 300);
return;
}
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT);
var shader = shaders['testlgl'];
//shader.uniforms({pointSize: 4});
gl.enable(gl.DEPTH_TEST);
gl.disable(gl.BLEND);
// Set the transformation matrix for the incoming points
gl.pushMatrix();
gl.matrixMode(gl.MODELVIEW);
setZoomPan();
var colorz = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [128, 128, 0], [128, 128, 128]];
if (order.length == 0) {
for (var i = 0; i < ds.groups.length; i++) order[i] = i;
}
if (doShuffle) {
// use Fisher-Yates to shuffle
for (var i = order.length - 1; i > 1; i--) {
var j = Math.floor(Math.random() * (i+1));
var tmp = order[i];
order[i] = order[j];
order[j] = tmp;
}
}
// Draw each data series as one color
for (var i = 0; i < order.length; i++) {
var v = ds.groups[order[i]];
var vertBuffer = [];
vertBuffer['position'] = v.buf;
shader.uniforms({
pointSize: outlierSize,
color: colorz[order[i]]
}).drawBuffers(vertBuffer, null, gl.POINTS);
}
// Remove the transformation
gl.popMatrix();
};
// ### drawBlur();
//
// For each data series (group), compute the density at each pixel in the canvas, then
// blur in the x- and y-directions, storing the output in `textures['max0']`.
var drawBlur = function() {
// Determine which blur shader to use, based on the given bandwidth parameter
var window = sigma * 3;
var blurShader = window < 16 ? shaders['testblur16'] :
window < 32 ? shaders['testblur32'] :
window < 64 ? shaders['testblur64'] :
window < 128 ? shaders['testblur128'] :
shaders['testblur256'];
if (!shaders['testpt'] || !blurShader) {
if (!timer)
timer = setTimeout("gl.ondraw()", 300);
return;
}
if (!textureExists) {
timeStart("\tinitializing textures");
initTextures();
timeStop("\tinitializing textures");
}
// Clear the viewport and set a blank color for density counts.
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
ds.groups.forEach(function(grp,i) {
timeStart("\tclearing textures");
clearTextures(grp);
timeStop("\tclearing textures");
// Set up point-drawing state and transformation matrix.
gl.pushMatrix();
gl.matrixMode(gl.MODELVIEW);
setZoomPan();
// We don't really care about a color here, we just want to make a texture that
// is conveying locations of points; get ready to draw points to fbo
gl.disable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE, gl.ONE);
gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
// Draw point density to texture (`textures['freq0']`).
timeStart("\tdrawing point density to texture");
grp.textures['freq0'].drawTo(function() {
var vertBuffer = [];
vertBuffer['position'] = grp.buf;
shaders['testpt'].uniforms({pointSize:1}).drawBuffers(vertBuffer, null, gl.POINTS);
});
timeStop("\tdrawing point density to texture");
// Clean up state
gl.bindBuffer(gl.ARRAY_BUFFER, null); // release buffer
gl.popMatrix();
var delta = [1.0 / gl.canvas.width, 1.0 / gl.canvas.height];
// Start to blur points in the x direction.
timeStart("\tbluring points in x direction");
grp.textures['freq1'].drawTo(function() {
grp.textures['freq0'].bind(0);
blurShader.uniforms({
texture: 0,
sigma: sigma,
offset: [1.0, 0.0],
delta: delta
}).draw(plane);
});
timeStop("\tbluring points in x direction");
// Now, swap texture 2 and 1; change offset to blur in the y direction.
timeStart("\tbluring points in y direction");
grp.textures['freq0'].drawTo(function() {
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
grp.textures['freq1'].bind(0);
blurShader.uniforms({
texture: 0,
sigma: sigma,
offset: [0.0, 1.0],
delta: delta
}).draw(plane);
});
timeStop("\tbluring points in y direction");
// also draw to inital max texture for use there.
timeStart("\tbluring points in y direction (repeat)");
grp.textures['max0'].drawTo(function() {
grp.textures['freq1'].bind(0);
blurShader.uniforms({
texture: 0,
sigma: sigma,
offset: [0.0, 1.0],
delta: delta
}).draw(plane);
});
timeStop("\tbluring points in y direction (repeat)");
// clean up state
grp.textures['freq1'].unbind(0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
});
};
// ### findMax();
//
// Use GPGPU-like minimizations to reduce the values in `textures['max0']` to the first
// two pixel values in the texture for subsequent computations. At the end of this
// function, the maximum value should be (0,0) of `textures['max3']`.
var findMax = function() {
var shader = shaders['testmax'];
if (!shader) {
if (!timer)
timer = setTimeout("gl.ondraw()", 300);
return;
}
gl.disable(gl.DEPTH_TEST);
var scalePerStep = 8; // shader collapses 8*8 vertices into 1
var maxDim = Math.max(gl.canvas.width, gl.canvas.height); // default: 800px
var numSteps = Math.floor(Math.log(maxDim) / Math.log(scalePerStep)); // default: 3 steps
var pixAtEnd = Math.ceil(maxDim / Math.pow(scalePerStep, numSteps)); // default: 2 pixels
// Calculate the maximum for each group independently.
ds.groups.forEach(function(grp,i) {
timeStart("\tfinding max for group " + i);
for (var i = 0; i < numSteps; i++) {
grp.textures['max' + (i+1) % 2].drawTo(function() {
grp.textures['max' + i % 2].bind(0);
shaders['testmax'].uniforms({
texture: 0,
delta: [1.0 / gl.canvas.width, 1.0 / gl.canvas.height]
}).draw(plane);
grp.textures['max' + i % 2].unbind(0);
});
}
timeStop("\tfinding max for group " + i);
});
console.log("maxValue is in the max" + (numSteps % 2) + " texture, in the first " + pixAtEnd + " pixels");
maxTexName = "max" + ((numSteps) % 2);
maxComputed = true;
};
// ### getGlobalMax();
//
// Uses a shader to pick out the maximum value stored in all groups' textures.
// Activated on request from the UI.
var getGlobalMax = function() {
var shader = shaders['maxtexture'];
if (!shader) {
if (!timer)
timer = setTimeout("gl.ondraw()", 300);
return;
}
gl.disable(gl.DEPTH_TEST);
var lastGrp = 0;
ds.groups.forEach(function(grp, g) {
maxTexture[(g + 1) % 2].drawTo(function() {
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
maxTexture[g % 2].bind(0);
grp.textures[maxTexName].bind(1);
shader.uniforms({
max1: 0,
max2: 1
}).draw(plane);
grp.textures[maxTexName].unbind(1);
maxTexture[g % 2].unbind(0);
});
lastGrp = (g + 1) % 2;
});
maxTextureNum = lastGrp;
};
// ### getMaxTexture();
//
// Contains logic to select the appropriate texture that holds the maximum value
// with which to determine the thresholded region for the particular group.
var getMaxTexture = function(grp) {
if (maxTextureNum == -1)
return grp.textures[maxTexName];
else
return maxTexture[maxTextureNum];
};
// ### getJfa();
//
// Use the jump-flooding algorithm to calculate the distance from every pixel to the
// nearest threshold boundary.
var getJfa = function() {
if (!shaders['jfa'] || !shaders['jfainit']) {
if (!timer)
timer = setTimeout("gl.ondraw()", 300);
return;
}
gl.disable(gl.DEPTH_TEST);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
// Execute the initialization step to prime the points in the thresholded region.
ds.groups.forEach(function(grp, g) {
timeStart("\tInitializing JFA for group " + g);
grp.textures['dist0'].drawTo(function() {
grp.textures['freq0'].bind(0); // Texture that contains the blurred density data.
getMaxTexture(grp).bind(1); // Texture that contains the max density at (0,0)
shaders['jfainit'].uniforms({
texture: 0,
maxTex: 1,
upperLimit: threshold
}).draw(plane);
grp.textures['freq0'].unbind(0);
getMaxTexture(grp).unbind(1);
});
timeStop("\tInitializing JFA for group " + g);
// Iterate through the JFA
var size = Math.max(gl.canvas.height, gl.canvas.width);
var log2 = Math.log(size) / Math.log(2);
var n = Math.ceil(log2);
var k = Math.pow(2, n - 1);
n = (n - 1) / 2 + 1;
timeStart("\tRunning JFA for group " + g);
for (var i = 0; i < 2 * n; i++) {
grp.textures['dist' + (i+1) % 2].drawTo(function() {
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
grp.textures['dist' + i % 2].bind(0);
shaders['jfa'].uniforms({
kStep: k,
delta: [1 / gl.canvas.width, 1 / gl.canvas.height],
texture: 0
}).draw(plane);
grp.textures['dist' + i % 2].unbind(0);
});
k = Math.max(1, Math.round(k / 2));
}
timeStop("\tRunning JFA for group " + g);
});
};
// ### shade();
//
// Compute the final coloring of each data series (group) independently.
var shade = function() {
if (!shaders['shade']) {
if (!timer)
timer = setTimeout("gl.ondraw()", 300);
return;
}
gl.clearColor(1.0, 1.0, 1.0, 1.0);
ds.groups.forEach(function(grp, i) {
// Use the max0 texture (raw density function) and the distance texture (jfa)
grp.textures['rgb'].drawTo(function() {
grp.textures['outlierpts'].bind(3);
getMaxTexture(grp).bind(2);
grp.textures['dist0'].bind(1);
grp.textures['freq0'].bind(0);
shaders['shade'].uniforms({
texture: 0,
distances: 1,
maxTex: 2,
outliers: 3,
delta: [1 / gl.canvas.width, 1 / gl.canvas.height],
rgbColor: ds.colors[i],
lowerLimit: 0.001,
upperLimit: threshold
}).draw(plane);
});
// Clean up state.
grp.textures['freq0'].unbind(0);
grp.textures['dist0'].unbind(1);
getMaxTexture(grp).unbind(2);
grp.textures['outlierpts'].bind(3);
});
};
// # setTransformationBackground();
//
// Sets the transformation matrix used by the background drawing shader.
// For now, assumes the background is a equirectangular projection of the US
// centered at xx, xx, bounds
var setTransformationBackground = function(mb) {
// From Wikipedia: https://commons.wikimedia.org/wiki/File:USA_location_map.svg;
// the bounds of the current map; N, S, W, E:
// create the `bgPlane` if it hasn't been created
if (!bgPlane) {
bgPlane = GL.Mesh.plane();
bgPlane.vertices[0] = [mb[0], mb[2], 0];
bgPlane.vertices[1] = [mb[1], mb[2], 0];
bgPlane.vertices[2] = [mb[0], mb[3], 0];
bgPlane.vertices[3] = [mb[1], mb[3], 0];
bgPlane.compile();
}
};
// ### blend();
//
// Blend the shaded datasets together into the final image, and draw to the viewport.
var blend = function() {
if (!shaders['blend'] || !shaders['background']) {
if (!timer)
timer = setTimeout('gl.ondraw()', 300);
return;
}
gl.clearColor(1.0, 1.0, 1.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
if (bgTexture && $("#showbackground").prop("checked")) {
var mapBounds = [-125.5, -66.5, 24.2, 49.8];
setTransformationBackground(mapBounds);
// Set up point-drawing state and transformation matrix.
gl.pushMatrix();
gl.matrixMode(gl.MODELVIEW);
setZoomPan();
bgTexture.bind(0);
// Set where the crop the image to allow a power-of-two texture size (for mipmapping);
// takes original scale height (2133px) and 'scales' the texture coordinates so they crop off
// the remainder to make the power-of-two size (4096 - 2133).
mapBounds[2] = mapBounds[2] - ((mapBounds[3] - mapBounds[2]) / 2133) * (4096 - 2133);//23.55968;
// draw background, if it exists
shaders['background'].uniforms({
background: 0,
bounds: mapBounds
}).draw(bgPlane);
bgTexture.unbind(0);
// Clean up state
gl.bindBuffer(gl.ARRAY_BUFFER, null); // release buffer
gl.popMatrix();
}
ds.groups.forEach(function(grp, i) {
grp.textures['rgb'].bind(i);
});
shaders['blend'].uniforms({
N: ds.groups.length, // this should be the number of datasets
lf: 0.9,
cf: 0.95,
texture0: 0,
texture1: 1,
texture2: 2,
texture3: 3,
texture4: 4,
texture5: 5,
texture6: 6,
texture7: 7
}).draw(plane);
// clean up state
//ds.groups[0].textures['rgb'].unbind(0);
//ds.groups[1].textures['rgb'].unbind(1);
ds.groups.forEach(function(grp, i) {
grp.textures['rgb'].unbind(i);
});
};
// ### drawOutliers();
//
// Draw the outlier points
var drawOutliers = function() {
if (!shaders['outliers'] || !shaders['outliercombine']) {
if (!timer)
timer = setTimeout('gl.ondraw()', 300);
return;
}
var minPt = [untransformX(0), untransformY(0)];
var maxPt = [untransformX(gl.canvas.width), untransformY(gl.canvas.height)];
var gridSize = [gl.canvas.width / clutterRadius, gl.canvas.height / clutterRadius];
// get the grid size in actual coords
for (var i = 0; i < 2; i++) {
gridSize[i] = (maxPt[i] - minPt[i]) / gridSize[i];
}
var resolution = [gl.canvas.width, gl.canvas.height];
var gridOffset = [0,0];
for (var i = 0; i < 2; i++) {
gridOffset[i] = (minPt[i] / gridSize[i]) - Math.floor(minPt[i] / gridSize[i]);
gridOffset[i] = gridOffset[i] * clutterRadius / resolution[i];
}
ds.groups.forEach(function(grp, i) {
grp.textures['outliers'].drawTo(function() {
// Set up point-drawing state and transformation matrix.
gl.pushMatrix();
gl.matrixMode(gl.MODELVIEW);
setZoomPan();
gl.disable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.DST_ALPHA);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
var vertBuffer = [];
vertBuffer['position'] = grp.buf;
grp.textures['dist0'].bind(0);
shaders['outliers'].uniforms({
jfa: 0,
gridSize: clutterRadius,
resolution: [gl.canvas.width, gl.canvas.height],
offset: gridOffset
}).drawBuffers(vertBuffer, null, gl.POINTS);
grp.textures['dist0'].unbind(0);
gl.popMatrix();
});
// now, actually draw specific points out
gl.disable(gl.BLEND);
gl.disable(gl.DEPTH_TEST);
grp.textures['outlierpts'].drawTo(function() {
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
grp.textures['outliers'].bind(0);
shaders['outliercombine'].uniforms({
grid: 0,
gridSize: clutterRadius,
pointRadius: outlierSize,
resolution: [gl.canvas.width, gl.canvas.height],
offset: gridOffset
}).draw(plane);
grp.textures['outliers'].unbind(0);
});
});
};
// ### init();
//
// Function that runs once when the data has been loaded and initialized; sets the plane
// object for screen-space textures and the values to set up the point transformation
// matrix.
var setup = false;
var init = function() {
plane = GL.Mesh.plane();
setInitBounds();
setup = true;
};
// ### setInitBounds();
//
// Set up 'bounding box', more like the window parameters of the graph; get the max range
// and set a +20% margin.
var setInitBounds = function() {
var b = bounds;
offset = [-(b[0][0] + b[0][1]) / 2.0, -(b[1][0] + b[1][1]) / 2.0];
scale = Math.max(b[0][1] - b[0][0], b[1][1] - b[1][0]) * 1.2;
scale = gl.canvas.height / scale;
screenOffset = [gl.canvas.width / 2.0, gl.canvas.height / 2.0];
maxComputed = false;
};
// ### gl.ondraw();
//
// The drawing command handled by lightgl.js. Whenever options are changed or the user
// pans or zooms, this function will be called.
gl.ondraw = function() {
// Delay drawing until shaders and data is ready
if (!dataReady) {
if (!timer)
timer = setTimeout("gl.ondraw()", 300);
return;
}
// Cancel any subsequent timing events for this function.
if (timer) {
clearTimeout(timer);
timer = null;
}
// Set the timings variable
timings = $("#dotiming").prop('checked');
if (timings) {
console.log("START TIMING RUN");
console.log("=====================================");
//timeStart("== total time elapsed");
}
// Tell the drawing operations that the maximum textures are unavilable
// if the 'use global maximum' checkbox is unchecked.
if (!$("#globalmax").prop('checked'))
maxTextureNum = -1;
console.time("== total time elapsed");
// On the first run, set up required parameters.
if (!setup)
init();
if ($("#showpoints").prop('checked'))
drawPoints();
else if ($("#showjfa").prop('checked')) {
drawBlur();
findMax();
getJfa();
debugJfa();
} else if ($("#hideoutliers").prop('checked')) {
drawBlur();
if (!maxComputed)
findMax();
if ($("#globalmax").prop('checked'))
getGlobalMax();
getJfa();
shade();
blend();
} else if ($("#showmax").prop('checked')) {
drawBlur();
findMax();
debugMax();
} else {
if (timings) { console.time("draw blur"); }
drawBlur();
if (timings) { console.timeEnd("draw blur"); console.time("find max"); }
if (!maxComputed)
findMax();
if ($("#globalmax").prop('checked'))
getGlobalMax();
if (timings) { console.timeEnd("find max"); console.time("propagate JFA"); }
getJfa();
if (timings) { console.timeEnd("propagate JFA"); console.time("draw outliers"); }
drawOutliers();
if (timings) { console.timeEnd("draw outliers"); console.time("shade"); }
shade();
if (timings) { console.timeEnd("shade"); console.time("blend"); }
blend();
if (timings) { console.timeEnd("blend"); }
}
// draw the plot elements (axes, labels)
if ($("#hidegrid").prop('checked')) {
context2d.clearRect(0, 0, gl.canvas.width, gl.canvas.height);
} else {
timeStart("draw 2D grid");
draw2d();
timeStop("draw 2D grid");
}
console.timeEnd("== total time elapsed");
//timeStop("== total time elapsed");
};
// ## Handlers for mouse-interaction
// Handle panning the canvas.
var panX, panY;
var buttons = {};
gl.onmousedown = function(e) {
buttons[e.which] = true;
panX = e.x;
panY = gl.canvas.height - e.y;
};
gl.onmousemove = function(e) {
if (drags(e)) {
screenOffset[0] += e.x - panX;
screenOffset[1] += (gl.canvas.height - e.y) - panY;
panX = e.x;
panY = gl.canvas.height - e.y;
gl.ondraw();
} else if (pointTree.hasOwnProperty("nearest")) {
// get actual mouse position within the canvas
var mouseX = e.x - gl.canvas.offsetLeft;
var mouseY = gl.canvas.height - (e.y - gl.canvas.offsetParent.offsetTop);
// just do the simple thing and ask which grid cell we're in
var minPt = [untransformX(0), untransformY(0)];
var maxPt = [untransformX(gl.canvas.width), untransformY(gl.canvas.height)];
var gridSize = [gl.canvas.width / clutterRadius, gl.canvas.height / clutterRadius];
// get the grid size in actual coords
for (var i = 0; i < 2; i++) {
gridSize[i] = (maxPt[i] - minPt[i]) / gridSize[i];
}
var resolution = [gl.canvas.width, gl.canvas.height];
var gridOffset = [0,0];
for (var i = 0; i < 2; i++) {
gridOffset[i] = (minPt[i] / gridSize[i]) - Math.floor(minPt[i] / gridSize[i]);
gridOffset[i] = gridOffset[i] * clutterRadius / resolution[i];
}
var curPos = [untransformX(mouseX), untransformY(mouseY)];
var curCell = [];
for (var i = 0; i < 2; i++) {
curCell[i] = Math.floor((curPos[i] + gridOffset[i] - minPt[i]) / gridSize[i]);
}
// console.log("---");
// console.log("pixel space: %3d, %3d, point space: %4.3f, %4.3f", mouseX, mouseY, curPos[0], curPos[1]);
// console.log("in gridcell %2d, %2d!", curCell[0], curCell[1]);
// get closest point
var nearestPt = pointTree.nearest({'x': curPos[0], 'y': curPos[1]}, 1)[0];
var grpColor = ds.colors[ds.groupNames.indexOf(nearestPt[0].grp)];
var cssColor = grpColor.map(function(c) { return Math.round(c * 255); }).join(",");
var detailStr = '<div class="legend-swatch" style="background-color: ';
detailStr += 'rgb(' + cssColor + ');"></div> ';
detailStr += '<strong>' + nearestPt[0].grp + "</strong><br />";
detailStr += "(" + nearestPt[0].x.toFixed(2) + ", " + nearestPt[0].y.toFixed(2) + ")";
$("#detail-text").html(detailStr);
}
};
gl.onmouseup = function(e) {
buttons[e.which] = false;
maxComputed = false;
gl.ondraw();
};
var drags = function(e) {
for (var b in buttons) {
if (Object.prototype.hasOwnProperty.call(buttons, b) && buttons[b]) return true;
}
};
// Handle zooming in and out.
var mwheel = function(e, delta, deltaX, deltaY) {
e.preventDefault();
var x = e.offsetX;
var y = gl.canvas.height - e.offsetY;
offset[0] = -(untransformX(x));
offset[1] = -(untransformY(y));
scale = deltaY > 0 ? scale / 0.9 : scale * 0.9;
screenOffset[0] = x;
screenOffset[1] = y;
// Force recomputation of the maximum value textures when zooming to preserve some sort of thresholded region.
maxComputed = false;
gl.ondraw();
};
/* some transforms */
var untransformX = function(x) {
return (x - screenOffset[0]) / scale - offset[0];
};
var untransformY = function(y) {
return (y - screenOffset[1]) / scale - offset[1];
};
var transformX = function(x) {
return (x + offset[0]) * scale + screenOffset[0];
};
var transformY = function(y) {
return (y + offset[1]) * scale + screenOffset[1];
};
var context2d;
var numLines = 9;
var draw2d = function() {
//context2d.fillStyle = "#fff";
//context2d.fillRect(0, 0, gl.canvas.width, gl.canvas.height);
context2d.clearRect(0, 0, gl.canvas.width, gl.canvas.height);
context2d.font = "25px sans-serif;";
// context2d.fillText("TESTING", 20, 30);
context2d.save();
context2d.strokeStyle = "rgba(0.56,0.56,0.56,0.5)";
context2d.lineWidth = 1;
var digitDisplay = function(num, exp, d) {
if (exp > 0)
return "" + Math.round(num/d) * d;
else {
var printNum = "" + Math.round(num/d) * d;
if (printNum.indexOf(".") == -1)
return printNum;
else
return printNum.substring(0, printNum.indexOf(".") + 1 + Math.abs(exp - 1));
}
};
// do minor lines first
var min = untransformY(0), max = untransformY(gl.canvas.height);
var exp = Math.floor(Math.log(max - min) / Math.log(10));
var d = Math.pow(10, exp) * 0.1;
var alpha = (1 - (150 - d * scale) / 150)
alpha = Math.max(0.0, Math.min(1.0, alpha)) / 2;
context2d.globalAlpha = alpha;
var graphMin = Math.floor(min / d) * d;
var graphMax = Math.ceil(max / d) * d;
for (var y = graphMin; y < graphMax + 0.5*d; y += d) {