enable zooming in mandelbrot app and add a few other things to the code for later...
[mandelbrot-web.git] / js / mandelbrot.js
1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3  *
4  * The contents of this file are subject to the Mozilla Public License Version
5  * 1.1 (the "License"); you may not use this file except in compliance with
6  * the License. You may obtain a copy of the License at
7  * http://www.mozilla.org/MPL/
8  *
9  * Software distributed under the License is distributed on an "AS IS" basis,
10  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11  * for the specific language governing rights and limitations under the
12  * License.
13  *
14  * The Original Code is KaiRo.at Mandelbrot, XULRunner version.
15  *
16  * The Initial Developer of the Original Code is
17  * Robert Kaiser <kairo@kairo.at>.
18  * Portions created by the Initial Developer are Copyright (C) 2008-210
19  * the Initial Developer. All Rights Reserved.
20  *
21  * Contributor(s):
22  *   Robert Kaiser <kairo@kairo.at>
23  *   Boris Zbarsky <bzbarsky@mit.edu>
24  *
25  * Alternatively, the contents of this file may be used under the terms of
26  * either the GNU General Public License Version 2 or later (the "GPL"), or
27  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28  * in which case the provisions of the GPL or the LGPL are applicable instead
29  * of those above. If you wish to allow use of your version of this file only
30  * under the terms of either the GPL or the LGPL, and not to allow others to
31  * use your version of this file under the terms of the MPL, indicate your
32  * decision by deleting the provisions above and replace them with the notice
33  * and other provisions required by the GPL or the LGPL. If you do not delete
34  * the provisions above, a recipient may use your version of this file under
35  * the terms of any one of the MPL, the GPL or the LGPL.
36  *
37  * ***** END LICENSE BLOCK ***** */
38
39 var gColorPalette = [];
40 var gStartTime = 0;
41 var gCurrentImageData;
42 var gLastImageData;
43
44 function Startup() {
45   var img = document.getElementById("mbrotImage");
46   img.addEventListener("mouseup", imgEvHandler, false);
47   img.addEventListener("mousedown", imgEvHandler, false);
48   img.addEventListener("mousemove", imgEvHandler, false);
49   img.addEventListener("touchstart", imgEvHandler, false);
50   img.addEventListener("touchend", imgEvHandler, false);
51   img.addEventListener("touchcancel", imgEvHandler, false);
52   img.addEventListener("touchleave", imgEvHandler, false);
53   img.addEventListener("touchmove", imgEvHandler, false);
54 }
55
56 function getAdjustVal(aName) {
57   var value;
58   switch (aName) {
59     case "image.width":
60     case "image.height":
61       value = 0;
62       try {
63         value = document.getElementById(aName.replace(".", "_")).value;
64       }
65       catch (e) { }
66       if ((value < 10) || (value > 5000)) {
67         value = 300;
68         //document.getElementById(aName.replace(".", "_")).value = value;
69       }
70       return value;
71     case "last_image.Cr_*":
72       var Cr_min = -2.0;
73       var Cr_max = 1.0;
74       try {
75         Cr_min = parseFloat(document.getElementById("Cr_min").value);
76         Cr_max = parseFloat(document.getElementById("Cr_max").value);
77       }
78       catch (e) { }
79       if ((Cr_min < -3) || (Cr_min > 2) ||
80           (Cr_max < -3) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
81         Cr_min = -2.0; Cr_max = 1.0;
82       }
83       document.getElementById("Cr_min").value = Cr_min;
84       document.getElementById("Cr_max").value = Cr_max;
85       return {Cr_min: Cr_min, Cr_max: Cr_max};
86     case "last_image.Ci_*":
87       var Ci_min = -1.5;
88       var Ci_max = 1.5;
89       try {
90         Ci_min = parseFloat(document.getElementById("Ci_min").value);
91         Ci_max = parseFloat(document.getElementById("Ci_max").value);
92       }
93       catch (e) { }
94       if ((Ci_min < -2.5) || (Ci_min > 2.5) ||
95           (Ci_max < -2.5) || (Ci_max > 2.5) || (Ci_min >= Ci_max)) {
96         Ci_min = -1.5; Ci_max = 1.5;
97       }
98       document.getElementById("Ci_min").value = Ci_min;
99       document.getElementById("Ci_max").value = Ci_max;
100       return {Ci_min: Ci_min, Ci_max: Ci_max};
101     case "iteration_max":
102       value = 500;
103       try {
104         value = document.getElementById("iterMax").value;
105       }
106       catch (e) {
107         setIter(value);
108       }
109       if (value < 10 || value > 10000) {
110         value = 500;
111         setIter(value);
112       }
113       return value;
114     case "use_algorithm":
115       value = "numeric";
116       try {
117         value = document.getElementById("algorithm").value;
118       }
119       catch (e) {
120         setAlgorithm(value);
121       }
122       return value;
123    case "color_palette":
124       value = "kairo";
125       try {
126         value = document.getElementById("palette").value;
127       }
128       catch(e) {
129         setPalette(value);
130       }
131       return value;
132    case "syncProportions":
133       value = true;
134       try {
135         value = document.getElementById("proportional").value;
136       }
137       catch(e) {
138         document.getElementById("proportional").value = value;
139       }
140       return value;
141     default:
142       return false;
143   }
144 }
145
146 function setVal(aName, aValue) {
147   switch (aName) {
148     case "image.width":
149     case "image.height":
150       document.getElementById(aName.replace(".", "_")).value = value;
151       break;
152     case "last_image.Cr_*":
153       document.getElementById("Cr_min").value = aValue.Cr_min;
154       document.getElementById("Cr_max").value = aValue.Cr_max;
155       break;
156     case "last_image.Ci_*":
157       document.getElementById("Ci_min").value = aValue.Ci_min;
158       document.getElementById("Ci_max").value = aValue.Ci_max;
159       break;
160     case "iteration_max":
161       setIter(aValue);
162       break;
163     case "use_algorithm":
164       setAlgorithm(aValue);
165       break;
166    case "color_palette":
167       setPalette(valueaValue);
168       break;
169    case "syncProportions":
170       document.getElementById("proportional").value = aValue;
171       break;
172   }
173 }
174
175 function adjustCoordsAndDraw(aC_min, aC_max) {
176   var iWidth = getAdjustVal("image.width");
177   var iHeight = getAdjustVal("image.height");
178
179   // correct coordinates
180   if (aC_min.r < -2)
181     aC_min.r = -2;
182   if (aC_max.r > 2)
183     aC_max.r = 2;
184   if ((aC_min.r > 2) || (aC_max.r < -2) || (aC_min.r >= aC_max.r)) {
185     aC_min.r = -2.0; aC_max.r = 1.0;
186   }
187   if (aC_min.i < -2)
188     aC_min.i = -2;
189   if (aC_max.i > 2)
190     aC_max.i = 2;
191   if ((aC_min.i > 2) || (aC_max.i < -2) || (aC_min.i >= aC_max.i)) {
192     aC_min.i = -1.3; aC_max.i = 1.3;
193   }
194
195   var CWidth = aC_max.r - aC_min.r;
196   var CHeight = aC_max.i - aC_min.i;
197   var C_mid = new complex(aC_min.r + CWidth / 2, aC_min.i + CHeight / 2);
198
199   var CRatio = Math.max(CWidth / iWidth, CHeight / iHeight);
200
201   setVal("last_image.Cr_*", {Cr_min: C_mid.r - iWidth * CRatio / 2,
202                              Cr_max: C_mid.r + iWidth * CRatio / 2});
203   setVal("last_image.Ci_*", {Ci_min: C_mid.i - iHeight * CRatio / 2,
204                              Ci_max: C_mid.i + iHeight * CRatio / 2});
205
206   drawImage();
207 }
208
209 function drawImage() {
210   var canvas = document.getElementById("mbrotImage");
211   var context = canvas.getContext("2d");
212
213   document.getElementById("calcTime").textContent = "--";
214
215   if (gCurrentImageData) {
216     gLastImageData = gCurrentImageData;
217   }
218
219   gColorPalette = getColorPalette(document.getElementById("palette").value);
220
221   var Cr_vals = getAdjustVal("last_image.Cr_*");
222   var Cr_min = Cr_vals.Cr_min;
223   var Cr_max = Cr_vals.Cr_max;
224
225   var Ci_vals = getAdjustVal("last_image.Ci_*");
226   var Ci_min = Ci_vals.Ci_min;
227   var Ci_max = Ci_vals.Ci_max;
228
229   var iterMax = getAdjustVal("iteration_max");
230   var algorithm = getAdjustVal("use_algorithm");
231
232   var iWidth = canvas.width;
233   if ((iWidth < 10) || (iWidth > 5000)) {
234     iWidth = 300;
235     canvas.width = iWidth;
236   }
237   var iHeight = canvas.height;
238   if ((iHeight < 10) || (iHeight > 5000)) {
239     iHeight = 300;
240     canvas.height = iHeight;
241   }
242
243   gCurrentImageData = {
244     C_min: new complex(Cr_min, Ci_min),
245     C_max: new complex(Cr_max, Ci_max),
246     iWidth: iWidth,
247     iHeight: iHeight,
248     iterMax: iterMax
249   };
250
251   context.fillStyle = "rgba(255, 255, 255, 127)";
252   context.fillRect(0, 0, canvas.width, canvas.height);
253
254   gStartTime = new Date();
255
256   drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
257               canvas, context, iterMax, algorithm);
258 }
259
260 function drawLine(line, dimensions, canvas, context, iterMax, algorithm) {
261     var Cr_min = dimensions[0];
262     var Cr_max = dimensions[1];
263     var Cr_scale = Cr_max - Cr_min;
264
265     var Ci_min = dimensions[2];
266     var Ci_max = dimensions[3];
267     var Ci_scale = Ci_max - Ci_min;
268
269     var lines = Math.min(canvas.height - line, 8);
270     var imageData = context.createImageData(canvas.width, lines);
271     var pixels = imageData.data;
272     var idx = 0;
273     for (var img_y = line; img_y < canvas.height && img_y < line+8; img_y++)
274       for (var img_x = 0; img_x < canvas.width; img_x++) {
275         var C = new complex(Cr_min + (img_x / canvas.width) * Cr_scale,
276                             Ci_min + (img_y / canvas.height) * Ci_scale);
277         var colors = drawPoint(context, img_x, img_y, C, iterMax, algorithm);
278         pixels[idx++] = colors[0];
279         pixels[idx++] = colors[1];
280         pixels[idx++] = colors[2];
281         pixels[idx++] = colors[3];
282       }
283     context.putImageData(imageData, 0, line);
284
285     if (img_y < canvas.height)
286       setTimeout(drawLine, 0, img_y, dimensions, canvas, context, iterMax, algorithm);
287     else if (gStartTime)
288       EndCalc();
289 }
290
291 function EndCalc() {
292   var endTime = new Date();
293   var timeUsed = (endTime.getTime() - gStartTime.getTime()) / 1000;
294   document.getElementById("calcTime").textContent = timeUsed.toFixed(3) + " seconds";
295 }
296
297 function complex(aReal, aImag) {
298   this.r = aReal;
299   this.i = aImag;
300 }
301 complex.prototype = {
302   square: function() {
303     return new complex(this.r * this.r - this.i * this.i,
304                        2 * this.r * this.i);
305   },
306   dist: function() {
307     return Math.sqrt(this.r * this.r + this.i * this.i);
308   },
309   add: function(aComplex) {
310     return new complex(this.r + aComplex.r, this.i + aComplex.i);
311   }
312 }
313
314 function mandelbrotValueOO (aC, aIterMax) {
315   // this would be nice code in general but it looks like JS objects are too heavy for normal use.
316   var Z = new complex(0.0, 0.0);
317   for (var iter = 0; iter < aIterMax; iter++) {
318     Z = Z.square().add(aC);
319     if (Z.r * Z.r + Z.i * Z.i > 256) { break; }
320   }
321   return iter;
322 }
323
324 function mandelbrotValueNumeric (aC, aIterMax) {
325   // optimized numeric code for fast calculation
326   var Cr = aC.r, Ci = aC.i;
327   var Zr = 0.0, Zi = 0.0;
328   var Zr2 = Zr * Zr, Zi2 = Zi * Zi;
329   for (var iter = 0; iter < aIterMax; iter++) {
330     Zi = 2 * Zr * Zi + Ci;
331     Zr = Zr2 - Zi2 + Cr;
332
333     Zr2 = Zr * Zr; Zi2 = Zi * Zi;
334     if (Zr2 + Zi2 > 256) { break; }
335   }
336   return iter;
337 }
338
339 function getColor(aIterValue, aIterMax) {
340   var standardizedValue = Math.round(aIterValue * 1024 / aIterMax);
341   if (gColorPalette && gColorPalette.length)
342     return gColorPalette[standardizedValue];
343
344   // fallback to simple b/w if for some reason we don't have a palette
345   if (aIterValue == aIterMax)
346     return [0, 0, 0, 255];
347   else
348     return [255, 255, 255, 255];
349 }
350
351 function getColorPalette(palName) {
352   var palette = [];
353   switch (palName) {
354     case 'bw':
355       for (var i = 0; i < 1024; i++) {
356         palette[i] = [255, 255, 255, 255];
357       }
358       palette[1024] = [0, 0, 0, 255];
359       break;
360     case 'kairo':
361       // outer areas
362       for (var i = 0; i < 32; i++) {
363         var cc1 = Math.floor(i * 127 / 31);
364         var cc2 = 170 - Math.floor(i * 43 / 31);
365         palette[i] = [cc1, cc2, cc1, 255];
366       }
367       // inner areas
368       for (var i = 0; i < 51; i++) {
369         var cc = Math.floor(i * 170 / 50);
370         palette[32 + i] = [cc, 0, (170-cc), 255];
371       }
372       // corona
373       for (var i = 0; i < 101; i++) {
374         var cc = Math.floor(i * 200 / 100);
375         palette[83 + i] = [255, cc, 0, 255];
376       }
377       // inner corona
378       for (var i = 0; i < 201; i++) {
379         var cc1 = 255 - Math.floor(i * 85 / 200);
380         var cc2 = 200 - Math.floor(i * 30 / 200);
381         var cc3 = Math.floor(i * 170 / 200);
382         palette[184 + i] = [cc1, cc2, cc3, 255];
383       }
384       for (var i = 0; i < 301; i++) {
385         var cc1 = 170 - Math.floor(i * 43 / 300);
386         var cc2 = 170 + Math.floor(i * 85 / 300);
387         palette[385 + i] = [cc1, cc1, cc2, 255];
388       }
389       for (var i = 0; i < 338; i++) {
390         var cc = 127 + Math.floor(i * 128 / 337);
391         palette[686 + i] = [cc, cc, 255, 255];
392       }
393       palette[1024] = [0, 0, 0, 255];
394       break;
395     case 'rainbow-linear1':
396       for (var i = 0; i < 256; i++) {
397         palette[i] = [i, 0, 0, 255];
398         palette[256 + i] = [255, i, 0, 255];
399         palette[512 + i] = [255 - i, 255, i, 255];
400         palette[768 + i] = [i, 255-i, 255, 255];
401       }
402       palette[1024] = [0, 0, 0, 255];
403       break;
404     case 'rainbow-squared1':
405       for (var i = 0; i < 34; i++) {
406         var cc = Math.floor(i * 255 / 33);
407         palette[i] = [cc, 0, 0, 255];
408       }
409       for (var i = 0; i < 137; i++) {
410         var cc = Math.floor(i * 255 / 136);
411         palette[34 + i] = [255, cc, 0, 255];
412       }
413       for (var i = 0; i < 307; i++) {
414         var cc = Math.floor(i * 255 / 306);
415         palette[171 + i] = [255 - cc, 255, cc, 255];
416       }
417       for (var i = 0; i < 546; i++) {
418         var cc = Math.floor(i * 255 / 545);
419         palette[478 + i] = [cc, 255 - cc, 255, 255];
420       }
421       palette[1024] = [0, 0, 0, 255];
422       break;
423     case 'rainbow-linear2':
424       for (var i = 0; i < 205; i++) {
425         var cc = Math.floor(i * 255 / 204);
426         palette[i] = [255, cc, 0, 255];
427         palette[204 + i] = [255 - cc, 255, 0, 255];
428         palette[409 + i] = [0, 255, cc, 255];
429         palette[614 + i] = [0, 255 - cc, 255, 255];
430         palette[819 + i] = [cc, 0, 255, 255];
431       }
432       palette[1024] = [0, 0, 0, 255];
433       break;
434     case 'rainbow-squared2':
435       for (var i = 0; i < 19; i++) {
436         var cc = Math.floor(i * 255 / 18);
437         palette[i] = [255, cc, 0, 255];
438       }
439       for (var i = 0; i < 74; i++) {
440         var cc = Math.floor(i * 255 / 73);
441         palette[19 + i] = [255 - cc, 255, 0, 255];
442       }
443       for (var i = 0; i < 168; i++) {
444         var cc = Math.floor(i * 255 / 167);
445         palette[93 + i] = [0, 255, cc, 255];
446       }
447       for (var i = 0; i < 298; i++) {
448         var cc = Math.floor(i * 255 / 297);
449         palette[261 + i] = [0, 255 - cc, 255, 255];
450       }
451       for (var i = 0; i < 465; i++) {
452         var cc = Math.floor(i * 255 / 464);
453         palette[559 + i] = [cc, 0, 255, 255];
454       }
455       palette[1024] = [0, 0, 0, 255];
456       break;
457   }
458   return palette;
459 }
460
461 function drawPoint(context, img_x, img_y, C, iterMax, algorithm) {
462   var itVal;
463   switch (algorithm) {
464     case 'oo':
465       itVal = mandelbrotValueOO(C, iterMax);
466       break;
467     case 'numeric':
468     default:
469       itVal = mandelbrotValueNumeric(C, iterMax);
470       break;
471   }
472   return getColor(itVal, iterMax);
473 }
474
475 // ########## UI functions ##########
476
477 var zoomstart;
478 var imgBackup;
479 var zoomTouchID;
480
481 var imgEvHandler = {
482   handleEvent: function(aEvent) {
483     var canvas = document.getElementById("mbrotImage");
484     var context = canvas.getContext("2d");
485     var touchEvent = aEvent.type.indexOf('touch') != -1;
486
487     // Bail out if this is neither a touch nor left-click.
488     if (!touchEvent && aEvent.button != 0)
489       return;
490
491     // Bail out if the started touch can't be found.
492     if (touchEvent && zoomstart &&
493         !aEvent.changedTouches.identifiedTouch(zoomTouchID))
494       return;
495
496     var coordObj = touchEvent ?
497                    aEvent.changedTouches.identifiedTouch(zoomTouchID) :
498                    aEvent;
499
500     switch (aEvent.type) {
501       case 'mousedown':
502       case 'touchstart':
503         if (touchEvent) {
504           zoomTouchID = aEvent.changedTouches.item(0).identifier;
505           coordObj = aEvent.changedTouches.identifiedTouch(zoomTouchID);
506         }
507         // left button - start dragzoom
508         zoomstart = {x: coordObj.clientX - canvas.offsetLeft,
509                      y: coordObj.clientY - canvas.offsetTop};
510         imgBackup = context.getImageData(0, 0, canvas.width, canvas.height);
511         break;
512       case 'mouseup':
513       case 'touchend':
514         if (zoomstart) {
515           context.putImageData(imgBackup, 0, 0);
516           var zoomend = {x: coordObj.clientX - canvas.offsetLeft,
517                          y: coordObj.clientY - canvas.offsetTop};
518
519           // make sure zoomend is bigger than zoomstart
520           if ((zoomend.x == zoomstart.x) || (zoomend.y == zoomstart.y)) {
521             // cannot zoom what has no area, discard it
522             zoomstart = undefined;
523             return;
524           }
525           if (zoomend.x < zoomstart.x)
526             [zoomend.x, zoomstart.x] = [zoomstart.x, zoomend.x];
527           if (zoomend.y < zoomstart.y)
528             [zoomend.y, zoomstart.y] = [zoomstart.y, zoomend.y];
529
530           // determine new "coordinates"
531           var CWidth = gCurrentImageData.C_max.r - gCurrentImageData.C_min.r;
532           var CHeight = gCurrentImageData.C_max.i - gCurrentImageData.C_min.i;
533           var newC_min = new complex(
534               gCurrentImageData.C_min.r + zoomstart.x / gCurrentImageData.iWidth * CWidth,
535               gCurrentImageData.C_min.i + zoomstart.y / gCurrentImageData.iHeight * CHeight);
536           var newC_max = new complex(
537               gCurrentImageData.C_min.r + zoomend.x / gCurrentImageData.iWidth * CWidth,
538               gCurrentImageData.C_min.i + zoomend.y / gCurrentImageData.iHeight * CHeight);
539
540           adjustCoordsAndDraw(newC_min, newC_max);
541         }
542         zoomstart = undefined;
543         break;
544       case 'mousemove':
545       case 'touchmove':
546         if (zoomstart) {
547           context.putImageData(imgBackup, 0, 0);
548           context.strokeStyle = "rgb(255,255,31)";
549           context.strokeRect(zoomstart.x, zoomstart.y,
550                              coordObj.clientX - canvas.offsetLeft - zoomstart.x,
551                              coordObj.clientY - canvas.offsetTop - zoomstart.y);
552         }
553       break;
554     }
555   }
556 };
557
558 function toggleSettings() {
559   var fs = document.getElementById("settings");
560   if (fs.style.display != "block") {
561     fs.style.display = "block";
562   }
563   else {
564     fs.style.display = "none";
565   }
566 }
567
568 function goBack() {
569   if (gLastImageData) {
570     document.getElementById("iterMax").value = gLastImageData.iterMax;
571     // use gLastImageData.iWidth, gLastImageData.iHeight ???
572     adjustCoordsAndDraw(gLastImageData.C_min, gLastImageData.C_max);
573     gLastImageData = undefined;
574   }
575 }
576
577 function setIter(aIter) {
578   document.getElementById("iterMax").value = aIter;
579 }
580
581 function setPalette(aPaletteID) {
582   document.getElementById("palette").value = aPaletteID;
583   gColorPalette = getColorPalette(aPaletteID);
584 }
585
586 function setAlgorithm(algoID) {
587   //document.getElementById("algorithm").value = algoID;
588 }