/
black-hole.js
2171 lines (1950 loc) · 77.2 KB
/
black-hole.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
/////////////////////
// Black hole solver
/////////////////////
window.BlackHoleSolver = {};
(function (exports, numeric) {
// exports
exports.computeBlackHoleAngleFunction = function (startRadius, polynomialDegree, numAngleDataPoints, fovAngle, optionalNumIterationsInODESolver) {
// To prevent warping for pixels far from the black hole, solve for angles well beyond the fov so
// that the polynomial fits data well for angles near the fov limit.
var degreesBufferBeyondFov = 45;
var maxAngleToCompute = fovAngle + degreesBufferBeyondFov;
var angleTables = computeBlackHoleTables(startRadius, numAngleDataPoints, maxAngleToCompute, optionalNumIterationsInODESolver);
// We want to find coefficients for a good polynomial function that matches the data.
// We do so by finding coeffs that minimize sum of differences^2 btwn polynomial output
// and actual outAngles table result.
var polynomial = function (params, x) {
var sum = 0.0;
for (var i = 0; i <= polynomialDegree; i++) {
sum += params[i] * Math.pow(x, i);
}
return sum;
}
var initialCoeffs = [];
for (var i = 0; i <= polynomialDegree; i++) {
initialCoeffs.push(1.0);
}
var leastSquaresObjective = function (params) {
var total = 0.0;
for (var i = 0; i < angleTables.inAngles.length; i++) {
var result = polynomial(params, angleTables.inAngles[i]);
var delta = result - angleTables.outAngles[i];
total += (delta * delta);
}
return total;
}
var minimizer = numeric.uncmin(leastSquaresObjective, initialCoeffs);
return {
anglePolynomialCoefficients: minimizer.solution,
maxInBlackHoleAngle: angleTables.maxInBlackHoleAngle
};
}
var computeBlackHoleTables = function (startRadius, numAngleDataPoints, maxAngle, optionalNumIterationsInODESolver) {
var angleStep = maxAngle / numAngleDataPoints;
var inAngles = [];
for (var angle = 0.0; angle < maxAngle; angle += angleStep) {
inAngles.push(angle);
}
var outAngleResults = getOutAngleResultsTableForInAngles(inAngles, startRadius, optionalNumIterationsInODESolver);
// Find the largest value that will fall into the black hole.
var maxInBlackHoleAngle = 0;
var retInAngles = [];
var retOutAngles = [];
for (var i = 0; i < inAngles.length; i++) {
if (outAngleResults[i].inBlackHole) {
maxInBlackHoleAngle = inAngles[i];
} else if (!isNaN(inAngles[i]) && !isNaN(outAngleResults[i].angle)){
retInAngles.push(inAngles[i] + Math.PI);
var outAngle = outAngleResults[i].angle;
// Want angle to be measured from axis toward black hole, not axis toward viewer.
if (outAngle < 0) {
outAngle = -180 - outAngle
} else {
outAngle = 180 - outAngle
}
retOutAngles.push(outAngle);
}
}
return {
maxInBlackHoleAngle: degreesToRadians(maxInBlackHoleAngle),
inAngles: retInAngles.map(degreesToRadians),
outAngles: retOutAngles.map(degreesToRadians)
};
}
var degreesToRadians = function (degrees) {
return degrees * Math.PI / 180;
}
// helpers
var getOutAngleResultsTableForInAngles = function (angles, startRadius, optionalNumIterations) {
return angles.map(function (angle) {
return getBlackHoleSolution(angle, startRadius, 0, 20 * Math.PI, optionalNumIterations);
}).map(function (sol) {
return getXYPhotonPathFromSolution(sol);
}).map(function (photonPath) {
if (endsInVicinityOfBlackHole(photonPath)) {
return {inBlackHole: true};
}
var finalSlope = getFinalSlope(photonPath);
var ret = {
angle: getAngleFromSlope(finalSlope)
};
return ret;
});
}
var plotPhotonPathsForAngles = function (angles, startRadius, optionalNumIterations) {
if (!window.workshop) {
throw "numeric.js `workshop` must be defined to plot photon paths for angles. Copy the solver functions into the workshop on the numeric.js website and run this again to see a plot."
}
var angleTable = {};
var photonPaths = angles.map(function (angle) {
return getBlackHoleSolution(angle, startRadius, 0, 20 * Math.PI, optionalNumIterations);
}).map(function (sol) {
return getXYPhotonPathFromSolution(sol);
});
workshop.plot(photonPaths, { xaxis: { min: -1 * startRadius, max: startRadius }, yaxis: { min: -1 * startRadius, max: startRadius } });
}
var getXYPhotonPathFromSolution = function (sol) {
var rValues = numeric.transpose(sol.y)[0].map(function (val) {
return 1 / val;
});
var thetaValues = sol.x;
var photonPath = [];
for (var i = 0; i < rValues.length; i++) {
if (rValues[i] < 0) break;
var x = rValues[i] * Math.cos(thetaValues[i]);
var y = rValues[i] * Math.sin(thetaValues[i]);
photonPath.push([x, y]);
}
return photonPath;
}
var endsInVicinityOfBlackHole = function(photonPath) {
if (photonPath.length < 1) throw "At least one photonPath coord required to compute whether ends in vicinity of black hole";
var last = photonPath[photonPath.length - 1];
var x = last[0];
var y = last[1];
return Math.abs(x) < 1 && Math.abs(y) < 1;
}
var getFinalSlope = function (photonPath) {
if (photonPath.length < 2) throw "Not enough photonPath coords to compute a slope!";
var a = photonPath[photonPath.length - 2];
var b = photonPath[photonPath.length - 1];
return {
xComponent: b[0] - a[0],
yComponent: b[1] - a[1]
};
}
var getAngleFromSlope = function (slope) {
var angleInRad = Math.atan2(slope.yComponent, slope.xComponent);
var angleInDegrees = angleInRad * 180 / Math.PI;
return angleInDegrees;
}
var getBlackHoleSolution = function (startAngleDegrees, startRadius, startT, endT, optionalNumIterations) {
var numIterations = optionalNumIterations || 100;
return numeric.dopri(
startT,
endT,
[1.0/startRadius, 1/(startRadius * Math.tan(startAngleDegrees * Math.PI / 180.0))],
blackHoleSystem,
undefined,
numIterations
);
}
var blackHoleSystem = function (t, x) {
var u = x[0];
var u_prime = x[1];
var u_double_prime = 3*u*u - u;
return [u_prime, u_double_prime];
}
})(window.BlackHoleSolver, window.numeric);
///////////////////
// Draw black hole
///////////////////
window.BlackHole = {};
(function (exports, BlackHoleSolver) {
window.counter = 0;
// exports
exports.blackHoleifyImage = function (canvasId, backgroundImageSrc, opt) {
var image = new Image();
image.crossOrigin = 'Anonymous';
image.onload = function() {
init(canvasId, image, opt);
}
image.src = backgroundImageSrc;
}
var init = function (placeholderId, image, opt) {
var placeholder = document.getElementById(placeholderId);
try {
var canvas = fx.canvas();
} catch (e) {
placeholder.innerHTML = e;
return;
}
var texture = canvas.texture(image);
canvas.draw(texture).update().replace(placeholder);
opt = opt || {};
var distanceFromBlackHole = opt['distanceFromBlackHole'] || 80;
var polynomialDegree = opt['polynomialDegree'] || 2;
var numAngleTableEntries = opt['numAngleTableEntries'] || 1000;
var fovAngleInDegrees = opt['fovAngleInDegrees'] || 73;
var fovAngleInRadians = fovAngleInDegrees * Math.PI / 180;
var blackHoleAngleFn = BlackHoleSolver.computeBlackHoleAngleFunction(distanceFromBlackHole, polynomialDegree, numAngleTableEntries, fovAngleInDegrees);
var blackHoleVisible = false;
$(canvas).mousemove(function (evt) {
var offset = $(canvas).offset();
var x = evt.pageX - offset.left;
var y = evt.pageY - offset.top;
canvas.draw(texture).blackHole(x, y, blackHoleAngleFn, fovAngleInRadians).update();
blackHoleVisible = true;
});
$(canvas).mouseleave(function (evt) {
if (blackHoleVisible) {
canvas.draw(texture).update();
blackHoleVisible = false;
}
});
}
})(window.BlackHole, window.BlackHoleSolver);
////////////////////////////////////////
// modified-glfx.js
////////////////////////////////////////
/*
* MODIFIED version of glfx.js - can render black holes.
*
* glfx.js
* http://evanw.github.com/glfx.js/
*
* Copyright 2011 Evan Wallace
* Released under the MIT license
*/
var fx = (function() {
var exports = {};
// src/OES_texture_float_linear-polyfill.js
// From: https://github.com/evanw/OES_texture_float_linear-polyfill
(function() {
// Uploads a 2x2 floating-point texture where one pixel is 2 and the other
// three pixels are 0. Linear filtering is only supported if a sample taken
// from the center of that texture is (2 + 0 + 0 + 0) / 4 = 0.5.
function supportsOESTextureFloatLinear(gl) {
// Need floating point textures in the first place
if (!gl.getExtension('OES_texture_float')) {
return false;
}
// Create a render target
var framebuffer = gl.createFramebuffer();
var byteTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, byteTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, byteTexture, 0);
// Create a simple floating-point texture with value of 0.5 in the center
var rgba = [
2, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
];
var floatTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, floatTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.FLOAT, new Float32Array(rgba));
// Create the test shader
var program = gl.createProgram();
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(vertexShader, '\
attribute vec2 vertex;\
void main() {\
gl_Position = vec4(vertex, 0.0, 1.0);\
}\
');
gl.shaderSource(fragmentShader, '\
uniform sampler2D texture;\
void main() {\
gl_FragColor = texture2D(texture, vec2(0.5));\
}\
');
gl.compileShader(vertexShader);
gl.compileShader(fragmentShader);
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
// Create a buffer containing a single point
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0]), gl.STREAM_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
// Render the point and read back the rendered pixel
var pixel = new Uint8Array(4);
gl.useProgram(program);
gl.viewport(0, 0, 1, 1);
gl.bindTexture(gl.TEXTURE_2D, floatTexture);
gl.drawArrays(gl.POINTS, 0, 1);
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
// The center sample will only have a value of 0.5 if linear filtering works
return pixel[0] === 127 || pixel[0] === 128;
}
// The constructor for the returned extension object
function OESTextureFloatLinear() {
}
// Cache the extension so it's specific to each context like extensions should be
function getOESTextureFloatLinear(gl) {
if (gl.$OES_texture_float_linear$ === void 0) {
Object.defineProperty(gl, '$OES_texture_float_linear$', {
enumerable: false,
configurable: false,
writable: false,
value: new OESTextureFloatLinear()
});
}
return gl.$OES_texture_float_linear$;
}
// This replaces the real getExtension()
function getExtension(name) {
return name === 'OES_texture_float_linear'
? getOESTextureFloatLinear(this)
: oldGetExtension.call(this, name);
}
// This replaces the real getSupportedExtensions()
function getSupportedExtensions() {
var extensions = oldGetSupportedExtensions.call(this);
if (extensions.indexOf('OES_texture_float_linear') === -1) {
extensions.push('OES_texture_float_linear');
}
return extensions;
}
// Get a WebGL context
try {
var gl = document.createElement('canvas').getContext('experimental-webgl');
} catch (e) {
}
// Don't install the polyfill if the browser already supports it or doesn't have WebGL
if (!gl || gl.getSupportedExtensions().indexOf('OES_texture_float_linear') !== -1) {
return;
}
// Install the polyfill if linear filtering works with floating-point textures
if (supportsOESTextureFloatLinear(gl)) {
var oldGetExtension = WebGLRenderingContext.prototype.getExtension;
var oldGetSupportedExtensions = WebGLRenderingContext.prototype.getSupportedExtensions;
WebGLRenderingContext.prototype.getExtension = getExtension;
WebGLRenderingContext.prototype.getSupportedExtensions = getSupportedExtensions;
}
}());
// src/core\canvas.js
var gl;
function clamp(lo, value, hi) {
return Math.max(lo, Math.min(value, hi));
}
function wrapTexture(texture) {
return {
_: texture,
loadContentsOf: function(element) {
// Make sure that we're using the correct global WebGL context
gl = this._.gl;
this._.loadContentsOf(element);
},
destroy: function() {
// Make sure that we're using the correct global WebGL context
gl = this._.gl;
this._.destroy();
}
};
}
function texture(element) {
return wrapTexture(Texture.fromElement(element));
}
function initialize(width, height) {
var type = gl.UNSIGNED_BYTE;
// Go for floating point buffer textures if we can, it'll make the bokeh
// filter look a lot better. Note that on Windows, ANGLE does not let you
// render to a floating-point texture when linear filtering is enabled.
// See http://crbug.com/172278 for more information.
if (gl.getExtension('OES_texture_float') && gl.getExtension('OES_texture_float_linear')) {
var testTexture = new Texture(100, 100, gl.RGBA, gl.FLOAT);
try {
// Only use gl.FLOAT if we can render to it
testTexture.drawTo(function() { type = gl.FLOAT; });
} catch (e) {
}
testTexture.destroy();
}
if (this._.texture) this._.texture.destroy();
if (this._.spareTexture) this._.spareTexture.destroy();
this.width = width;
this.height = height;
this._.texture = new Texture(width, height, gl.RGBA, type);
this._.spareTexture = new Texture(width, height, gl.RGBA, type);
this._.extraTexture = this._.extraTexture || new Texture(0, 0, gl.RGBA, type);
this._.flippedShader = this._.flippedShader || new Shader(null, '\
uniform sampler2D texture;\
varying vec2 texCoord;\
void main() {\
gl_FragColor = texture2D(texture, vec2(texCoord.x, 1.0 - texCoord.y));\
}\
');
this._.isInitialized = true;
}
/*
Draw a texture to the canvas, with an optional width and height to scale to.
If no width and height are given then the original texture width and height
are used.
*/
function draw(texture, width, height) {
if (!this._.isInitialized || texture._.width != this.width || texture._.height != this.height) {
initialize.call(this, width ? width : texture._.width, height ? height : texture._.height);
}
texture._.use();
this._.texture.drawTo(function() {
Shader.getDefaultShader().drawRect();
});
return this;
}
function update() {
this._.texture.use();
this._.flippedShader.drawRect();
return this;
}
function simpleShader(shader, uniforms, textureIn, textureOut) {
(textureIn || this._.texture).use();
this._.spareTexture.drawTo(function() {
shader.uniforms(uniforms).drawRect();
});
this._.spareTexture.swapWith(textureOut || this._.texture);
}
function replace(node) {
node.parentNode.insertBefore(this, node);
node.parentNode.removeChild(node);
return this;
}
function contents() {
var texture = new Texture(this._.texture.width, this._.texture.height, gl.RGBA, gl.UNSIGNED_BYTE);
this._.texture.use();
texture.drawTo(function() {
Shader.getDefaultShader().drawRect();
});
return wrapTexture(texture);
}
/*
Get a Uint8 array of pixel values: [r, g, b, a, r, g, b, a, ...]
Length of the array will be width * height * 4.
*/
function getPixelArray() {
var w = this._.texture.width;
var h = this._.texture.height;
var array = new Uint8Array(w * h * 4);
this._.texture.drawTo(function() {
gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, array);
});
return array;
}
function wrap(func) {
return function() {
// Make sure that we're using the correct global WebGL context
gl = this._.gl;
// Now that the context has been switched, we can call the wrapped function
return func.apply(this, arguments);
};
}
exports.canvas = function() {
var canvas = document.createElement('canvas');
try {
gl = canvas.getContext('experimental-webgl', { premultipliedAlpha: false });
} catch (e) {
gl = null;
}
if (!gl) {
throw 'This browser does not support WebGL';
}
canvas._ = {
gl: gl,
isInitialized: false,
texture: null,
spareTexture: null,
flippedShader: null
};
// Core methods
canvas.texture = wrap(texture);
canvas.draw = wrap(draw);
canvas.update = wrap(update);
canvas.replace = wrap(replace);
canvas.contents = wrap(contents);
canvas.getPixelArray = wrap(getPixelArray);
// Filter methods
canvas.brightnessContrast = wrap(brightnessContrast);
canvas.hexagonalPixelate = wrap(hexagonalPixelate);
canvas.hueSaturation = wrap(hueSaturation);
canvas.colorHalftone = wrap(colorHalftone);
canvas.triangleBlur = wrap(triangleBlur);
canvas.unsharpMask = wrap(unsharpMask);
canvas.perspective = wrap(perspective);
canvas.matrixWarp = wrap(matrixWarp);
canvas.bulgePinch = wrap(bulgePinch);
canvas.tiltShift = wrap(tiltShift);
canvas.dotScreen = wrap(dotScreen);
canvas.edgeWork = wrap(edgeWork);
canvas.lensBlur = wrap(lensBlur);
canvas.zoomBlur = wrap(zoomBlur);
canvas.noise = wrap(noise);
canvas.denoise = wrap(denoise);
canvas.curves = wrap(curves);
canvas.swirl = wrap(swirl);
canvas.ink = wrap(ink);
canvas.vignette = wrap(vignette);
canvas.vibrance = wrap(vibrance);
canvas.sepia = wrap(sepia);
// custom
canvas.blackHole = wrap(blackHole);
return canvas;
};
exports.splineInterpolate = splineInterpolate;
// src/core\matrix.js
// from javax.media.jai.PerspectiveTransform
function getSquareToQuad(x0, y0, x1, y1, x2, y2, x3, y3) {
var dx1 = x1 - x2;
var dy1 = y1 - y2;
var dx2 = x3 - x2;
var dy2 = y3 - y2;
var dx3 = x0 - x1 + x2 - x3;
var dy3 = y0 - y1 + y2 - y3;
var det = dx1*dy2 - dx2*dy1;
var a = (dx3*dy2 - dx2*dy3) / det;
var b = (dx1*dy3 - dx3*dy1) / det;
return [
x1 - x0 + a*x1, y1 - y0 + a*y1, a,
x3 - x0 + b*x3, y3 - y0 + b*y3, b,
x0, y0, 1
];
}
function getInverse(m) {
var a = m[0], b = m[1], c = m[2];
var d = m[3], e = m[4], f = m[5];
var g = m[6], h = m[7], i = m[8];
var det = a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
return [
(e*i - f*h) / det, (c*h - b*i) / det, (b*f - c*e) / det,
(f*g - d*i) / det, (a*i - c*g) / det, (c*d - a*f) / det,
(d*h - e*g) / det, (b*g - a*h) / det, (a*e - b*d) / det
];
}
function multiply(a, b) {
return [
a[0]*b[0] + a[1]*b[3] + a[2]*b[6],
a[0]*b[1] + a[1]*b[4] + a[2]*b[7],
a[0]*b[2] + a[1]*b[5] + a[2]*b[8],
a[3]*b[0] + a[4]*b[3] + a[5]*b[6],
a[3]*b[1] + a[4]*b[4] + a[5]*b[7],
a[3]*b[2] + a[4]*b[5] + a[5]*b[8],
a[6]*b[0] + a[7]*b[3] + a[8]*b[6],
a[6]*b[1] + a[7]*b[4] + a[8]*b[7],
a[6]*b[2] + a[7]*b[5] + a[8]*b[8]
];
}
// src/core\shader.js
var Shader = (function() {
function isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
function isNumber(obj) {
return Object.prototype.toString.call(obj) == '[object Number]';
}
function compileSource(type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw 'compile error: ' + gl.getShaderInfoLog(shader);
}
return shader;
}
var defaultVertexSource = '\
attribute vec2 vertex;\
attribute vec2 _texCoord;\
varying vec2 texCoord;\
void main() {\
texCoord = _texCoord;\
gl_Position = vec4(vertex * 2.0 - 1.0, 0.0, 1.0);\
}';
var defaultFragmentSource = '\
uniform sampler2D texture;\
varying vec2 texCoord;\
void main() {\
gl_FragColor = texture2D(texture, texCoord);\
}';
function Shader(vertexSource, fragmentSource) {
this.vertexAttribute = null;
this.texCoordAttribute = null;
this.program = gl.createProgram();
vertexSource = vertexSource || defaultVertexSource;
fragmentSource = fragmentSource || defaultFragmentSource;
fragmentSource = 'precision highp float;' + fragmentSource; // annoying requirement is annoying
gl.attachShader(this.program, compileSource(gl.VERTEX_SHADER, vertexSource));
gl.attachShader(this.program, compileSource(gl.FRAGMENT_SHADER, fragmentSource));
gl.linkProgram(this.program);
if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) {
throw 'link error: ' + gl.getProgramInfoLog(this.program);
}
}
Shader.prototype.destroy = function() {
gl.deleteProgram(this.program);
this.program = null;
};
Shader.prototype.uniforms = function(uniforms) {
gl.useProgram(this.program);
for (var name in uniforms) {
if (!uniforms.hasOwnProperty(name)) continue;
var location = gl.getUniformLocation(this.program, name);
if (location === null) continue; // will be null if the uniform isn't used in the shader
var value = uniforms[name];
if (value.uniformVectorType) {
gl[value.uniformVectorType](location, new Float32Array(value.value));
} else if (isArray(value)) {
switch (value.length) {
case 1: gl.uniform1fv(location, new Float32Array(value)); break;
case 2: gl.uniform2fv(location, new Float32Array(value)); break;
case 3: gl.uniform3fv(location, new Float32Array(value)); break;
case 4: gl.uniform4fv(location, new Float32Array(value)); break;
case 9: gl.uniformMatrix3fv(location, false, new Float32Array(value)); break;
case 16: gl.uniformMatrix4fv(location, false, new Float32Array(value)); break;
default: throw 'dont\'t know how to load uniform "' + name + '" of length ' + value.length;
}
} else if (isNumber(value)) {
gl.uniform1f(location, value);
} else {
throw 'attempted to set uniform "' + name + '" to invalid value ' + (value || 'undefined').toString();
}
}
// allow chaining
return this;
};
// textures are uniforms too but for some reason can't be specified by gl.uniform1f,
// even though floating point numbers represent the integers 0 through 7 exactly
Shader.prototype.textures = function(textures) {
gl.useProgram(this.program);
for (var name in textures) {
if (!textures.hasOwnProperty(name)) continue;
gl.uniform1i(gl.getUniformLocation(this.program, name), textures[name]);
}
// allow chaining
return this;
};
Shader.prototype.drawRect = function(left, top, right, bottom) {
var undefined;
var viewport = gl.getParameter(gl.VIEWPORT);
top = top !== undefined ? (top - viewport[1]) / viewport[3] : 0;
left = left !== undefined ? (left - viewport[0]) / viewport[2] : 0;
right = right !== undefined ? (right - viewport[0]) / viewport[2] : 1;
bottom = bottom !== undefined ? (bottom - viewport[1]) / viewport[3] : 1;
if (gl.vertexBuffer == null) {
gl.vertexBuffer = gl.createBuffer();
}
gl.bindBuffer(gl.ARRAY_BUFFER, gl.vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ left, top, left, bottom, right, top, right, bottom ]), gl.STATIC_DRAW);
if (gl.texCoordBuffer == null) {
gl.texCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, gl.texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, 0, 1, 1, 0, 1, 1 ]), gl.STATIC_DRAW);
}
if (this.vertexAttribute == null) {
this.vertexAttribute = gl.getAttribLocation(this.program, 'vertex');
gl.enableVertexAttribArray(this.vertexAttribute);
}
if (this.texCoordAttribute == null) {
this.texCoordAttribute = gl.getAttribLocation(this.program, '_texCoord');
gl.enableVertexAttribArray(this.texCoordAttribute);
}
gl.useProgram(this.program);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.vertexBuffer);
gl.vertexAttribPointer(this.vertexAttribute, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.texCoordBuffer);
gl.vertexAttribPointer(this.texCoordAttribute, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
};
Shader.getDefaultShader = function() {
gl.defaultShader = gl.defaultShader || new Shader();
return gl.defaultShader;
};
return Shader;
})();
// src/core\spline.js
// from SplineInterpolator.cs in the Paint.NET source code
function SplineInterpolator(points) {
var n = points.length;
this.xa = [];
this.ya = [];
this.u = [];
this.y2 = [];
points.sort(function(a, b) {
return a[0] - b[0];
});
for (var i = 0; i < n; i++) {
this.xa.push(points[i][0]);
this.ya.push(points[i][1]);
}
this.u[0] = 0;
this.y2[0] = 0;
for (var i = 1; i < n - 1; ++i) {
// This is the decomposition loop of the tridiagonal algorithm.
// y2 and u are used for temporary storage of the decomposed factors.
var wx = this.xa[i + 1] - this.xa[i - 1];
var sig = (this.xa[i] - this.xa[i - 1]) / wx;
var p = sig * this.y2[i - 1] + 2.0;
this.y2[i] = (sig - 1.0) / p;
var ddydx =
(this.ya[i + 1] - this.ya[i]) / (this.xa[i + 1] - this.xa[i]) -
(this.ya[i] - this.ya[i - 1]) / (this.xa[i] - this.xa[i - 1]);
this.u[i] = (6.0 * ddydx / wx - sig * this.u[i - 1]) / p;
}
this.y2[n - 1] = 0;
// This is the backsubstitution loop of the tridiagonal algorithm
for (var i = n - 2; i >= 0; --i) {
this.y2[i] = this.y2[i] * this.y2[i + 1] + this.u[i];
}
}
SplineInterpolator.prototype.interpolate = function(x) {
var n = this.ya.length;
var klo = 0;
var khi = n - 1;
// We will find the right place in the table by means of
// bisection. This is optimal if sequential calls to this
// routine are at random values of x. If sequential calls
// are in order, and closely spaced, one would do better
// to store previous values of klo and khi.
while (khi - klo > 1) {
var k = (khi + klo) >> 1;
if (this.xa[k] > x) {
khi = k;
} else {
klo = k;
}
}
var h = this.xa[khi] - this.xa[klo];
var a = (this.xa[khi] - x) / h;
var b = (x - this.xa[klo]) / h;
// Cubic spline polynomial is now evaluated.
return a * this.ya[klo] + b * this.ya[khi] +
((a * a * a - a) * this.y2[klo] + (b * b * b - b) * this.y2[khi]) * (h * h) / 6.0;
};
// src/core\texture.js
var Texture = (function() {
Texture.fromElement = function(element) {
var texture = new Texture(0, 0, gl.RGBA, gl.UNSIGNED_BYTE);
texture.loadContentsOf(element);
return texture;
};
function Texture(width, height, format, type) {
this.gl = gl;
this.id = gl.createTexture();
this.width = width;
this.height = height;
this.format = format;
this.type = type;
gl.bindTexture(gl.TEXTURE_2D, this.id);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
if (width && height) gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, null);
}
Texture.prototype.loadContentsOf = function(element) {
this.width = element.width || element.videoWidth;
this.height = element.height || element.videoHeight;
gl.bindTexture(gl.TEXTURE_2D, this.id);
gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, element);
};
Texture.prototype.initFromBytes = function(width, height, data) {
this.width = width;
this.height = height;
this.format = gl.RGBA;
this.type = gl.UNSIGNED_BYTE;
gl.bindTexture(gl.TEXTURE_2D, this.id);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, this.type, new Uint8Array(data));
};
Texture.prototype.destroy = function() {
gl.deleteTexture(this.id);
this.id = null;
};
Texture.prototype.use = function(unit) {
gl.activeTexture(gl.TEXTURE0 + (unit || 0));
gl.bindTexture(gl.TEXTURE_2D, this.id);
};
Texture.prototype.unuse = function(unit) {
gl.activeTexture(gl.TEXTURE0 + (unit || 0));
gl.bindTexture(gl.TEXTURE_2D, null);
};
Texture.prototype.ensureFormat = function(width, height, format, type) {
// allow passing an existing texture instead of individual arguments
if (arguments.length == 1) {
var texture = arguments[0];
width = texture.width;
height = texture.height;
format = texture.format;
type = texture.type;
}
// change the format only if required
if (width != this.width || height != this.height || format != this.format || type != this.type) {
this.width = width;
this.height = height;
this.format = format;
this.type = type;
gl.bindTexture(gl.TEXTURE_2D, this.id);
gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, null);
}
};
Texture.prototype.drawTo = function(callback) {
// start rendering to this texture
gl.framebuffer = gl.framebuffer || gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, gl.framebuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.id, 0);
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
throw new Error('incomplete framebuffer');
}
gl.viewport(0, 0, this.width, this.height);
// do the drawing
callback();
// stop rendering to this texture
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
};
var canvas = null;
function getCanvas(texture) {
if (canvas == null) canvas = document.createElement('canvas');
canvas.width = texture.width;
canvas.height = texture.height;
var c = canvas.getContext('2d');
c.clearRect(0, 0, canvas.width, canvas.height);
return c;
}
Texture.prototype.fillUsingCanvas = function(callback) {
callback(getCanvas(this));
this.format = gl.RGBA;
this.type = gl.UNSIGNED_BYTE;
gl.bindTexture(gl.TEXTURE_2D, this.id);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, canvas);
return this;
};
Texture.prototype.toImage = function(image) {
this.use();
Shader.getDefaultShader().drawRect();
var size = this.width * this.height * 4;
var pixels = new Uint8Array(size);
var c = getCanvas(this);
var data = c.createImageData(this.width, this.height);
gl.readPixels(0, 0, this.width, this.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
for (var i = 0; i < size; i++) {
data.data[i] = pixels[i];
}
c.putImageData(data, 0, 0);
image.src = canvas.toDataURL();
};
Texture.prototype.swapWith = function(other) {
var temp;
temp = other.id; other.id = this.id; this.id = temp;
temp = other.width; other.width = this.width; this.width = temp;
temp = other.height; other.height = this.height; this.height = temp;
temp = other.format; other.format = this.format; this.format = temp;
};
return Texture;
})();
// src/filters\common.js
function warpShader(uniforms, warp) {
return new Shader(null, uniforms + '\
uniform sampler2D texture;\
uniform vec2 texSize;\
varying vec2 texCoord;\
void main() {\
vec2 coord = texCoord * texSize;\
' + warp + '\
gl_FragColor = texture2D(texture, coord / texSize);\
vec2 clampedCoord = clamp(coord, vec2(0.0), texSize);\
if (coord != clampedCoord) {\
/* fade to transparent if we are outside the image */\
gl_FragColor.a *= max(0.0, 1.0 - length(coord - clampedCoord));\
}\
}');
}
// returns a random number between 0 and 1
var randomShaderFunc = '\
float random(vec3 scale, float seed) {\
/* use the fragment position for a different seed per-pixel */\
return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);\
}\
';
// src/filters\adjust\brightnesscontrast.js
/**
* @filter Brightness / Contrast