-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjulia.html
430 lines (393 loc) · 13 KB
/
julia.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
<html>
<head>
<title>Julia 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="juliaFS">
precision highp float;
varying vec2 pos;
uniform vec2 center, step, c;
uniform int numSteps;
uniform int numDecomps;
const int maxNumSteps = 16384;
float sqrdistance(vec2 val) {
return val.x*val.x+val.y*val.y;
}
vec2 juliaStep(vec2 z) {
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 step, int numSteps) {
if (numDecomps > 1) {
int idx = int(floor((3.1415926 + atan(z.y, z.x)) * float(numDecomps) / 6.2833852));
return getPaletteColor(idx);
}
return vec4(log(sqrdistance(z))/3.0, float(step)/float(numSteps), abs(atan(z.y, z.x))/3.0, 1);
}
void main(void) {
vec2 z = 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 = juliaStep(z);
}
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('webgl');
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);
}
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', 'juliaFS'].map(_ => ctx.compileShaderById(_)));
this._ctx = ctx;
this._juliaProgram = prog;
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;
const decompMatch = window.location.search.match(/[?&]numDecomp=(\d+)/);
this._numDecomps = decompMatch ? Number(decompMatch[1]) : 0;
const cMatch = window.location.search.match(/[?&]c=(-?\d+\.\d+)([+-]\d+\.\d+)i/);
if (cMatch) {
this._c = new Point(Number(cMatch[1]), Number(cMatch[2]));
} else {
//this._c = new Point(-0.7269, 0.1889);
//this._c = new Point(-0.4, 0.6);
this._c = new Point(0.27334, 0.00742);
}
const cValue = document.getElementById('cValue');
if (cValue) {
cValue.innerHTML = " (c=" + this._c.x + (this._c.y < 0 ? "" : "+") + this._c.y + "i)";
}
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]);
}
render() {
const ctx = this._ctx;
const scale = this._scale;
const step = this._halfCanvasDim.mul(scale);
ctx.getGLContext().useProgram(this._juliaProgram);
ctx.setUniform2f('center', this._center.x, this._center.y);
ctx.setUniform2f('step', step.x, step.y);
ctx.setUniform2f('c', this._c.x, this._c.y);
ctx.setUniform1i('numSteps', this._numSteps);
ctx.setUniform1i('numDecomps', this._numDecomps);
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>Julia Set rendered in fragment shader<div id="cValue" style="display:inline;"/></H1>
<canvas id="canvas" width="1024px" height="1024px"></canvas>
</body>
</html>