-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmandelbrot.html
602 lines (547 loc) · 17.5 KB
/
mandelbrot.html
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
<html>
<head>
<title>Mandelbrot set</title>
</head>
<script type="x-shader/x-vertex" id="passThruVS">
attribute vec2 coord;
varying vec2 pos;
void main(void) {
pos = coord;
gl_Position = vec4(coord, 0, 1.0);
gl_PointSize = 1.0;
}
</script>
<script type="x-shader/x-fragment" id="dfMandelbrotFS">
precision highp float;
varying vec2 pos;
uniform vec2 center, step;
uniform int numSteps;
uniform int usePalette;
uniform float ONE;
const int maxNumSteps = 16384;
vec2 quickTwoSum(float a, float b) {
float s = (a + b) * ONE;
float e = b - (s - a);
return vec2(s, e);
}
vec4 twoSumComp(vec2 a_ri, vec2 b_ri) {
vec2 s = (a_ri + b_ri) * ONE;
vec2 v = s - a_ri;
vec2 e = (a_ri - (s - v)) + (b_ri - v);
return vec4(s.x, e.x, s.y, e.y);
}
vec2 df_add(vec2 a, vec2 b) {
vec4 st = twoSumComp(a, b);
st.y += st.z;
st.xy = quickTwoSum(st.x, st.y);
st.y += st.w;
st.xy = quickTwoSum(st.x, st.y);
return st.xy;
}
vec4 twoSubComp(vec2 a_ri, vec2 b_ri) {
vec2 s = a_ri - b_ri;
vec2 v = s - a_ri;
vec2 e = (a_ri - (s - v)) + (-b_ri - v);
return vec4(s.x, e.x, s.y, e.y);
}
vec2 df_sub(vec2 a, vec2 b) {
vec4 st = twoSubComp(a, b);
st.y += st.z;
st.xy = quickTwoSum(st.x, st.y);
st.y += st.w;
st.xy = quickTwoSum(st.x, st.y);
return st.xy;
}
vec4 splitComp(vec2 c)
{
vec2 t = c * 4097.0;
vec2 c_hi = t - (t - c);
vec2 c_lo = c - c_hi;
return vec4(c_hi.x, c_lo.x, c_hi.y, c_lo.y);
}
vec2 twoProd(float a, float b)
{
float p = a * b;
vec4 abS = splitComp(vec2(a,b));
float err = ((abS.x * abS.z - p)
+ abS.x * abS.w + abS.y * abS.z)
+ abS.y * abS.w;
return vec2(p, err);
}
vec2 df_mul(vec2 a, vec2 b) {
vec2 p = twoProd(a.x,b.x);
p.y += a.x * b.y;
p.y += a.y * b.x;
return quickTwoSum(p.x,p.y);
}
vec4 mandelbrotStep(vec4 z, vec4 c) {
vec2 zx = df_add(df_sub(df_mul(z.xy,z.xy), df_mul(z.zw, z.zw)), c.xy);
vec2 zy = df_add(df_mul(vec2(2.0,0), df_mul(z.xy,z.zw)), c.zw);
return vec4(zx, zy);
}
float sqrdistance(vec4 val) {
return val.x*val.x + val.z*val.z;
}
int mod(int a, int b) {
float af = float(a);
float bf = float(b);
return int(floor(af-floor(af/bf)*bf));
}
vec4 getPaletteColor(int steps) {
int idx = mod(steps, 7);
if (idx == 0)
return vec4(0, 0, 1, 1);
if (idx == 1)
return vec4(0, 1, 0, 1);
if (idx == 2)
return vec4(0, 1, 1, 1);
if (idx == 3)
return vec4(1, 0, 0, 1);
if (idx == 4)
return vec4(1, 0, 1, 1);
if (idx == 5)
return vec4(1, 1, 0, 1);
return vec4(1, 1, 1, 1);
}
vec4 assignColor(vec4 z, int steps, int numSteps) {
if (usePalette == 0)
return vec4(abs(.5*z.x), float(step)/float(numSteps), abs(.5*z.z), 1);
float nu = log(log(sqrdistance(z))/2.0)/log(2.0);
vec4 a = getPaletteColor(steps);
vec4 b = getPaletteColor(steps+1);
return a * nu + b * (1.0 - nu);
}
void main(void) {
vec4 z = vec4(0);
vec4 c = vec4(
df_add(vec2(center.x, 0), df_mul(vec2(step.x, 0), vec2(pos.x, 0))),
df_sub(vec2(center.y, 0), df_mul(vec2(step.y, 0), vec2(pos.y, 0))));
for(int cnt = 0; cnt < maxNumSteps; cnt++) {
if (cnt == numSteps) break;
if (sqrdistance(z) >= 4.0) {
gl_FragColor = assignColor(z, cnt, numSteps);
return;
}
z = mandelbrotStep(z, c);
}
gl_FragColor = vec4(0, 0, 0, 1.0);
}
</script>
<script type="x-shader/x-fragment" id="mandelbrotFS">
precision highp float;
varying vec2 pos;
uniform vec2 center, step;
uniform int numSteps;
uniform int usePalette;
const int maxNumSteps = 16384;
float sqrdistance(vec2 val) {
return val.x*val.x+val.y*val.y;
}
vec2 mandelbrotStep(vec2 z, vec2 c) {
return vec2(z.x*z.x-z.y*z.y+c.x, 2.0*z.x*z.y + c.y);
}
int mod(int a, int b) {
float af = float(a);
float bf = float(b);
return int(floor(af-floor(af/bf)*bf));
}
vec4 getPaletteColor(int steps) {
int idx = mod(steps, 7);
if (idx == 0)
return vec4(0, 0, 1, 1);
if (idx == 1)
return vec4(0, 1, 0, 1);
if (idx == 2)
return vec4(0, 1, 1, 1);
if (idx == 3)
return vec4(1, 0, 0, 1);
if (idx == 4)
return vec4(1, 0, 1, 1);
if (idx == 5)
return vec4(1, 1, 0, 1);
return vec4(1, 1, 1, 1);
}
vec4 assignColor(vec2 z, int steps, int numSteps) {
if (usePalette == 0)
return vec4(abs(.5*z.x), float(step)/float(numSteps), abs(.5*z.y), 1);
float nu = log(log(sqrdistance(z))/2.0)/log(2.0);
vec4 a = getPaletteColor(steps);
vec4 b = getPaletteColor(steps+1);
return a * nu + b * (1.0 - nu);
}
void main(void) {
vec2 z = vec2(0, 0);
vec2 c = vec2(center.x + step.x*pos.x, center.y - step.y*pos.y);
for(int cnt = 0; cnt < maxNumSteps; cnt++) {
if (cnt == numSteps) break;
if (sqrdistance(z) >= 4.0) {
gl_FragColor = assignColor(z, cnt, numSteps);
return;
}
z = mandelbrotStep(z, c);
}
gl_FragColor = vec4(0, 0, 0, 1.0);
}
</script>
<script type="x-shader/x-fragment" id="solidColorFS">
precision highp float;
uniform vec4 color;
void main(void) {
gl_FragColor = color;
}
</script>
<script type="text/javascript">
class GLContext {
constructor(canvas) {
if (canvas == null)
throw 'Can not find canvas';
const ctx = canvas.getContext('webgl2');
if (ctx == null)
throw 'Can not get WebGL context...';
ctx.viewport(0, 0, canvas.clientWidth, canvas.clientHeight);
ctx.clearColor(0, 0, 0, 1.0);
ctx.clear(ctx.COLOR_BUFFER_BIT);
this._ctx = ctx;
this.PRIMITIVES = {
POINTS: ctx.POINTS,
LINE_STRIP: ctx.LINE_STRIP,
LINES: ctx.LINES,
TRIANGLE_STRIP: ctx.TRIANGLE_STRIP,
TRIANGLES: ctx.TRIANGLES,
};
}
getGLContext() {
if (!this._ctx) throw 'Missing context';
return this._ctx;
}
compileShader(type, source) {
const glCtx = this.getGLContext();
var rc = glCtx.createShader(type);
glCtx.shaderSource(rc, source);
glCtx.compileShader(rc);
if (!glCtx.getShaderParameter(rc, glCtx.COMPILE_STATUS)) {
throw glCtx.getShaderInfoLog(rc) + ' in ' + source;
}
return rc;
}
compileShaderById(id) {
const glCtx = this.getGLContext();
const element = document.getElementById(id);
if (element == null) {
throw 'Can not find shader by element id ' + id;
}
const source = element.innerHTML;
if (element.type === 'x-shader/x-vertex') {
return this.compileShader(glCtx.VERTEX_SHADER, source);
}
if (element.type === 'x-shader/x-fragment') {
return this.compileShader(glCtx.FRAGMENT_SHADER, source);
}
throw 'Unknown shader type ' + element.type;
}
linkProgram(shaders) {
const glCtx = this.getGLContext();
const rc = glCtx.createProgram();
for(var cnt = 0; cnt < shaders.length; cnt++) {
if (!shaders[cnt]) {
throw 'Can not link program with null shaders';
}
glCtx.attachShader(rc, shaders[cnt]);
}
glCtx.linkProgram(rc);
if (!glCtx.getProgramParameter(rc, glCtx.LINK_STATUS)) {
throw glCtx.getProgramInfoLog(rc);
}
return rc;
}
setUniform1i(name, a) {
const glCtx = this.getGLContext();
const prog = glCtx.getParameter(glCtx.CURRENT_PROGRAM);
const idx = glCtx.getUniformLocation(prog, name);
glCtx.uniform1i(idx, a);
}
setUniform1f(name, a) {
const glCtx = this.getGLContext();
const prog = glCtx.getParameter(glCtx.CURRENT_PROGRAM);
const idx = glCtx.getUniformLocation(prog, name);
glCtx.uniform1f(idx, a);
}
setUniform2f(name, a, b) {
const glCtx = this.getGLContext();
const prog = glCtx.getParameter(glCtx.CURRENT_PROGRAM);
const idx = glCtx.getUniformLocation(prog, name);
glCtx.uniform2f(idx, a, b);
}
setUniform4f(name, a, b, c, d) {
const glCtx = this.getGLContext();
const prog = glCtx.getParameter(glCtx.CURRENT_PROGRAM);
const idx = glCtx.getUniformLocation(prog, name);
glCtx.uniform4f(idx, a, b, c, d);
}
draw2DArray(type, name, arr) {
const glCtx = this.getGLContext();
const prog = glCtx.getParameter(glCtx.CURRENT_PROGRAM);
const idx = glCtx.getAttribLocation(prog, name);
var buf = glCtx.createBuffer();
glCtx.bindBuffer(glCtx.ARRAY_BUFFER, buf);
glCtx.bufferData(glCtx.ARRAY_BUFFER, new Float32Array(arr), glCtx.STATIC_DRAW);
glCtx.enableVertexAttribArray(idx);
glCtx.vertexAttribPointer(idx, 2, glCtx.FLOAT, false, 0, 0);
glCtx.drawArrays(type, 0, arr.length/2);
glCtx.deleteBuffer(buf);
}
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
sub(p) { return new Point(this.x-p.x, this.y-p.y); }
add(p) { return new Point(this.x+p.x, this.y+p.y); }
mul(a) { return new Point(a*this.x, a*this.y); }
len2() { return this.x*this.x + this.y*this.y;}
len() { return Math.sqrt(this.len2());}
}
class Complex {
constructor(re, im) { this.re = re; this.im = im; }
sub(p) { return new Complex(this.re-p.re, this.im-p.im); }
add(p) { return new Complex(this.re+p.re, this.im+p.im); }
mul(x) {
if (x instanceof Complex)
return new Complex(x.re*this.re - x.im*this.im, x.re*this.im + x.im*this.re);
return new Complex(x*this.re, x*this.im);
}
}
function TouchState(event) {
const rc = {};
for(var cnt = 0; cnt < event.touches.length; ++cnt) {
const touch = event.touches[cnt];
rc[touch.identifier] = new Point(touch.clientX, touch.clientY);
}
return rc;
}
function comparableTouches(a, b) {
if (a == null || b == null) return false;
const akeys = Object.keys(a);
const bkeys = Object.keys(b);
for(var cnt = 0; cnt < akeys.length; ++cnt) {
if (!bkeys.includes(akeys[cnt])) return false;
}
return true;
}
class ZoomRenderer {
constructor(canvas) {
const ctx = new GLContext(canvas);
const prog = ctx.linkProgram(['passThruVS', 'mandelbrotFS'].map(_ => ctx.compileShaderById(_)));
const dprog = ctx.linkProgram(['passThruVS', 'dfMandelbrotFS'].map(_ => ctx.compileShaderById(_)));
const sprog = ctx.linkProgram(['passThruVS', 'solidColorFS'].map(_ => ctx.compileShaderById(_)));
this._ctx = ctx;
this._mandelProgram = prog;
this._dfMandelProgram = dprog;
this._solidProgram = sprog;
this._halfCanvasDim = new Point(canvas.clientWidth, canvas.clientHeight).mul(.5);
this._scale = 4.0/Math.min(canvas.clientWidth, canvas.clientHeight);
this._center = new Point(0.0, 0.0);
const stepsMatch = window.location.search.match(/[&?]numSteps=(\d+)/);
this._numSteps = stepsMatch ? Number(stepsMatch[1]) : 256;
if (window.location.search.indexOf('overfloat') >= 0) {
this._center = new Point(0.2807024158978315, -0.011177972555812295);
this._scale = 4.0/(2e6*Math.min(canvas.clientWidth, canvas.clientHeight));
}
this._forceDF = window.location.search.indexOf('forceDF') >= 0;
this._noDF = window.location.search.indexOf('noDF') >= 0;
this._usePalette = window.location.search.indexOf('usePalette') >= 0;
this._configureMouseEventHandlers(canvas);
this._configureTouchEventHandlers(canvas);
}
_configureMouseEventHandlers(canvas) {
canvas.addEventListener('click', (event) => {
const clickTime = Date.now();
// Doubleclick is two clicks less than .3 seconds apart
if (clickTime - this._prevClickTime > 300) {
this._prevClickTime = clickTime;
return;
}
this.adjustScaleWithInvariantPoint(.5, event.offsetX, event.offsetY);
this._prevClickTime = 0;
this.render();
});
canvas.addEventListener('wheel', (event) => {
const wheelTime = Date.now();
if (event.deltaY == 0) return;
// Limit number of scroll events to 20 per seconds
if (wheelTime - this._prevWheelTime < 50) {
event.preventDefault();
return;
}
this._prevWheelTime = wheelTime;
const factor = event.deltaY > 0 ? .8 : 1.25;
this.adjustScaleWithInvariantPoint(factor, event.offsetX, event.offsetY);
this.render();
event.preventDefault();
});
canvas.addEventListener('mousedown', (event) => {
this._dragStart = new Point(event.offsetX, event.offsetY);
this._dragStartCenter = new Point(this._center.x, this._center.y);
});
canvas.addEventListener('mousemove', (event) => {
const dragStart = this._dragStart;
if (dragStart == null) return;
const moveTime = Date.now();
if (moveTime - this._prevMoveTime < 50) return;
this._prevMoveTime = moveTime;
const offs = new Point(event.offsetX, event.offsetY).sub(dragStart);
this._center = this._dragStartCenter.sub(offs.mul(this._scale));
this.render();
});
canvas.addEventListener('mouseup', (event) => {
this._dragStart = null;
this._dragStartCenter = null;
});
this._prevClickTime = 0;
this._prevWheelTime = 0;
this._prevMoveTime = 0;
this._dragStart = null;
this._dragStartCenter = null;
}
_configureTouchEventHandlers(canvas) {
try { TouchEvent; } catch(e) {
return;
}
console.log("Configuring touch event handlers");
canvas.addEventListener('touchstart', (event) => {
this._touchStart = TouchState(event);
this._touchStartCenter = this._center;
this._touchStartScale = this._scale;
});
canvas.addEventListener('touchend', (event) => {
this._touchStart = null;
this._touchStartCenter = null;
});
canvas.addEventListener('touchmove', (event) => {
if (this._touchStart == null) return;
const state = TouchState(event);
if (!comparableTouches(state, this._touchStart)) return;
event.preventDefault();
const touchTime = Date.now();
if (touchTime - this._prevTouchTime < 50) return;
this._prevTouchTime = touchTime;
const touchKeys = Object.keys(this._touchStart);
if (touchKeys.length == 1) {
const key = touchKeys[0];
const offs = state[key].sub(this._touchStart[key]);
this._center = this._touchStartCenter.sub(offs.mul(this._scale));
this.render();
}
if (touchKeys.length == 2) {
const a = touchKeys[0];
const b = touchKeys[1];
const mid = this._touchStart[a].add(this._touchStart[b]).mul(.5);
const distStart = this._touchStart[a].sub(this._touchStart[b]).len();
const dist = state[a].sub(state[b]).len();
this._scale = this._touchStartScale;
this._center = this._touchStartCenter;
this.adjustScaleWithInvariantPoint(distStart/dist, mid.x, mid.y);
this.render();
}
});
this._prevTouchTime = 0;
this._touchStart = null;
this._touchStartCenter = null;
}
canvas2rendercoord(x, y) {
const offs = new Point(x, y).sub(this._halfCanvasDim);
return this._center.add(offs.mul(this._scale));
}
adjustScaleWithInvariantPoint(factor, invX, invY) {
const offs = new Point(invX, invY).sub(this._halfCanvasDim);
this._center = this._center.add(offs.mul((1-factor)*this._scale));
this._scale *= factor;
}
drawQuad(x0, y0, x1, y1) {
this._ctx.draw2DArray(this._ctx.PRIMITIVES.TRIANGLE_STRIP, 'coord', [x0, y0, x1, y0, x0, y1, x1, y1]);
}
renderOnCpu(sx,sy,ex,ey) {
if (sx == undefined) sx = -1;
if (sy == undefined) sy = -1;
if (ex == undefined) ex = 1;
if (ey == undefined) ey = 1;
const canvasDim = this._halfCanvasDim.mul(2.0);
const topLeft = this.canvas2rendercoord(0,0);
const bottomRight = this.canvas2rendercoord(canvasDim.x, canvasDim.y);
const dim = bottomRight.sub(topLeft);
const ctx = this._ctx;
ctx.getGLContext().useProgram(this._solidProgram);
for(var y = sy; y <= ey; y += 2.0/canvasDim.y)
for(var x = sx; x <= ex; x += 2.0/canvasDim.x) {
var z = new Complex(0, 0);
const c = new Complex(topLeft.x + dim.x*.5*(x+1.0), bottomRight.y - dim.y*.5*(y+1.0));
var cnt = 0;
while ( cnt < this._numSteps && z.re*z.re+z.im*z.im < 4.0) {
z = z.mul(z).add(c);
cnt += 1;
}
if (cnt == this._numSteps) {
ctx.setUniform4f('color', 0, 0, 0, 1);
} else {
ctx.setUniform4f('color', Math.abs(.5*z.re), cnt/256, Math.abs(.5*z.im), 1);
}
ctx.draw2DArray(ctx.PRIMITIVES.POINTS, 'coord', [x, y]);
}
}
render() {
const ctx = this._ctx;
const scale = this._scale;
const step = this._halfCanvasDim.mul(scale);
if (this._noDF)
ctx.getGLContext().useProgram(this._mandelProgram);
else if (this._forceDF)
ctx.getGLContext().useProgram(this._dfMandelProgram);
else
ctx.getGLContext().useProgram(scale >= 1e-7 ? this._mandelProgram : this._dfMandelProgram);
ctx.setUniform2f('center', this._center.x, this._center.y);
ctx.setUniform2f('step', step.x, step.y);
ctx.setUniform1i('numSteps', this._numSteps);
ctx.setUniform1i('usePalette', this._usePalette ? 1 : 0);
ctx.setUniform1f('ONE', 1.0);
this.drawQuad(-1,-1, 1, 1);
}
}
var renderer = null;
function configureRenderer() {
const runBenchmark = window.location.search.indexOf('benchmark') > 0;
const canvas = document.getElementById('canvas');
if (!runBenchmark) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
try {
renderer = new ZoomRenderer(canvas);
} catch (e) {
alert('Inialization failed: ' + e);
return;
}
if (!runBenchmark) {
return renderer.render();
}
var animCount = 0;
var lastTime = 0;
var avgFPS = 0;
const callback = function(animTime) {
if (lastTime > 0) {
const curFPS = 1000.0/(animTime - lastTime);
avgFPS += (curFPS - avgFPS) / animCount;
}
lastTime = animTime;
renderer.render();
renderer.adjustScaleWithInvariantPoint(.96, 591.7, 400);
if (animCount++ == 256) {
return console.log("Average FPS is " + avgFPS);
}
window.requestAnimationFrame(callback);
};
window.requestAnimationFrame(callback);
}
</script>
<body onLoad="configureRenderer();">
<H1>Mandelbrot Set rendered in fragment shader</H1>
<canvas id="canvas" width="1024px" height="1024px"></canvas>
</body>
</html>