add an option for synching proportions and implement it (mostly)
[mandelbrot.git] / xulapp / chrome / mandelbrot / content / 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
19  * the Initial Developer. All Rights Reserved.
20  *
21  * Contributor(s):
22  *   Robert Kaiser <kairo@kairo.at>
23  *
24  * Alternatively, the contents of this file may be used under the terms of
25  * either the GNU General Public License Version 2 or later (the "GPL"), or
26  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27  * in which case the provisions of the GPL or the LGPL are applicable instead
28  * of those above. If you wish to allow use of your version of this file only
29  * under the terms of either the GPL or the LGPL, and not to allow others to
30  * use your version of this file under the terms of the MPL, indicate your
31  * decision by deleting the provisions above and replace them with the notice
32  * and other provisions required by the GPL or the LGPL. If you do not delete
33  * the provisions above, a recipient may use your version of this file under
34  * the terms of any one of the MPL, the GPL or the LGPL.
35  *
36  * ***** END LICENSE BLOCK ***** */
37
38 var gColorPalette = [];
39 var gPref = Components.classes["@mozilla.org/preferences-service;1"]
40                       .getService(Components.interfaces.nsIPrefService)
41                       .getBranch(null);
42 var gStartTime = 0;
43
44 function Startup() {
45   updateIterMenu();
46   updatePaletteMenu();
47   document.getElementById("statusLabel").value =
48       document.getElementById("mbrotBundle").getString("statusEmpty");
49 }
50
51 function drawImage() {
52   let canvas = document.getElementById("mbrotImage");
53   let context = canvas.getContext("2d");
54
55   document.getElementById("statusLabel").value =
56       document.getElementById("mbrotBundle").getString("statusDrawing");
57
58   let Cr_min = -2.0;
59   let Cr_max = 1.0;
60   try {
61     Cr_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_min"));
62     Cr_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_max"));
63   }
64   catch (e) { }
65   if ((Cr_min < -2) || (Cr_min > 2) ||
66       (Cr_max < -2) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
67     Cr_min = -2.0; Cr_max = 1.0;
68   }
69   gPref.setCharPref("mandelbrot.last_image.Cr_min", Cr_min);
70   gPref.setCharPref("mandelbrot.last_image.Cr_max", Cr_max);
71
72   let Ci_min = -1.5;
73   let Ci_max = 1.5;
74   try {
75     Ci_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_min"));
76     Ci_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_max"));
77   }
78   catch (e) { }
79   if ((Ci_min < -2) || (Ci_min > 2) ||
80       (Ci_max < -2) || (Ci_max > 2) || (Ci_min >= Ci_max)) {
81     Ci_min = -2.0; Ci_max = 1.0;
82   }
83   gPref.setCharPref("mandelbrot.last_image.Ci_min", Ci_min);
84   gPref.setCharPref("mandelbrot.last_image.Ci_max", Ci_max);
85
86   let iterMax = gPref.getIntPref("mandelbrot.iteration_max");
87   let algorithm = gPref.getCharPref("mandelbrot.use_algorithm");
88
89   let iWidth = 0;
90   try {
91     iWidth = gPref.getIntPref("mandelbrot.image.width");
92   }
93   catch (e) { }
94   if ((iWidth < 10) || (iWidth > 5000)) {
95     iWidth = 300;
96     gPref.setIntPref("mandelbrot.image.width", iWidth);
97   }
98   let iHeight = 0;
99   try {
100     iHeight = gPref.getIntPref("mandelbrot.image.height");
101   }
102   catch (e) { }
103   if ((iHeight < 10) || (iHeight > 5000)) {
104     iHeight = 300;
105     gPref.setIntPref("mandelbrot.image.height", iHeight);
106   }
107
108   canvas.width = iWidth;
109   canvas.height = iHeight;
110
111   context.fillStyle = "rgba(255, 255, 255, 127)";
112   context.fillRect(0, 0, canvas.width, canvas.height);
113
114   gStartTime = new Date();
115
116   drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
117               canvas, context, iterMax, algorithm);
118 }
119
120 function drawLine(line, dimensions, canvas, context, iterMax, algorithm) {
121     let Cr_min = dimensions[0];
122     let Cr_max = dimensions[1];
123     let Cr_scale = Cr_max - Cr_min;
124
125     let Ci_min = dimensions[2];
126     let Ci_max = dimensions[3];
127     let Ci_scale = Ci_max - Ci_min;
128
129     let pixels = [];
130     for (var img_y = line; img_y < canvas.height && img_y < line+8; img_y++)
131       for (let img_x = 0; img_x < canvas.width; img_x++) {
132         let C = new complex(Cr_min + (img_x / canvas.width) * Cr_scale,
133                             Ci_min + (img_y / canvas.height) * Ci_scale);
134         pixels.push.apply(pixels, drawPoint(context, img_x, img_y, C, iterMax, algorithm));
135       }
136     context.putImageData({width: canvas.width, height: pixels.length/4/canvas.width, data: pixels}, 0, line);
137
138     if (img_y < canvas.height)
139       setTimeout(drawLine, 0, img_y, dimensions, canvas, context, iterMax, algorithm);
140     else if (gStartTime)
141       EndCalc();
142 }
143
144 function EndCalc() {
145   let endTime = new Date();
146   let timeUsed = (endTime.getTime() - gStartTime.getTime()) / 1000;
147   document.getElementById("statusLabel").value =
148       document.getElementById("mbrotBundle").getFormattedString("statusTime", [timeUsed.toFixed(3)]);
149 }
150
151 function complex(aReal, aImag) {
152   this.r = aReal;
153   this.i = aImag;
154 }
155 complex.prototype = {
156   square: function() {
157     return new complex(this.r * this.r - this.i * this.i,
158                        2 * this.r * this.i);
159   },
160   dist: function() {
161     return Math.sqrt(this.r * this.r + this.i * this.i);
162   },
163   add: function(aComplex) {
164     return new complex(this.r + aComplex.r, this.i + aComplex.i);
165   }
166 }
167
168 function mandelbrotValueOO (aC, aIterMax) {
169   // this would be nice code in general but it looks like JS objects are too heavy for normal use.
170   let Z = new complex(0.0, 0.0);
171   for (var iter = 0; iter < aIterMax; iter++) {
172     Z = Z.square().add(aC);
173     if (Z.r * Z.r + Z.i * Z.i > 256) { break; }
174   }
175   return iter;
176 }
177
178 function mandelbrotValueNumeric (aC, aIterMax) {
179   // optimized numeric code for fast calculation
180   let Cr = aC.r, Ci = aC.i;
181   let Zr = 0.0, Zi = 0.0;
182   let Zr2 = Zr * Zr, Zi2 = Zi * Zi;
183   for (var iter = 0; iter < aIterMax; iter++) {
184     Zi = 2 * Zr * Zi + Ci;
185     Zr = Zr2 - Zi2 + Cr;
186
187     Zr2 = Zr * Zr; Zi2 = Zi * Zi;
188     if (Zr2 + Zi2 > 256) { break; }
189   }
190   return iter;
191 }
192
193 function getColor(aIterValue, aIterMax) {
194   let standardizedValue = Math.round(aIterValue * 1024 / aIterMax);
195   if (gColorPalette && gColorPalette.length)
196     return gColorPalette[standardizedValue];
197
198   // fallback to simple b/w if for some reason we don't have a palette
199   if (aIterValue == aIterMax)
200     return [0, 0, 0, 255];
201   else
202     return [255, 255, 255, 255];
203 }
204
205 function getColorPalette(palName) {
206   var palette = [];
207   switch (palName) {
208     case 'bw':
209       for (let i = 0; i < 1024; i++) {
210         palette[i] = [255, 255, 255, 255];
211       }
212       palette[1024] = [0, 0, 0, 255];
213       break;
214     case 'kairo':
215       // outer areas
216       for (let i = 0; i < 32; i++) {
217         let cc1 = Math.floor(i * 127 / 31);
218         let cc2 = 170 - Math.floor(i * 43 / 31);
219         palette[i] = [cc1, cc2, cc1, 255];
220       }
221       // inner areas
222       for (let i = 0; i < 51; i++) {
223         let cc = Math.floor(i * 170 / 50);
224         palette[32 + i] = [cc, 0, (170-cc), 255];
225       }
226       // corona
227       for (let i = 0; i < 101; i++) {
228         let cc = Math.floor(i * 200 / 100);
229         palette[83 + i] = [255, cc, 0, 255];
230       }
231       // inner corona
232       for (let i = 0; i < 201; i++) {
233         let cc1 = 255 - Math.floor(i * 85 / 200);
234         let cc2 = 200 - Math.floor(i * 30 / 200);
235         let cc3 = Math.floor(i * 170 / 200);
236         palette[184 + i] = [cc1, cc2, cc3, 255];
237       }
238       for (let i = 0; i < 301; i++) {
239         let cc1 = 170 - Math.floor(i * 43 / 300);
240         let cc2 = 170 + Math.floor(i * 85 / 300);
241         palette[385 + i] = [cc1, cc1, cc2, 255];
242       }
243       for (let i = 0; i < 338; i++) {
244         let cc = 127 + Math.floor(i * 128 / 337);
245         palette[686 + i] = [cc, cc, 255, 255];
246       }
247       palette[1024] = [0, 0, 0, 255];
248       break;
249     case 'rainbow-linear1':
250       for (let i = 0; i < 256; i++) {
251         palette[i] = [i, 0, 0, 255];
252         palette[256 + i] = [255, i, 0, 255];
253         palette[512 + i] = [255 - i, 255, i, 255];
254         palette[768 + i] = [i, 255-i, 255, 255];
255       }
256       palette[1024] = [0, 0, 0, 255];
257       break;
258   }
259 /*
260 Select Case palnr
261 Case 1  'Standard-Palette (QB-Colors)
262      For i = 0 To 1024
263          xx = CInt(i * 500 / 1024 + 2)
264          If xx <= 15 Then clr = xx
265          If xx > 15 Then clr = CInt(Sqr((xx - 15 + 1) * 15 ^ 2 / 485))
266          If xx >= 500 Then clr = 0
267          palette(i) = QBColor(clr)
268      Next
269 Case 3  'Regenbogen-Palette 1 (qu.)
270      For i = 0 To 33
271          clr = CInt(i * 255 / 33)
272          palette(i) = RGB(clr, 0, 0)
273      Next
274      For i = 0 To 136
275          clr = CInt(i * 255 / 136)
276          palette(34 + i) = RGB(255, clr, 0)
277      Next
278      For i = 0 To 306
279          clr = CInt(i * 255 / 306)
280          palette(171 + i) = RGB(255 - clr, 255, clr)
281      Next
282      For i = 0 To 545
283          clr = CInt(i * 255 / 545)
284          palette(478 + i) = RGB(clr, 255 - clr, 255)
285      Next
286 Case 4  'Regenbogen-Palette 2 (linear)
287      For i = 0 To 204
288          clr = CInt(i * 255 / 204)
289          palette(i) = RGB(255, clr, 0)
290          palette(204 + i) = RGB(255 - clr, 255, 0)
291          palette(409 + i) = RGB(0, 255, clr)
292          palette(614 + i) = RGB(0, 255 - clr, 255)
293          palette(819 + i) = RGB(clr, 0, 255)
294      Next
295 Case 5  'Regenbogen-Palette 2 (qu.)
296      For i = 0 To 18
297          clr = CInt(i * 255 / 18)
298          palette(i) = RGB(255, clr, 0)
299      Next
300      For i = 0 To 73
301          clr = CInt(i * 255 / 73)
302          palette(20 + i) = RGB(255 - clr, 255, 0)
303      Next
304      For i = 0 To 167
305          clr = CInt(i * 255 / 167)
306          palette(93 + i) = RGB(0, 255, clr)
307      Next
308      For i = 0 To 297
309          clr = CInt(i * 255 / 297)
310          palette(261 + i) = RGB(0, 255 - clr, 255)
311      Next
312      For i = 0 To 464
313          clr = CInt(i * 255 / 464)
314          palette(559 + i) = RGB(clr, 0, 255)
315      Next
316 */
317   return palette;
318 }
319
320 function drawPoint(context, img_x, img_y, C, iterMax, algorithm) {
321   var itVal;
322   switch (algorithm) {
323     case 'oo':
324       itVal = mandelbrotValueOO(C, iterMax);
325       break;
326     case 'numeric':
327     default:
328       itVal = mandelbrotValueNumeric(C, iterMax);
329       break;
330   }
331   return getColor(itVal, iterMax);
332 }
333
334 /***** pure UI functions *****/
335
336 function saveImage() {
337   const bundle = document.getElementById("mbrotBundle");
338   const nsIFilePicker = Components.interfaces.nsIFilePicker;
339   var fp = null;
340   try {
341     fp = Components.classes["@mozilla.org/filepicker;1"]
342                    .createInstance(nsIFilePicker);
343   } catch (e) {}
344   if (!fp) return;
345   var promptString = bundle.getString("savePrompt");
346   fp.init(window, promptString, nsIFilePicker.modeSave);
347   fp.appendFilter(bundle.getString("pngFilterName"), "*.png");
348   fp.defaultString = "mandelbrot.png";
349
350   var fpResult = fp.show();
351   if (fpResult != nsIFilePicker.returnCancel) {
352     saveCanvas(document.getElementById("mbrotImage"), fp.file);
353   }
354 }
355
356 function updateIterMenu() {
357   try {
358     var currentIter = gPref.getIntPref("mandelbrot.iteration_max");
359   }
360   catch(e) {
361     var currentIter = 0;
362   }
363   if (currentIter < 10) {
364     currentIter = 500;
365     setIter(currentIter);
366   }
367
368   var popup = document.getElementById("menu_iterPopup");
369   var item = popup.firstChild;
370   while (item) {
371     if (item.getAttribute("name") == "iter") {
372       if (item.getAttribute("value") == currentIter)
373         item.setAttribute("checked","true");
374       else
375         item.removeAttribute("checked");
376     }
377     item = item.nextSibling;
378   }
379 }
380
381 function setIter(aIter) {
382   gPref.setIntPref("mandelbrot.iteration_max", aIter);
383 }
384
385 function updatePaletteMenu() {
386   try {
387     var currentPalette = gPref.getCharPref("mandelbrot.color_palette");
388   }
389   catch(e) {
390     var currentPalette = '';
391   }
392   if (!currentPalette.length) {
393     currentPalette = 'kairo';
394     setPalette(currentPalette);
395   }
396   if (!gColorPalette || !gColorPalette.length)
397     gColorPalette = getColorPalette(currentPalette);
398
399   var popup = document.getElementById("menu_palettePopup");
400   var item = popup.firstChild;
401   while (item) {
402     if (item.getAttribute("name") == "palette") {
403       if (item.getAttribute("value") == currentPalette)
404         item.setAttribute("checked", "true");
405       else
406         item.removeAttribute("checked");
407     }
408     item = item.nextSibling;
409   }
410 }
411
412 function setPalette(aPaletteID) {
413   gPref.setCharPref("mandelbrot.color_palette", aPaletteID);
414   gColorPalette = getColorPalette(aPaletteID);
415 }
416
417 function imgSettings() {
418   window.openDialog("chrome://mandelbrot/content/image-settings.xul");
419 }
420
421 function updateDebugMenu() {
422   var jitMenuItem = document.getElementById("jitEnabled");
423   jitMenuItem.setAttribute("checked", gPref.getBoolPref("javascript.options.jit.chrome"));
424 }
425
426 function toggleJITState(jitMenuItem) {
427   var jitEnabled = !gPref.getBoolPref("javascript.options.jit.chrome");
428   gPref.setBoolPref("javascript.options.jit.chrome", jitEnabled)
429   jitMenuItem.setAttribute("checked", jitEnabled? "true" : "false");
430 }
431
432 function updateAlgoMenu() {
433   try {
434     var currentAlgo = gPref.getCharPref("mandelbrot.use_algorithm");
435   }
436   catch(e) {
437     var currentAlgo = '';
438   }
439   if (!currentAlgo.length) {
440     currentAlgo = 'numeric';
441     setAlgorithm(currentAlgo);
442   }
443
444   var popup = document.getElementById("menu_algoPopup");
445   var item = popup.firstChild;
446   while (item) {
447     if (item.getAttribute("name") == "algorithm") {
448       if (item.getAttribute("value") == currentAlgo)
449         item.setAttribute("checked", "true");
450       else
451         item.removeAttribute("checked");
452     }
453     item = item.nextSibling;
454   }
455 }
456
457 function setAlgorithm(algoID) {
458   gPref.setCharPref("mandelbrot.use_algorithm", algoID);
459 }
460
461 /***** helper functions from external sources *****/
462
463 // function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
464 // custom modifications:
465 //   - use "a"-prefix on function arguments
466 //   - take an nsILocalFile as aDestFile argument
467 //   - always do silent download
468 function saveCanvas(aCanvas, aDestFile) {
469   // create a data url from the canvas and then create URIs of the source and targets  
470   var io = Components.classes["@mozilla.org/network/io-service;1"]
471                      .getService(Components.interfaces.nsIIOService);
472   var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
473
474   // prepare to save the canvas data
475   var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
476                           .createInstance(Components.interfaces.nsIWebBrowserPersist);
477
478   persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
479   persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
480
481   // save the canvas data to the file
482   persist.saveURI(source, null, null, null, null, aDestFile);
483 }
484
485 // function below is from http://developer.mozilla.org/en/docs/How_to_Quit_a_XUL_Application
486 function quitApp(aForceQuit) {
487   var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1']
488                              .getService(Components.interfaces.nsIAppStartup);
489
490   // eAttemptQuit will try to close each XUL window, but the XUL window can cancel the quit
491   // process if there is unsaved data. eForceQuit will quit no matter what.
492   var quitSeverity = aForceQuit ? Components.interfaces.nsIAppStartup.eForceQuit :
493                                   Components.interfaces.nsIAppStartup.eAttemptQuit;
494   appStartup.quit(quitSeverity);
495 }