-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
500 lines (426 loc) · 11.5 KB
/
main.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
//@ts-check
/// <reference path="types.d.ts"/>
import 'https://unpkg.com/classnames';
import { createElement, render } from 'https://unpkg.com/preact@latest?module';
import HistoryTreeView from './components/HistoryTreeView.js';
import ComplexNumber from './core/ComplexNumber.js';
import HistoryTree from './core/HistoryTree.js';
import iterateMandelbrot, { iterateJuliaJs } from './core/iterateMandelbrot.js';
import Matrix3 from './core/Matrix3.js';
import Vector3 from './core/Vector3.js';
import debounce from './util/debounce.js';
/**
* @typedef {{
* transform: Matrix3;
* juliaInitial: ComplexNumber | null;
* thumbnail: HTMLCanvasElement;
* }} HistoryItem
*/
/**
* @template T
* @typedef {import('./core/HistoryTree.js').HistoryNode<T>} HistoryNode
*/
function iterateMandelbrotAndGetPath(c, maxIterations) {
const path = [];
let z = new ComplexNumber(0, 0);
maxIterations = Math.max(1, maxIterations);
path.push(z.clone());
for (let i = 0; i < maxIterations; i++) {
z = z.multiply(z).add(c);
path.push(z.clone());
if (z.magnitudeSquared() > 4) return path;
}
return path;
}
function iterateJuliaAndGetPath(initial, c, maxIterations) {
const path = [];
let z = initial;
maxIterations = Math.max(1, maxIterations);
path.push(z.clone());
for (let i = 0; i < maxIterations; i++) {
z = z.multiply(z).add(c);
path.push(z.clone());
if (z.magnitudeSquared() > 4) return path;
}
return path;
}
function rainbowColour(iterations) {
const hue = iterations;
const saturation = 25 + Math.abs((iterations % 100) - 50);
const luminance = iterations % 2 === 0 ? 50 : 25;
return `hsl(${hue}, ${saturation}%, ${luminance}%)`;
}
/**
* @param {HTMLCanvasElement} canvas
* @param {number} width
* @param {number} height
* @param {Matrix3} transform
* @param {ComplexNumber|null} juliaInitial
* @param {number} maxIterations
* @param {AbortSignal} abort
*/
async function drawMandelbrot(
canvas,
width,
height,
transform,
juliaInitial,
maxIterations,
abort
) {
//Start timing execution
const startTime = performance.now();
const context = canvas.getContext('2d');
if (!context) {
throw new Error('Could not get canvas context');
}
// context.clearRect(0, 0, width, height);
for (let y = 0; y < height; y++) {
await new Promise((s) => setTimeout(s, 0));
for (let x = 0; x < width; x++) {
if (abort.aborted) {
return;
}
const transformedPoint = transform.transform(
new Vector3(x / width, y / height, 1)
);
const c = new ComplexNumber(transformedPoint.x, transformedPoint.y);
const result = juliaInitial
? iterateJuliaJs(c, juliaInitial.clone(), maxIterations)
: iterateMandelbrot(c, maxIterations);
if (result.iterations === maxIterations)
context.fillStyle = 'black';
else context.fillStyle = rainbowColour(result.iterations);
context.fillRect(x, y, 1, 1);
}
}
//Stop timing execution
const endTime = performance.now();
console.log(
`Execution time: ${
endTime - startTime
} ms. MaxIterations: ${maxIterations}`
);
document.title = `Execution time: ${
endTime - startTime
} ms. MaxIterations: ${maxIterations}`;
}
/**
* @param {number} width
* @param {number} height
* @param {Matrix3} transform
* @param {ComplexNumber|null} juliaInitial
* @param {number} maxIterations
*/
function createThumbnail(
width,
height,
transform,
juliaInitial,
maxIterations
) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
drawMandelbrot(
canvas,
width,
height,
transform,
juliaInitial,
maxIterations,
new AbortController().signal
);
return canvas;
}
window.addEventListener('load', () => {
let maxIterations = 5000;
const canvasEle = document.getElementById('canvas');
if (!(canvasEle instanceof HTMLCanvasElement))
throw new Error('Invalid canvas element');
const canvas = canvasEle;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let pathLength = 0;
/**
* @param {Matrix3} transform
* @param {ComplexNumber | null} juliaInitial
* @return {HistoryItem}
*/
function createHistoryItem(transform, juliaInitial) {
return {
transform,
thumbnail: createThumbnail(
150,
150,
transform,
juliaInitial,
maxIterations
),
juliaInitial,
};
}
const history = new HistoryTree(
createHistoryItem(Matrix3.boundingBox(-2, -2, 2, 2), null)
);
render(
createElement(HistoryTreeView, { historyTree: history }, null),
document.getElementById('history')
);
let abortController = new AbortController();
function drawCurrent() {
abortController.abort();
abortController = new AbortController();
const state = history.currentState();
drawMandelbrot(
canvas,
canvas.width,
canvas.height,
state.transform,
state.juliaInitial,
maxIterations,
abortController.signal
);
}
const drawDebounced = debounce(drawCurrent, 1000);
history.onMove.addEventListener('move', () => {
drawCurrent();
});
window.addEventListener(
'resize',
debounce(() => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
drawCurrent();
}, 100)
);
//adjust maxiterations with mouse wheel scroll
canvas.addEventListener('wheel', (event) => {
event.preventDefault();
let delta = event.deltaY > 0 ? 1 : -1;
if (event.shiftKey) delta *= 100;
if (!event.ctrlKey) {
pathLength = Math.max(1, pathLength + delta);
document.title = `Path length: ${pathLength}`;
return;
}
//adjust maxiterations by delta but minimum of 1
maxIterations = Math.max(1, maxIterations + delta);
//put a message in the title with maxIterations
document.title = `${maxIterations}`;
drawDebounced();
});
window.addEventListener('keydown', (e) => {
// if ctrl + a number key is pressed, save the current transform to local storage
if (e.ctrlKey && e.keyCode >= 49 && e.keyCode <= 57) {
e.preventDefault();
//if there's already a save here, confirm overwrite
if (localStorage.getItem(`transform${e.keyCode - 48}`)) {
if (!confirm(`Overwrite saved transform ${e.keyCode - 48}?`))
return;
}
localStorage.setItem(
`transform${e.keyCode - 48}`,
JSON.stringify(history.currentState().transform.toJson())
);
//alert the user
alert(`Saved transform ${e.keyCode - 48}`);
}
//otherwise if a number key is pressed, load the transform from local storage
else if (e.keyCode >= 49 && e.keyCode <= 57) {
e.preventDefault();
const savedTransform = localStorage.getItem(
`transform${e.keyCode - 48}`
);
if (savedTransform) {
history.push(
createHistoryItem(
Matrix3.fromJson(JSON.parse(savedTransform)),
null
)
);
alert(`Loading transform ${e.keyCode - 48}`);
drawCurrent();
} else {
alert(`No saved transform ${e.keyCode - 48}`);
}
}
// otherwise if the tilde key is pressed and there's a transform in the stack, pop it
else if (e.keyCode === 192) {
e.preventDefault();
// if shift is pressed, reload the transform from the forward history
const oldHead = history.current;
if (e.shiftKey) {
history.go(1);
} else {
history.go(-1);
}
if (history.current !== oldHead) {
drawCurrent();
}
}
// otherwise if ctrl s is pressed, prompt for a resolution and trigger a download of a high res image of the mandelbrot set
else if (e.ctrlKey && e.keyCode === 83) {
e.preventDefault();
// prompt for x and y resolution
const res = prompt(
'Enter x and y resolution (separated by a space)',
'1920 1080'
);
if (res === null) return;
const resolution = res.split(' ').map((x) => parseInt(x));
if (
resolution.length !== 2 ||
resolution.some(
(dimension) =>
typeof dimension !== 'number' || dimension < 1
)
) {
alert('Invalid resolution');
return;
}
const [width, height] = resolution;
const canvasHiRes = document.createElement('canvas');
canvasHiRes.width = width;
canvasHiRes.height = height;
const context = canvasHiRes.getContext('2d');
(async () => {
const state = history.currentState();
await drawMandelbrot(
canvasHiRes,
canvasHiRes.width,
canvasHiRes.height,
state.transform,
state.juliaInitial,
maxIterations,
new AbortController().signal
);
const link = document.createElement('a');
link.download = `mandelbrot.png`;
link.href = canvasHiRes.toDataURL();
link.click();
})();
}
});
drawCurrent();
let clickStart = null;
canvas.addEventListener('mousedown', (event) => {
// If middle mouse button is pressed, zoom out
if (event.button === 1) {
if (history.current.id !== 'root') {
if (history.currentState().juliaInitial === null) {
history.goTo('root');
} else {
history.push(
createHistoryItem(
Matrix3.boundingBox(-2, -2, 2, 2),
history.currentState().juliaInitial
)
);
}
}
event.preventDefault();
drawCurrent();
return;
}
if (event.button !== 0) return;
clickStart = new Vector3(event.offsetX, event.offsetY, 1);
});
canvas.addEventListener('contextmenu', (event) => {
if (event.ctrlKey) return;
event.preventDefault();
const juliaInitial = history
.currentState()
.transform?.transform(
new Vector3(
event.offsetX / canvas.width,
event.offsetY / canvas.height,
1
)
);
if (!juliaInitial) return;
history.push(
createHistoryItem(
history.currentState().transform,
new ComplexNumber(juliaInitial.x, juliaInitial.y)
)
);
});
canvas.addEventListener('mousemove', (event) => {
const context = canvas.getContext('2d');
if (!context) throw new Error('Could not get canvas context');
context.strokeStyle = '#fff2';
if (pathLength > 0) {
const transformedPoint = history
.currentState()
.transform.transform(
new Vector3(
event.offsetX / canvas.width,
event.offsetY / canvas.height,
1
)
);
const c = new ComplexNumber(transformedPoint.x, transformedPoint.y);
const juliaInitial = history.currentState().juliaInitial;
const path = juliaInitial
? iterateJuliaAndGetPath(c, juliaInitial, pathLength)
: iterateMandelbrotAndGetPath(c, pathLength);
const inverseTransform = history.currentState().transform.inverse();
if (!inverseTransform) return;
context.beginPath();
path.forEach((point, index) => {
const pointInCanvas = inverseTransform.transform(
new Vector3(point.real, point.imaginary, 1)
);
pointInCanvas.x /= pointInCanvas.z;
pointInCanvas.y /= pointInCanvas.z;
if (index === 0) {
context.moveTo(
pointInCanvas.x * canvas.width,
pointInCanvas.y * canvas.height
);
} else {
context.lineTo(
pointInCanvas.x * canvas.width,
pointInCanvas.y * canvas.height
);
}
});
context.stroke();
}
if (event.button !== 0) return;
if (!clickStart) return;
//draw rectangle from clickstart to current position
context.beginPath();
context.rect(
clickStart.x,
clickStart.y,
event.offsetX - clickStart.x,
event.offsetY - clickStart.y
);
context.stroke();
});
canvas.addEventListener('mouseup', (event) => {
//ignore non-left clicks
if (event.button !== 0) return;
if (!clickStart) return;
const clickEnd = new Vector3(event.offsetX, event.offsetY, 1);
history.push(
createHistoryItem(
history
.currentState()
.transform.multiply(
Matrix3.boundingBox(
clickStart.x / canvas.width,
clickStart.y / canvas.height,
clickEnd.x / canvas.width,
clickEnd.y / canvas.height
)
),
history.currentState().juliaInitial
)
);
clickStart = null;
drawCurrent();
});
});